@lpdjs/firestore-repo-service 2.6.42 → 2.6.44

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.
@@ -1,4 +1,4 @@
1
- # @lpdjs/firestore-repo-service (v2.6.42) — full documentation
1
+ # @lpdjs/firestore-repo-service (v2.6.44) — full documentation
2
2
 
3
3
  > ⚡ Type-safe Firestore ORM with auto-generated repositories, advanced queries, relations with typed select, pagination with include, batch/bulk operations, aggregations and transactions.
4
4
 
package/dist/llms.txt CHANGED
@@ -1,4 +1,4 @@
1
- # @lpdjs/firestore-repo-service (v2.6.42)
1
+ # @lpdjs/firestore-repo-service (v2.6.44)
2
2
 
3
3
  > ⚡ Type-safe Firestore ORM with auto-generated repositories, advanced queries, relations with typed select, pagination with include, batch/bulk operations, aggregations and transactions.
4
4
 
@@ -1,4 +1,4 @@
1
- 'use strict';var crypto=require('crypto'),zod=require('zod'),firestore=require('firebase-admin/firestore'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var re=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Qe=Object.prototype.hasOwnProperty;var Ve=(e,t)=>()=>(e&&(t=e(e=0)),t);var Xe=(e,t)=>{for(var n in t)re(e,n,{get:t[n],enumerable:true});},Ye=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Je(t))!Qe.call(e,i)&&i!==n&&re(e,i,{get:()=>t[i],enumerable:!(s=We(t,i))||s.enumerable});return e};var et=e=>Ye(re({},"__esModule",{value:true}),e);var Ke={};Xe(Ke,{DEFAULT_HTML_CSP:()=>_e,securityHeaders:()=>_t});function _t(e={}){let t=e.csp===void 0?_e:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,s=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,i=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(a,c,u)=>{typeof c?.setHeader=="function"&&(c.setHeader("X-Content-Type-Options","nosniff"),n&&c.setHeader("X-Frame-Options",n),s&&c.setHeader("Referrer-Policy",s),i&&c.setHeader("Cache-Control",i),t&&c.setHeader("Content-Security-Policy",t)),await u();}}var Be,Me,_e,Le=Ve(()=>{Be="https://cdn.jsdelivr.net",Me="https://www.gstatic.com",_e=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Be} ${Me}`,`style-src 'self' 'unsafe-inline' ${Be}`,`connect-src 'self' ${Me} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var ge="preserve";function we(){return ge}function tt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function be(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(tt(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function xe(e){return e}var rt=new Set(["<","<=",">",">=","!="]),ot=new Set(["array-contains","array-contains-any"]);function se(e){return e==="desc"?"DESCENDING":"ASCENDING"}function st(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function it(e,t,n,s,i){let a=[],c=new Set;for(let f of s)if(f.op==="=="||f.op==="in"||f.op==="not-in"){if(c.has(f.field))continue;c.add(f.field),a.push({fieldPath:f.field,order:"ASCENDING"});}for(let f of s)if(ot.has(f.op)){if(c.has(f.field))continue;c.add(f.field),a.push({fieldPath:f.field,arrayConfig:"CONTAINS"});}for(let f of s)if(rt.has(f.op)){if(c.has(f.field))continue;c.add(f.field);let g=i?.field===f.field?se(i.dir):"ASCENDING";a.push({fieldPath:f.field,order:g});}if(i&&!c.has(i.field)&&a.push({fieldPath:i.field,order:se(i.dir)}),a.length===1&&n)return dt(e,t,a[0]);let u=i&&a.some(f=>f.fieldPath===i.field)?se(i.dir):"ASCENDING";return a.push({fieldPath:"__name__",order:u}),at(e,t,n,a)}function at(e,t,n,s,i="(default)"){let a=`projects/${e}/databases/${i}/collectionGroups/${t}/indexes/_`,c=[...ce(1,a),...Q(2,n?2:1)];for(let g of s)c.push(...Se(3,Re(g)));let u=i==="(default)"?"-default-":i,f=encodeURIComponent(ve(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${u}/indexes?create_composite=${f}`}function ct(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function ie(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function ae(e,t){return e<<3|t}function ce(e,t){let n=Array.from(new TextEncoder().encode(t));return [ae(e,2),...ie(n.length),...n]}function Q(e,t){return [ae(e,0),...ie(t)]}function Se(e,t){return [ae(e,2),...ie(t.length),...t]}function Re(e){let t=[...ce(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Q(3,1)):t.push(...Q(2,e.order==="DESCENDING"?2:1)),t}function ve(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function dt(e,t,n,s="(default)"){let i=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,a=[...ce(1,i),...Q(2,2),...Se(3,Re(n))],c=s==="(default)"?"-default-":s,u=encodeURIComponent(ve(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes/automatic?create_exemption=${u}`}function ut(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let i of n)if(typeof i=="string"&&i.length>0)return i;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function pt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Ae(e,t){let n=e??{},s=pt(e),i;if(s&&(i=n.message?ct(n.message):void 0,!i)){let a=ut(t.ref);if(a){let c=st(t.path);i=it(a,c,t.isGroup,t.filters,t.sort);}}return {type:s?"index":"error",message:s?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:i}}function pe(e,t,n=200){let s=xe(t);return e.json(s,n)}function _(e,t,n,s=200){return pe(e,{success:true,data:t,meta:n},s)}function b(e,t,n=400){return pe(e,{success:false,error:t},n)}function de(e,t,n,s,i){let a=Ae(t,n),c=a.type==="index",u=c?424:500,g={success:false,error:c?a.message:i&&t instanceof Error?t.message:s};return c&&(g.errorType="index",a.indexUrl&&(g.indexUrl=a.indexUrl)),pe(e,g,u)}var ue="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ke(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let s=t[n];s>=ue.length*4||(e+=ue.charAt(s%ue.length));}}return e}function L(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(s=>be(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,i={};for(let[a,c]of Object.entries(s))i[a]=L(c);return zod.z.object(i)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return zod.z.array(L(s))}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(s)return L(s).optional()}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(s)return L(s).nullable()}if(n==="ZodDefault"||n==="default"){let s=t.innerType,i=t.defaultValue;if(s){let a=L(s);return typeof i=="function"?a.default(i()):a.default(i)}}return e}function ft(e,t,n=[]){let s=e.shape,i={},a=t&&t.length>0?t:Object.keys(s);for(let c of a){if(n.includes(c))continue;let u=c.split(".")[0];u&&s[u]&&(i[u]=s[u]);}return zod.z.object(i)}function V(e,t,n,s=false,i=[]){try{let a=ft(e,n,i),c=s?a.partial():a;return {success:!0,data:(we()==="normalize"?L(c):c).parse(t)}}catch(a){return a instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${a.issues.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function yt(e,t){let n=[],s=t?new Set(t):null,i={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[a,c]of Object.entries(e)){if(c===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(a))continue;let u=Array.isArray(c)?c[0]:c;if(u===void 0||u==="")continue;let f=a.match(/^(\w+)__(\w+)$/),g,v="==";if(f&&f[1]&&f[2]){g=f[1];let T=f[2];if(i[T])v=i[T];else continue}else if(!f)g=a;else continue;if(s&&!s.has(g))continue;let k=u;v==="in"||v==="not-in"||v==="array-contains-any"?k=u.split(",").map(T=>Oe(T.trim())):k=Oe(u),n.push({field:g,op:v,value:k});}return n}function Oe(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 X(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Ee(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let s=typeof n.docPath=="string"?n.docPath:void 0,i=typeof n.docId=="string"?n.docId:void 0;try{let a=e.repo.ref,c=a?.firestore;if(s&&c&&typeof c.doc=="function"){let u=await c.doc(s).get();if(u.exists)return u}if(i&&i.includes("/")&&c&&typeof c.doc=="function"){let u=await c.doc(i).get();if(u.exists)return u}if(i&&typeof a.doc=="function"){let u=await a.doc(i).get();if(u.exists)return u}return}catch{return}}function Te(e,t,n){async function s(d,r,y,o){if(!r.rules)return true;let l=r.rules?.[y];if(!l)return b(d,`Operation "${y}" is not allowed for this repository`,403),false;try{return await l(o)?!0:b(d,"Forbidden",403)}catch(m){let h=n&&m instanceof Error?m.message:"Forbidden";return b(d,h,403)}}async function i(d,r,y,o){if(!d.rules)return o;let l=d.rules?.filter;if(!l)return o;let m=[];for(let h of o)try{await l({user:r,doc:h,params:y})&&m.push(h);}catch{}return m}function a(d){return d.get("user")??d.get("docsUser")??null}function c(d,r){if(!d){let y=r.req.path.split("/");for(let o of y)if(e[o]){d=o;break}}return !d||!e[d]?null:e[d]??null}function u(d,r){if(!r)return;let y=d[r];if(typeof y!="string"||!y)return;let o=y.split("/").filter(Boolean),l=[];for(let m=1;m<o.length;m+=2)l.push(o[m]);return l.length>0?l:void 0}async function f(d,r){let y=`by${d.documentKey.charAt(0).toUpperCase()}${d.documentKey.slice(1)}`,o=d.repo.get[y];if(typeof o=="function")try{let m=await o(r);if(m)return m}catch{}return (await d.repo.query.by({where:[[d.documentKey,"==",r]],limit:1}))[0]??null}async function g(d){let r=d.c,y=r.req.param(),o=c(y.repoName,r);if(!o)return b(r,"Repository not found",404);let l=a(r);if(!await s(r,o,"list",{user:l,query:r.req.query(),params:y}))return;let m=[],h;try{let p=r.req.query(),w=Math.min(Number(p.pageSize)||o.pageSize,100),x=p.cursor,R=p.direction?.toLowerCase()==="prev"?"prev":"next",A=p.orderBy,P=p.orderDir?.toLowerCase()==="desc"?"desc":"asc",F=p.select,I=F?F.split(",").map($=>$.trim()):void 0,E;o.allowedIncludes&&p.includes&&(E=(typeof p.includes=="string"?p.includes.split(",").map(M=>M.trim()):Array.isArray(p.includes)?p.includes:[]).filter(M=>typeof M=="string"&&o.allowedIncludes.includes(M)),E?.length===0&&(E=void 0));let j=yt(p,o.filterableFields);m=j.map($=>({field:$.field,op:$.op,value:String($.value??"")})),A&&(h={field:A,dir:P});let z={pageSize:w,direction:R};if(x)try{let $=typeof x=="string"?JSON.parse(x):x;z.cursor=await Ee(o,$);}catch{}if(A){if(o.orderableFields&&!o.orderableFields.includes(A))return b(r,`Field not orderable: ${A}`,400);z.orderBy=[{field:A,direction:P}];}if(j.length>0){z.where=[];for(let $ of j){let M=$.value,te=o.schema?.shape?.[$.field];if(te&&typeof te.safeParse=="function"){let ne=te.safeParse($.value);if(ne.success)M=ne.data;else {let Ze=ne.error.issues.map(Ge=>Ge.message).join(", ");return b(r,`Invalid filter value for '${$.field}': ${Ze}`,400)}}z.where.push([$.field,$.op,M]);}}I&&(z.select=I),E&&(z.include=E);let K=await o.repo.query.paginate(z),Ue={items:await i(o,a(r),y,K.data),hasNextPage:K.hasNextPage,hasPrevPage:K.hasPrevPage,nextCursor:X(K.nextCursor),prevCursor:X(K.prevCursor)};return _(r,Ue,{pageSize:w,hasMore:K.hasNextPage})}catch(p){de(r,p,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:m,sort:h},"Failed to fetch documents",n);}}async function v(d){let r=d.c,y=r.req.param(),o=c(y.repoName,r);if(!o)return b(r,"Repository not found",404);let l=a(r);if(!await s(r,o,"list",{user:l,query:d.input||{},params:y}))return;let m=[],h;try{let p=d.input||{},w=Math.min(p.pageSize||o.pageSize,100),x=p.direction==="prev"?"prev":"next";p.where&&(m=p.where.map(I=>({field:String(I[0]),op:I[1],value:String(I[2]??"")}))),p.orderBy&&p.orderBy[0]&&(h={field:p.orderBy[0].field,dir:p.orderBy[0].direction==="desc"?"desc":"asc"});let R={pageSize:w,direction:x};if(p.cursor)try{let I=typeof p.cursor=="string"?JSON.parse(p.cursor):p.cursor;R.cursor=await Ee(o,I);}catch{}if(o.allowedIncludes&&p.includes&&p.includes.length>0){let I=p.includes.filter(E=>typeof E=="string"?o.allowedIncludes.includes(E):typeof E=="object"&&E!==null&&"relation"in E&&typeof E.relation=="string"?o.allowedIncludes.includes(E.relation):!1);I.length>0&&(R.include=I);}if(p.where&&p.where.length>0){if(o.filterableFields){let I=new Set(o.filterableFields),E=p.where.filter(j=>!I.has(j[0]));if(E.length>0){b(r,`Fields not filterable: ${E.map(j=>j[0]).join(", ")}`,400);return}}R.where=p.where;}if(p.orWhere&&p.orWhere.length>0){if(o.filterableFields){let I=new Set(o.filterableFields),E=p.orWhere.filter(j=>!I.has(j[0]));if(E.length>0){b(r,`Fields not filterable: ${E.map(j=>j[0]).join(", ")}`,400);return}}R.orWhere=p.orWhere;}if(p.orWhereGroups&&p.orWhereGroups.length>0){if(o.filterableFields){let I=new Set(o.filterableFields);for(let E of p.orWhereGroups){let j=E.filter(z=>!I.has(z[0]));if(j.length>0){b(r,`Fields not filterable: ${j.map(z=>z[0]).join(", ")}`,400);return}}}R.orWhereGroups=p.orWhereGroups;}if(p.orderBy&&p.orderBy.length>0){if(o.orderableFields){let I=new Set(o.orderableFields),E=p.orderBy.filter(j=>!I.has(j.field));if(E.length>0){b(r,`Fields not orderable: ${E.map(j=>j.field).join(", ")}`,400);return}}R.orderBy=p.orderBy;}p.select&&p.select.length>0&&(R.select=p.select);let A=await o.repo.query.paginate(R),F={items:await i(o,a(r),y,A.data),hasNextPage:A.hasNextPage,hasPrevPage:A.hasPrevPage,nextCursor:X(A.nextCursor),prevCursor:X(A.prevCursor)};return _(r,F,{pageSize:w,hasMore:A.hasNextPage})}catch(p){de(r,p,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:m,sort:h},"Failed to query documents",n);}}async function k(d){let r=d.c,y=r.req.param(),o=c(y.repoName,r);if(!o)return b(r,"Repository not found",404);let l=y.id;if(!l)return b(r,"Document ID required",400);try{let m=await f(o,l);if(!m)return b(r,"Document not found",404);let h=a(r);if(!await s(r,o,"get",{user:h,doc:m,params:y}))return;if(o.rules?.filter)try{if(!await o.rules.filter({user:h,doc:m,params:y}))return b(r,"Document not found",404)}catch{return b(r,"Document not found",404)}return _(r,m)}catch(m){de(r,m,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:[{field:o.documentKey,op:"==",value:l}]},"Failed to fetch document",n);}}async function T(d){let r=d.c,y=r.req.param(),o=c(y.repoName,r);if(!o)return b(r,"Repository not found",404);try{let l=d.input||{},m=a(r);if(!await s(r,o,"create",{user:m,body:l,params:y}))return;let h=V(o.schema,l,o.createFields,!1,o.systemKeys);if(!h.success)return b(r,h.error,400);if(o.validate){let w=await o.validate(h.data,"create");if(w)return b(r,w,400)}let p;if(o.isGroup&&o.parentKeys&&o.parentKeys.length>0){let w={...h.data};o.createdKey&&(w[o.createdKey]=new Date);let x=o.parentKeys.filter(P=>!w[P]);if(x.length>0){b(r,`Missing parent key(s) for subcollection create: ${x.join(", ")}`,400);return}let R=o.parentKeys.map(P=>w[P]),A=w[o.documentKey]||ke();p=await o.repo.set(...R,A,w);}else p=await o.repo.create(h.data);return _(r,p,void 0,201)}catch(l){let m=n&&l instanceof Error?l.message:"Failed to create document";return b(r,m,500)}}async function q(d,r){let y=d.c,o=y.req.param(),l=c(o.repoName,y);if(!l)return b(y,"Repository not found",404);let m=o.id;if(!m)return b(y,"Document ID required",400);try{let h=d.input||{},p=await f(l,m);if(!p)return b(y,"Document not found",404);let w=a(y);if(!await s(y,l,"update",{user:w,doc:p,body:h,params:o}))return;let x=V(l.schema,h,l.mutableFields,r,l.systemKeys);if(!x.success)return b(y,x.error,400);if(l.validate){let P=await l.validate(x.data,"update");if(P)return b(y,P,400)}let R=u(p,l.pathKey)??[m],A=await l.repo.update(...R,x.data);return _(y,A)}catch(h){let p=n&&h instanceof Error?h.message:"Failed to update document";return b(y,p,500)}}async function C(d){let r=d.c,y=r.req.param(),o=c(y.repoName,r);if(!o)return b(r,"Repository not found",404);if(!o.allowDelete)return b(r,"Delete not allowed for this repository",403);let l=y.id;if(!l)return b(r,"Document ID required",400);try{let m=await f(o,l);if(!m)return b(r,"Document not found",404);let h=a(r);if(!await s(r,o,"delete",{user:h,doc:m,params:y}))return;let p=u(m,o.pathKey)??[l];return await o.repo.delete(...p),_(r,{deleted:!0})}catch(m){let h=n&&m instanceof Error?m.message:"Failed to delete document";return b(r,h,500)}}function O(d){return d.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"})}async function S(d){let r=d.c,y=r.req.param(),o=c(y.repoName,r);if(!o)return b(r,"Repository not found",404);try{let l=d.input||{};if(!Array.isArray(l.operations))return b(r,"operations array is required",400);let m=a(r),h=o.repo.batch.create(),p=[];for(let w of l.operations){if(!w.type||!["create","update","delete"].includes(w.type))return b(r,"Invalid operation type",400);if(w.type==="create"){if(!await s(r,o,"create",{user:m,body:w.data,params:y}))return;let x=V(o.schema,w.data,o.createFields,!1,o.systemKeys);if(!x.success)return b(r,x.error,400);let R=w.data[o.documentKey]||ke(),A={...x.data};if(o.createdKey&&(A[o.createdKey]=new Date),o.isGroup&&o.parentKeys){let P=o.parentKeys.map(F=>A[F]);h.set(...P,R,A);}else h.set(R,A);p.push({op:"create",id:R});}else if(w.type==="update"){if(!w.id)return b(r,"id required for update",400);let x=await f(o,w.id);if(!x)return b(r,`Document ${w.id} not found`,404);if(!await s(r,o,"update",{user:m,doc:x,body:w.data,params:y}))return;let R=V(o.schema,w.data,o.mutableFields,!0,o.systemKeys);if(!R.success)return b(r,R.error,400);let A=u(x,o.pathKey)??[w.id];h.update(...A,R.data),p.push({op:"update",id:w.id});}else if(w.type==="delete"){if(!o.allowDelete)return b(r,"Delete not allowed",403);if(!w.id)return b(r,"id required for delete",400);let x=await f(o,w.id);if(!x)return b(r,`Document ${w.id} not found`,404);if(!await s(r,o,"delete",{user:m,doc:x,params:y}))return;let R=u(x,o.pathKey)??[w.id];h.delete(...R),p.push({op:"delete",id:w.id});}}return await h.commit(),_(r,{results:p})}catch(l){let m=n&&l instanceof Error?l.message:"Batch operation failed";return b(r,m,500)}}return {handleList:g,handleQuery:v,handleGet:k,handleCreate:T,handleUpdate:q,handleDelete:C,handleBatch:S,handleOptions:O}}function le(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&Object.assign(t.jsonSchema,n);let s=t.zodSchema?._zod?.def;s&&(s.type==="date"&&!t.jsonSchema.type?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):s.type==="bigint"&&!t.jsonSchema.type&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function H(e){return {$ref:`#/components/schemas/${e}`}}function D(e){return {description:e,content:{"application/json":{schema:H("ErrorResponse")}}}}function U(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Ce(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 ht(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 gt(e){let t=e.filterableFields??Object.keys(e.schema.shape),n=["eq","ne","lt","lte","gt","gte","in","nin","contains"],s=[];for(let i of t){s.push({name:i,in:"query",schema:{type:"string"},description:`Filter by ${i} (equality)`});for(let a of n)s.push({name:`${i}__${a}`,in:"query",schema:{type:"string"},description:`Filter ${i} with operator ${a}`});}return s}function wt(){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 bt(e,t,n,s,i){let a={},c=e.name,u=`${t}/${e.name}`,f=`${u}/{${e.documentKey}}`,g={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[u]={get:{operationId:`list${B(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[c],parameters:[...ht(e),...gt(e)],responses:{200:Ce(H(n)),500:D("Internal server error")}},post:{operationId:`create${B(e.name)}`,summary:`Create a ${N(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:H(s??n)}}},responses:{201:U("Document created",H(n)),400:D("Validation error"),500:D("Internal server error")}}},a[`${u}/query`]={post:{operationId:`query${B(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:H("QueryRequestBody")}}},responses:{200:Ce(H(n)),400:D("Invalid query"),500:D("Internal server error")}}},a[`${u}/batch`]={post:{operationId:`batch${B(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:H(`${n}BatchRequest`)}}},responses:{200:U("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:D("Validation error"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}}};let v={};return v.get={operationId:`get${B(N(e.name))}`,summary:`Get a single ${N(e.name)}`,tags:[c],parameters:[g],responses:{200:U("Document found",H(n)),404:D("Document not found"),500:D("Internal server error")}},v.put={operationId:`update${B(N(e.name))}`,summary:`Update a ${N(e.name)} (full replace)`,tags:[c],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:H(i??n)}}},responses:{200:U("Document updated",H(n)),400:D("Validation error"),404:D("Document not found"),500:D("Internal server error")}},v.patch={operationId:`patch${B(N(e.name))}`,summary:`Partially update a ${N(e.name)}`,tags:[c],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:{allOf:[H(i??n)],description:"All fields are optional for partial updates"}}}},responses:{200:U("Document patched",H(n)),400:D("Validation error"),404:D("Document not found"),500:D("Internal server error")}},e.allowDelete&&(v.delete={operationId:`delete${B(N(e.name))}`,summary:`Delete a ${N(e.name)}`,tags:[c],parameters:[g],responses:{200:U("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:D("Document not found"),500:D("Internal server error")}}),a[f]=v,a}function ye(e,t,n={}){let{title:s="CRUD API",version:i="1.0.0",description:a,servers:c,auth:u=false}=n,f=t==="/"?"":t.replace(/\/$/,""),g={},v={},k=[];g.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},g.QueryRequestBody=wt();for(let[O,S]of Object.entries(e)){let d=B(N(O)),r=`${d}Create`,y=`${d}Update`;g[d]=le(S.schema);let o=x=>{let R=x&&x.length>0?x:Object.keys(S.schema.shape),A={};for(let P of R){let F=P.split(".")[0];F&&S.schema.shape[F]&&!S.systemKeys.includes(F)&&(A[F]=S.schema.shape[F]);}return A},l=null,m=o(S.createFields);Object.keys(m).length>0&&(g[r]=le(zod.z.object(m)),l=r);let h=null,p=o(S.mutableFields);Object.keys(p).length>0&&(g[y]=le(zod.z.object(p)),h=y),g[`${d}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:H(l??d)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[H(h??d)],description:"Partial updates allowed"}},required:["type","id","data"]},...S.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let w=bt(S,f,d,l,h);Object.assign(v,w),k.push({name:O,description:`Operations on ${O} (collection: ${S.path})`});}let T={},q;return u==="basic"?(T.basicAuth={type:"http",scheme:"basic"},q=[{basicAuth:[]}]):u==="bearer"&&(T.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},q=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:i,...a?{description:a}:{}},...c&&c.length>0?{servers:c}:{},paths:v,components:{schemas:g,...Object.keys(T).length>0?{securitySchemes:T}:{}},...q?{security:q}:{},tags:k}}function B(e){return e.charAt(0).toUpperCase()+e.slice(1)}function N(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var Z=class extends Error{constructor(n,s){super("Request validation failed");this.zodError=n;this.source=s;this.statusCode=400;this.name="ValidationError";}};var W=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},J=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Pe(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Ie(e,t){return t instanceof Z?e.json({success:false,error:"Validation failed",issues:Pe(t.zodError)},400):t instanceof W?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof J?e.json({success:false,error:"Output validation failed",issues:Pe(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var De="Successful response",je="Error response";function At(e){return e==="get"?"query":"json"}function kt(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Ot(e){if(typeof e.safeParse=="function")return {description:je,schema:e};let t=e;return {description:t.description??je,schema:t.schema}}function $e(e,t,n,s){let i=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[u,f]of Object.entries(n.securitySchemes))i.registerComponent("securitySchemes",u,f);for(let u of e){let f=u.method,g=u.source??At(f),v=Ct(t,u.path??"/"),k=u.status??200,T=Et(f,g,u.input),q=qe(g,u.input,"query"),C=qe(g,u.input,"param"),O=Pt(f,v),S=kt(u.output,s),d={[k]:S?{description:De,content:{"application/json":{schema:S}}}:{description:De}};if(s?.errors)for(let[r,y]of Object.entries(s.errors)){let{description:o,schema:l}=Ot(y);d[r]=l?{description:o,content:{"application/json":{schema:l}}}:{description:o};}i.registerPath({method:f,path:Tt(v),operationId:O,summary:u.summary,description:u.description,tags:u.tags,deprecated:u.deprecated,security:u.security,request:{...q?{query:q}:{},...C?{params:C}:{},...T?{body:T}:{}},responses:d});}return new zodToOpenapi.OpenApiGeneratorV31(i.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function Et(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function qe(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Tt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Ct(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,i=`${n}${s}`;return i===""?"/":i}function Pt(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function He(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
1
+ 'use strict';var crypto=require('crypto'),zod=require('zod'),firestore=require('firebase-admin/firestore'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),hono=require('hono'),nodeServer=require('@hono/node-server'),async_hooks=require('async_hooks');var ie=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var et=Object.prototype.hasOwnProperty;var tt=(e,t)=>()=>(e&&(t=e(e=0)),t);var nt=(e,t)=>{for(var n in t)ie(e,n,{get:t[n],enumerable:true});},rt=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ye(t))!et.call(e,i)&&i!==n&&ie(e,i,{get:()=>t[i],enumerable:!(s=Xe(t,i))||s.enumerable});return e};var ot=e=>rt(ie({},"__esModule",{value:true}),e);var Ge={};nt(Ge,{DEFAULT_HTML_CSP:()=>Ze,securityHeaders:()=>Zt});function Zt(e={}){let t=e.csp===void 0?Ze:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,s=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,i=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(c,a,u)=>{typeof a?.setHeader=="function"&&(a.setHeader("X-Content-Type-Options","nosniff"),n&&a.setHeader("X-Frame-Options",n),s&&a.setHeader("Referrer-Policy",s),i&&a.setHeader("Cache-Control",i),t&&a.setHeader("Content-Security-Policy",t)),await u();}}var Ke,Le,Ze,We=tt(()=>{Ke="https://cdn.jsdelivr.net",Le="https://www.gstatic.com",Ze=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Ke} ${Le}`,`style-src 'self' 'unsafe-inline' ${Ke}`,`connect-src 'self' ${Le} https://*.googleapis.com https://*.firebaseio.com https://identitytoolkit.googleapis.com`,"img-src 'self' data:","font-src 'self' data:","frame-ancestors 'none'","base-uri 'self'","form-action 'self'"].join("; ");});var Se="preserve";function ve(){return Se}function st(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Re(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(st(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Ae(e){return e}var at=new Set(["<","<=",">",">=","!="]),ct=new Set(["array-contains","array-contains-any"]);function ce(e){return e==="desc"?"DESCENDING":"ASCENDING"}function dt(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function ut(e,t,n,s,i){let c=[],a=new Set;for(let f of s)if(f.op==="=="||f.op==="in"||f.op==="not-in"){if(a.has(f.field))continue;a.add(f.field),c.push({fieldPath:f.field,order:"ASCENDING"});}for(let f of s)if(ct.has(f.op)){if(a.has(f.field))continue;a.add(f.field),c.push({fieldPath:f.field,arrayConfig:"CONTAINS"});}for(let f of s)if(at.has(f.op)){if(a.has(f.field))continue;a.add(f.field);let g=i?.field===f.field?ce(i.dir):"ASCENDING";c.push({fieldPath:f.field,order:g});}if(i&&!a.has(i.field)&&c.push({fieldPath:i.field,order:ce(i.dir)}),c.length===1&&n)return ft(e,t,c[0]);let u=i&&c.some(f=>f.fieldPath===i.field)?ce(i.dir):"ASCENDING";return c.push({fieldPath:"__name__",order:u}),pt(e,t,n,c)}function pt(e,t,n,s,i="(default)"){let c=`projects/${e}/databases/${i}/collectionGroups/${t}/indexes/_`,a=[...pe(1,c),...Y(2,n?2:1)];for(let g of s)a.push(...ke(3,Oe(g)));let u=i==="(default)"?"-default-":i,f=encodeURIComponent(Ee(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${u}/indexes?create_composite=${f}`}function lt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function de(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function ue(e,t){return e<<3|t}function pe(e,t){let n=Array.from(new TextEncoder().encode(t));return [ue(e,2),...de(n.length),...n]}function Y(e,t){return [ue(e,0),...de(t)]}function ke(e,t){return [ue(e,2),...de(t.length),...t]}function Oe(e){let t=[...pe(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Y(3,1)):t.push(...Y(2,e.order==="DESCENDING"?2:1)),t}function Ee(e){let t=String.fromCharCode(...e),n;if(typeof Buffer<"u")n=Buffer.from(e).toString("base64");else if(typeof btoa<"u")n=btoa(t);else throw new Error("No base64 encoder available");return n.replace(/=+$/,"")}function ft(e,t,n,s="(default)"){let i=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,c=[...pe(1,i),...Y(2,2),...ke(3,Oe(n))],a=s==="(default)"?"-default-":s,u=encodeURIComponent(Ee(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${u}`}function yt(e){let t=e,n=[t?.firestore?.projectId,t?.firestore?.app?.options?.projectId,t?.firestore?._settings?.projectId,t?.firestore?.databaseId?.projectId,t?._firestore?.projectId];for(let i of n)if(typeof i=="string"&&i.length>0)return i;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function mt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Te(e,t){let n=e??{},s=mt(e),i;if(s&&(i=n.message?lt(n.message):void 0,!i)){let c=yt(t.ref);if(c){let a=dt(t.path);i=ut(c,a,t.isGroup,t.filters,t.sort);}}return {type:s?"index":"error",message:s?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:i}}function ye(e,t,n=200){let s=Ae(t);return e.json(s,n)}function B(e,t,n,s=200){return ye(e,{success:true,data:t,meta:n},s)}function b(e,t,n=400){return ye(e,{success:false,error:t},n)}function le(e,t,n,s,i){let c=Te(t,n),a=c.type==="index",u=a?424:500,g={success:false,error:a?c.message:i&&t instanceof Error?t.message:s};return a&&(g.errorType="index",c.indexUrl&&(g.indexUrl=c.indexUrl)),ye(e,g,u)}var fe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Ce(){let e="";for(;e.length<20;){let t=crypto.randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let s=t[n];s>=fe.length*4||(e+=fe.charAt(s%fe.length));}}return e}function K(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return zod.z.preprocess(s=>Re(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,i={};for(let[c,a]of Object.entries(s))i[c]=K(a);return zod.z.object(i)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return zod.z.array(K(s))}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(s)return K(s).optional()}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(s)return K(s).nullable()}if(n==="ZodDefault"||n==="default"){let s=t.innerType,i=t.defaultValue;if(s){let c=K(s);return typeof i=="function"?c.default(i()):c.default(i)}}return e}function gt(e,t,n=[]){let s=e.shape,i={},c=t&&t.length>0?t:Object.keys(s);for(let a of c){if(n.includes(a))continue;let u=a.split(".")[0];u&&s[u]&&(i[u]=s[u]);}return zod.z.object(i)}function ee(e,t,n,s=false,i=[]){try{let c=gt(e,n,i),a=s?c.partial():c;return {success:!0,data:(ve()==="normalize"?K(a):a).parse(t)}}catch(c){return c instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${c.issues.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function wt(e,t){let n=[],s=t?new Set(t):null,i={eq:"==",ne:"!=",lt:"<",lte:"<=",gt:">",gte:">=",in:"in",nin:"not-in",contains:"array-contains",containsAny:"array-contains-any"};for(let[c,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(c))continue;let u=Array.isArray(a)?a[0]:a;if(u===void 0||u==="")continue;let f=c.match(/^(\w+)__(\w+)$/),g,R="==";if(f&&f[1]&&f[2]){g=f[1];let T=f[2];if(i[T])R=i[T];else continue}else if(!f)g=c;else continue;if(s&&!s.has(g))continue;let k=u;R==="in"||R==="not-in"||R==="array-contains-any"?k=u.split(",").map(T=>Pe(T.trim())):k=Pe(u),n.push({field:g,op:R,value:k});}return n}function Pe(e){if(e==="true")return true;if(e==="false")return false;if(e==="null"||e==="__null__")return null;let t=Number(e);return !isNaN(t)&&e!==""?t:e}function te(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Ie(e,t){if(!t)return;let n;if(typeof t=="string")try{n=JSON.parse(t);}catch{n=t.includes("/")?{docPath:t}:{docId:t};}else typeof t=="object"&&(n=t);if(!n)return;let s=typeof n.docPath=="string"?n.docPath:void 0,i=typeof n.docId=="string"?n.docId:void 0;try{let c=e.repo.ref,a=c?.firestore;if(s&&a&&typeof a.doc=="function"){let u=await a.doc(s).get();if(u.exists)return u}if(i&&i.includes("/")&&a&&typeof a.doc=="function"){let u=await a.doc(i).get();if(u.exists)return u}if(i&&typeof c.doc=="function"){let u=await c.doc(i).get();if(u.exists)return u}return}catch{return}}function De(e,t,n){async function s(d,r,y,o){if(!r.rules)return true;let l=r.rules?.[y];if(!l)return b(d,`Operation "${y}" is not allowed for this repository`,403),false;try{return await l(o)?!0:b(d,"Forbidden",403)}catch(m){let h=n&&m instanceof Error?m.message:"Forbidden";return b(d,h,403)}}async function i(d,r,y,o){if(!d.rules)return o;let l=d.rules?.filter;if(!l)return o;let m=[];for(let h of o)try{await l({user:r,doc:h,params:y})&&m.push(h);}catch{}return m}function c(d){return d.get("user")??d.get("docsUser")??null}function a(d,r){if(!d){let y=r.req.path.split("/");for(let o of y)if(e[o]){d=o;break}}return !d||!e[d]?null:e[d]??null}function u(d,r){if(!r)return;let y=d[r];if(typeof y!="string"||!y)return;let o=y.split("/").filter(Boolean),l=[];for(let m=1;m<o.length;m+=2)l.push(o[m]);return l.length>0?l:void 0}async function f(d,r){let y=`by${d.documentKey.charAt(0).toUpperCase()}${d.documentKey.slice(1)}`,o=d.repo.get[y];if(typeof o=="function")try{let m=await o(r);if(m)return m}catch{}return (await d.repo.query.by({where:[[d.documentKey,"==",r]],limit:1}))[0]??null}async function g(d){let r=d.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let l=c(r);if(!await s(r,o,"list",{user:l,query:r.req.query(),params:y}))return;let m=[],h;try{let p=r.req.query(),w=Math.min(Number(p.pageSize)||o.pageSize,100),x=p.cursor,v=p.direction?.toLowerCase()==="prev"?"prev":"next",A=p.orderBy,P=p.orderDir?.toLowerCase()==="desc"?"desc":"asc",_=p.select,I=_?_.split(",").map(q=>q.trim()):void 0,E;o.allowedIncludes&&p.includes&&(E=(typeof p.includes=="string"?p.includes.split(",").map(M=>M.trim()):Array.isArray(p.includes)?p.includes:[]).filter(M=>typeof M=="string"&&o.allowedIncludes.includes(M)),E?.length===0&&(E=void 0));let j=wt(p,o.filterableFields);m=j.map(q=>({field:q.field,op:q.op,value:String(q.value??"")})),A&&(h={field:A,dir:P});let F={pageSize:w,direction:v};if(x)try{let q=typeof x=="string"?JSON.parse(x):x;F.cursor=await Ie(o,q);}catch{}if(A){if(o.orderableFields&&!o.orderableFields.includes(A))return b(r,`Field not orderable: ${A}`,400);F.orderBy=[{field:A,direction:P}];}if(j.length>0){F.where=[];for(let q of j){let M=q.value,Q=o.schema?.shape?.[q.field];if(Q&&typeof Q.safeParse=="function"){let oe=Q.safeParse(q.value);if(oe.success)M=oe.data;else if(Array.isArray(q.value)){let V=[],X=!1,be="";for(let Qe of q.value){let se=Q.safeParse(Qe);if(se.success)V.push(se.data);else {X=!0,be=se.error.issues.map(Ve=>Ve.message).join(", ");break}}if(X)return b(r,`Invalid filter value for '${q.field}': ${be}`,400);M=V;}else {let V=oe.error.issues.map(X=>X.message).join(", ");return b(r,`Invalid filter value for '${q.field}': ${V}`,400)}}F.where.push([q.field,q.op,M]);}}I&&(F.select=I),E&&(F.include=E);let U=await o.repo.query.paginate(F),Je={items:await i(o,c(r),y,U.data),hasNextPage:U.hasNextPage,hasPrevPage:U.hasPrevPage,nextCursor:te(U.nextCursor),prevCursor:te(U.prevCursor)};return B(r,Je,{pageSize:w,hasMore:U.hasNextPage})}catch(p){le(r,p,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:m,sort:h},"Failed to fetch documents",n);}}async function R(d){let r=d.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let l=c(r);if(!await s(r,o,"list",{user:l,query:d.input||{},params:y}))return;let m=[],h;try{let p=d.input||{},w=Math.min(p.pageSize||o.pageSize,100),x=p.direction==="prev"?"prev":"next";p.where&&(m=p.where.map(I=>({field:String(I[0]),op:I[1],value:String(I[2]??"")}))),p.orderBy&&p.orderBy[0]&&(h={field:p.orderBy[0].field,dir:p.orderBy[0].direction==="desc"?"desc":"asc"});let v={pageSize:w,direction:x};if(p.cursor)try{let I=typeof p.cursor=="string"?JSON.parse(p.cursor):p.cursor;v.cursor=await Ie(o,I);}catch{}if(o.allowedIncludes&&p.includes&&p.includes.length>0){let I=p.includes.filter(E=>typeof E=="string"?o.allowedIncludes.includes(E):typeof E=="object"&&E!==null&&"relation"in E&&typeof E.relation=="string"?o.allowedIncludes.includes(E.relation):!1);I.length>0&&(v.include=I);}if(p.where&&p.where.length>0){if(o.filterableFields){let I=new Set(o.filterableFields),E=p.where.filter(j=>!I.has(j[0]));if(E.length>0){b(r,`Fields not filterable: ${E.map(j=>j[0]).join(", ")}`,400);return}}v.where=p.where;}if(p.orWhere&&p.orWhere.length>0){if(o.filterableFields){let I=new Set(o.filterableFields),E=p.orWhere.filter(j=>!I.has(j[0]));if(E.length>0){b(r,`Fields not filterable: ${E.map(j=>j[0]).join(", ")}`,400);return}}v.orWhere=p.orWhere;}if(p.orWhereGroups&&p.orWhereGroups.length>0){if(o.filterableFields){let I=new Set(o.filterableFields);for(let E of p.orWhereGroups){let j=E.filter(F=>!I.has(F[0]));if(j.length>0){b(r,`Fields not filterable: ${j.map(F=>F[0]).join(", ")}`,400);return}}}v.orWhereGroups=p.orWhereGroups;}if(p.orderBy&&p.orderBy.length>0){if(o.orderableFields){let I=new Set(o.orderableFields),E=p.orderBy.filter(j=>!I.has(j.field));if(E.length>0){b(r,`Fields not orderable: ${E.map(j=>j.field).join(", ")}`,400);return}}v.orderBy=p.orderBy;}p.select&&p.select.length>0&&(v.select=p.select);let A=await o.repo.query.paginate(v),_={items:await i(o,c(r),y,A.data),hasNextPage:A.hasNextPage,hasPrevPage:A.hasPrevPage,nextCursor:te(A.nextCursor),prevCursor:te(A.prevCursor)};return B(r,_,{pageSize:w,hasMore:A.hasNextPage})}catch(p){le(r,p,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:m,sort:h},"Failed to query documents",n);}}async function k(d){let r=d.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let l=y.id;if(!l)return b(r,"Document ID required",400);try{let m=await f(o,l);if(!m)return b(r,"Document not found",404);let h=c(r);if(!await s(r,o,"get",{user:h,doc:m,params:y}))return;if(o.rules?.filter)try{if(!await o.rules.filter({user:h,doc:m,params:y}))return b(r,"Document not found",404)}catch{return b(r,"Document not found",404)}return B(r,m)}catch(m){le(r,m,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:[{field:o.documentKey,op:"==",value:l}]},"Failed to fetch document",n);}}async function T(d){let r=d.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);try{let l=d.input||{},m=c(r);if(!await s(r,o,"create",{user:m,body:l,params:y}))return;let h=ee(o.schema,l,o.createFields,!1,o.systemKeys);if(!h.success)return b(r,h.error,400);if(o.validate){let w=await o.validate(h.data,"create");if(w)return b(r,w,400)}let p;if(o.isGroup&&o.parentKeys&&o.parentKeys.length>0){let w={...h.data};o.createdKey&&(w[o.createdKey]=new Date);let x=o.parentKeys.filter(P=>!w[P]);if(x.length>0){b(r,`Missing parent key(s) for subcollection create: ${x.join(", ")}`,400);return}let v=o.parentKeys.map(P=>w[P]),A=w[o.documentKey]||Ce();p=await o.repo.set(...v,A,w);}else p=await o.repo.create(h.data);return B(r,p,void 0,201)}catch(l){let m=n&&l instanceof Error?l.message:"Failed to create document";return b(r,m,500)}}async function $(d,r){let y=d.c,o=y.req.param(),l=a(o.repoName,y);if(!l)return b(y,"Repository not found",404);let m=o.id;if(!m)return b(y,"Document ID required",400);try{let h=d.input||{},p=await f(l,m);if(!p)return b(y,"Document not found",404);let w=c(y);if(!await s(y,l,"update",{user:w,doc:p,body:h,params:o}))return;let x=ee(l.schema,h,l.mutableFields,r,l.systemKeys);if(!x.success)return b(y,x.error,400);if(l.validate){let P=await l.validate(x.data,"update");if(P)return b(y,P,400)}let v=u(p,l.pathKey)??[m],A=await l.repo.update(...v,x.data);return B(y,A)}catch(h){let p=n&&h instanceof Error?h.message:"Failed to update document";return b(y,p,500)}}async function C(d){let r=d.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);if(!o.allowDelete)return b(r,"Delete not allowed for this repository",403);let l=y.id;if(!l)return b(r,"Document ID required",400);try{let m=await f(o,l);if(!m)return b(r,"Document not found",404);let h=c(r);if(!await s(r,o,"delete",{user:h,doc:m,params:y}))return;let p=u(m,o.pathKey)??[l];return await o.repo.delete(...p),B(r,{deleted:!0})}catch(m){let h=n&&m instanceof Error?m.message:"Failed to delete document";return b(r,h,500)}}function O(d){return d.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400"})}async function S(d){let r=d.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);try{let l=d.input||{};if(!Array.isArray(l.operations))return b(r,"operations array is required",400);let m=c(r),h=o.repo.batch.create(),p=[];for(let w of l.operations){if(!w.type||!["create","update","delete"].includes(w.type))return b(r,"Invalid operation type",400);if(w.type==="create"){if(!await s(r,o,"create",{user:m,body:w.data,params:y}))return;let x=ee(o.schema,w.data,o.createFields,!1,o.systemKeys);if(!x.success)return b(r,x.error,400);let v=w.data[o.documentKey]||Ce(),A={...x.data};if(o.createdKey&&(A[o.createdKey]=new Date),o.isGroup&&o.parentKeys){let P=o.parentKeys.map(_=>A[_]);h.set(...P,v,A);}else h.set(v,A);p.push({op:"create",id:v});}else if(w.type==="update"){if(!w.id)return b(r,"id required for update",400);let x=await f(o,w.id);if(!x)return b(r,`Document ${w.id} not found`,404);if(!await s(r,o,"update",{user:m,doc:x,body:w.data,params:y}))return;let v=ee(o.schema,w.data,o.mutableFields,!0,o.systemKeys);if(!v.success)return b(r,v.error,400);let A=u(x,o.pathKey)??[w.id];h.update(...A,v.data),p.push({op:"update",id:w.id});}else if(w.type==="delete"){if(!o.allowDelete)return b(r,"Delete not allowed",403);if(!w.id)return b(r,"id required for delete",400);let x=await f(o,w.id);if(!x)return b(r,`Document ${w.id} not found`,404);if(!await s(r,o,"delete",{user:m,doc:x,params:y}))return;let v=u(x,o.pathKey)??[w.id];h.delete(...v),p.push({op:"delete",id:w.id});}}return await h.commit(),B(r,{results:p})}catch(l){let m=n&&l instanceof Error?l.message:"Batch operation failed";return b(r,m,500)}}return {handleList:g,handleQuery:R,handleGet:k,handleCreate:T,handleUpdate:$,handleDelete:C,handleBatch:S,handleOptions:O}}function me(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=zodToOpenapi.getOpenApiMetadata(t.zodSchema);n&&Object.assign(t.jsonSchema,n);let s=t.zodSchema?._zod?.def;s&&(s.type==="date"&&!t.jsonSchema.type?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):s.type==="bigint"&&!t.jsonSchema.type&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function H(e){return {$ref:`#/components/schemas/${e}`}}function D(e){return {description:e,content:{"application/json":{schema:H("ErrorResponse")}}}}function L(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function je(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 xt(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 St(e){let t=e.filterableFields??Object.keys(e.schema.shape),n=["eq","ne","lt","lte","gt","gte","in","nin","contains","containsAny"],s={eq:"equals. Use 'null' or '__null__' to match null values",ne:"not equals. Use 'null' or '__null__' to match non-null values",lt:"less than",lte:"less than or equal",gt:"greater than",gte:"greater than or equal",in:"in list (comma-separated values). Supports 'null' and '__null__' (e.g. val1,val2,__null__)",nin:"not in list (comma-separated values). Supports 'null' and '__null__'",contains:"array-contains",containsAny:"array-contains-any (comma-separated values). Supports 'null' and '__null__'"},i=[];for(let c of t){i.push({name:c,in:"query",schema:{type:"string"},description:`Filter by ${c} (equality). Use 'null' or '__null__' for null values`});for(let a of n){let u=s[a]?` (${s[a]})`:"";i.push({name:`${c}__${a}`,in:"query",schema:{type:"string"},description:`Filter ${c} with operator ${a}${u}`});}}return i}function vt(){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 Rt(e,t,n,s,i){let c={},a=e.name,u=`${t}/${e.name}`,f=`${u}/{${e.documentKey}}`,g={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};c[u]={get:{operationId:`list${N(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[a],parameters:[...xt(e),...St(e)],responses:{200:je(H(n)),500:D("Internal server error")}},post:{operationId:`create${N(e.name)}`,summary:`Create a ${z(e.name)}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:H(s??n)}}},responses:{201:L("Document created",H(n)),400:D("Validation error"),500:D("Internal server error")}}},c[`${u}/query`]={post:{operationId:`query${N(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:H("QueryRequestBody")}}},responses:{200:je(H(n)),400:D("Invalid query"),500:D("Internal server error")}}},c[`${u}/batch`]={post:{operationId:`batch${N(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[a],requestBody:{required:true,content:{"application/json":{schema:H(`${n}BatchRequest`)}}},responses:{200:L("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:D("Validation error"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}}};let R={};return R.get={operationId:`get${N(z(e.name))}`,summary:`Get a single ${z(e.name)}`,tags:[a],parameters:[g],responses:{200:L("Document found",H(n)),404:D("Document not found"),500:D("Internal server error")}},R.put={operationId:`update${N(z(e.name))}`,summary:`Update a ${z(e.name)} (full replace)`,tags:[a],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:H(i??n)}}},responses:{200:L("Document updated",H(n)),400:D("Validation error"),404:D("Document not found"),500:D("Internal server error")}},R.patch={operationId:`patch${N(z(e.name))}`,summary:`Partially update a ${z(e.name)}`,tags:[a],parameters:[g],requestBody:{required:true,content:{"application/json":{schema:{allOf:[H(i??n)],description:"All fields are optional for partial updates"}}}},responses:{200:L("Document patched",H(n)),400:D("Validation error"),404:D("Document not found"),500:D("Internal server error")}},e.allowDelete&&(R.delete={operationId:`delete${N(z(e.name))}`,summary:`Delete a ${z(e.name)}`,tags:[a],parameters:[g],responses:{200:L("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:D("Document not found"),500:D("Internal server error")}}),c[f]=R,c}function ge(e,t,n={}){let{title:s="CRUD API",version:i="1.0.0",description:c,servers:a,auth:u=false}=n,f=t==="/"?"":t.replace(/\/$/,""),g={},R={},k=[];g.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},g.QueryRequestBody=vt();for(let[O,S]of Object.entries(e)){let d=N(z(O)),r=`${d}Create`,y=`${d}Update`;g[d]=me(S.schema);let o=x=>{let v=x&&x.length>0?x:Object.keys(S.schema.shape),A={};for(let P of v){let _=P.split(".")[0];_&&S.schema.shape[_]&&!S.systemKeys.includes(_)&&(A[_]=S.schema.shape[_]);}return A},l=null,m=o(S.createFields);Object.keys(m).length>0&&(g[r]=me(zod.z.object(m)),l=r);let h=null,p=o(S.mutableFields);Object.keys(p).length>0&&(g[y]=me(zod.z.object(p)),h=y),g[`${d}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:H(l??d)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[H(h??d)],description:"Partial updates allowed"}},required:["type","id","data"]},...S.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let w=Rt(S,f,d,l,h);Object.assign(R,w),k.push({name:O,description:`Operations on ${O} (collection: ${S.path})`});}let T={},$;return u==="basic"?(T.basicAuth={type:"http",scheme:"basic"},$=[{basicAuth:[]}]):u==="bearer"&&(T.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},$=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:i,...c?{description:c}:{}},...a&&a.length>0?{servers:a}:{},paths:R,components:{schemas:g,...Object.keys(T).length>0?{securitySchemes:T}:{}},...$?{security:$}:{},tags:k}}function N(e){return e.charAt(0).toUpperCase()+e.slice(1)}function z(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var Z=class extends Error{constructor(n,s){super("Request validation failed");this.zodError=n;this.source=s;this.statusCode=400;this.name="ValidationError";}};var W=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},J=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function qe(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function $e(e,t){return t instanceof Z?e.json({success:false,error:"Validation failed",issues:qe(t.zodError)},400):t instanceof W?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof J?e.json({success:false,error:"Output validation failed",issues:qe(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var He="Successful response",_e="Error response";function Tt(e){return e==="get"?"query":"json"}function Ct(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Pt(e){if(typeof e.safeParse=="function")return {description:_e,schema:e};let t=e;return {description:t.description??_e,schema:t.schema}}function ze(e,t,n,s){let i=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[u,f]of Object.entries(n.securitySchemes))i.registerComponent("securitySchemes",u,f);for(let u of e){let f=u.method,g=u.source??Tt(f),R=jt(t,u.path??"/"),k=u.status??200,T=It(f,g,u.input),$=Fe(g,u.input,"query"),C=Fe(g,u.input,"param"),O=qt(f,R),S=Ct(u.output,s),d={[k]:S?{description:He,content:{"application/json":{schema:S}}}:{description:He}};if(s?.errors)for(let[r,y]of Object.entries(s.errors)){let{description:o,schema:l}=Pt(y);d[r]=l?{description:o,content:{"application/json":{schema:l}}}:{description:o};}i.registerPath({method:f,path:Dt(R),operationId:O,summary:u.summary,description:u.description,tags:u.tags,deprecated:u.deprecated,security:u.security,request:{...$?{query:$}:{},...C?{params:C}:{},...T?{body:T}:{}},responses:d});}return new zodToOpenapi.OpenApiGeneratorV31(i.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function It(e,t,n){return !n||e==="get"?null:t==="json"?{content:{"application/json":{schema:n}}}:t==="form"?{content:{"application/x-www-form-urlencoded":{schema:n}}}:null}function Fe(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Dt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function jt(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,i=`${n}${s}`;return i===""?"/":i}function qt(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Ne(e,t){let n=e.replace(/"/g,"&quot;");return `<!doctype html>
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="utf-8" />
@@ -9,5 +9,5 @@
9
9
  <script id="api-reference" data-url="${n}"></script>
10
10
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
11
11
  </body>
12
- </html>`}function Fe(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var me=new async_hooks.AsyncLocalStorage;function ze(){return async(e,t)=>{await me.run({c:e},async()=>{await t();});}}var qt=Object.freeze({}),ee=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=Ft(t.routes,t.api),t.services&&this.app.use("*",ze());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let s of n)this.app.use("*",s);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return nodeServer.getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let s=this.nodeHandler;return n?t(n,s):t(s)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=$e(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Ht(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,s=this.options.verbose??false;for(let i of this.mountedRoutes){if(!i.path)throw new Error(`[HonoServer] route "${i.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let a=Y(t,i.path),c=i.middlewares??[],u=i.source??(i.method==="get"?"query":"json"),f=Bt(i,u,n,$t(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),g=i.method.toUpperCase();this.app.on(g,[a],...c,f),s&&console.log(`[HonoServer] ${i.method.toUpperCase().padEnd(6)} ${a}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",s=t.docsPath===void 0?"/docs":t.docsPath,i=Y(this.options.basePath??"",n),a=s===false?null:Y(this.options.basePath??"",s),c;if(Fe(t.docsAuth)){let u=t.docsAuth;c=[u.middleware];let f=zt(a??i);for(let g of u.routes)this.app.on(g.method,[Y(f,g.name)],g.handler);}else c=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[i],...c,u=>u.json(this.buildOpenApiSpec())),a){let u=Nt(a,i);this.app.on("GET",[a],...c,f=>f.html(He(u,t.info.title)));}}};function Ne(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function $t(e){if(e)return Ne(e)?e.handler:e}function Ht(e){return Ne(e)?e:void 0}function Ft(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function Y(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,i=`${n}${s}`;return i===""?"/":i}function zt(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Nt(e,t){let n=e.split("/").filter(Boolean),s=t.split("/").filter(Boolean);n.pop();let i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i++;let a=n.length-i;return [...Array(a).fill(".."),...s.slice(i)].join("/")||"./"}function Bt(e,t,n,s,i,a,c){let u=e.input,f=e.output,g=e.status??200,v=i??qt;return async k=>{let T=async O=>{if(a){let S=await a.handle({error:O,c:k,route:e,services:v,logger:c});if(S)return S}return Ie(k,O)},q=async()=>{let O,S;try{S=await Mt(k,t,e.method);}catch(r){throw new W(r instanceof Error?r.message:String(r))}if(u){let r=u.safeParse(S);if(!r.success)throw new Z(r.error,t);O=r.data;}else O=S;let d=await e.handler({input:O,c:k,services:v,errorHandler:a,logger:c});if(n&&f&&!(d instanceof Response)){let r=f.safeParse(d);if(!r.success)throw new J(r.error);return r.data}return d},C;if(s)try{C=await s({next:q,route:e,c:k,services:v,errorHandler:a,logger:c});}catch(O){let S=await T(O);if(S)return S;throw O}else try{C=await q();}catch(O){let S=await T(O);if(S)return S;throw O}return C instanceof Response?C:k.json(C,g)}}async function Mt(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let s=await e.req.text();if(!s)return {};try{return JSON.parse(s)}catch(i){throw new Error(`Invalid JSON body: ${i instanceof Error?i.message:String(i)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function Pn(e){let{basePath:t="/",repos:n,parseBody:s=true,securityHeaders:i,verbose:a=false,httpsOptions:c}=e,u=t==="/"?"":t.replace(/\/$/,""),f={};for(let[d,r]of Object.entries(n)){if(!r.repo)throw new Error(`[createCrudServer] Repository "${d}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let y=r.schema??r.repo.schema??null;if(!y)throw new Error(`[createCrudServer] Repository "${d}" has no Zod schema.`);let o,l,m,h;if(r.fieldsConfig){let x=r.fieldsConfig;o=[],l=[],m=[],h=[];for(let[R,A]of Object.entries(x))for(let P of A)P==="filterable"?o.push(R):P==="orderable"?l.push(R):P==="mutable"?m.push(R):P==="create"&&h.push(R);l.length===0&&(l=o),o.length===0&&(o=void 0),l&&l.length===0&&(l=void 0),m.length===0&&(m=void 0),h.length===0&&(h=void 0);}let p=(()=>{let x=r.repo._parentKeys;return x&&x.length>0?x:void 0})();if(p&&h)for(let x of p)h.includes(x)||h.push(x);let w={name:d,path:r.path,repo:r.repo,schema:y,systemKeys:r.repo._systemKeys??[r.documentKey??"docId"],documentKey:r.documentKey??"docId",pathKey:r.repo._pathKey??void 0,isGroup:!!r.repo._isGroup,parentKeys:p,createdKey:r.repo._createdKey??void 0,pageSize:r.pageSize??25,filterableFields:o,orderableFields:l,mutableFields:m,createFields:h,allowDelete:r.allowDelete??false,allowedIncludes:r.allowedIncludes,validate:r.validate,rules:r.rules};f[d]=w;}let g=Te(f,u,a),v=e.openapi,k=v&&typeof v=="object"?v:{},T=null;function q(){return T||(T=ye(f,u,{...k,auth:k.auth??false})),T}let C=[];for(let d of Object.keys(f))C.push({api:"crud",method:"get",path:`/${d}`,source:"query",handler:g.handleList}),C.push({api:"crud",method:"post",path:`/${d}/query`,source:"json",handler:g.handleQuery}),C.push({api:"crud",method:"get",path:`/${d}/:id`,source:"query",handler:g.handleGet}),C.push({api:"crud",method:"post",path:`/${d}`,source:"json",handler:g.handleCreate}),C.push({api:"crud",method:"put",path:`/${d}/:id`,source:"json",handler:r=>g.handleUpdate(r,false)}),C.push({api:"crud",method:"patch",path:`/${d}/:id`,source:"json",handler:r=>g.handleUpdate(r,true)}),C.push({api:"crud",method:"delete",path:`/${d}/:id`,source:"query",handler:g.handleDelete}),C.push({api:"crud",method:"post",path:`/${d}/batch`,source:"json",handler:g.handleBatch});let O=new ee({...e,openapi:v!==false?{path:k.path??"/openapi.json",docsPath:k.docsPath??"/docs",info:{title:k.title??"CRUD API",version:k.version??"1.0.0"},docsAuth:k.docsAuth}:void 0,basePath:t,api:"crud",routes:C,middlewares:[async(d,r)=>{if(d.req.method==="OPTIONS")return d.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});d.header("Access-Control-Allow-Origin","*"),d.header("Access-Control-Allow-Credentials","true"),await r();},...e.middlewares||[]]});if(v!==false&&(O.buildOpenApiSpec=q),i!==false){let{securityHeaders:d}=(Le(),et(Ke)),r=i===void 0?{csp:false}:i;O.hono.use("*",async(y,o)=>{let l=d(r);await new Promise(m=>{let h=y.req.raw;l(h,{setHeader:(w,x)=>y.header(w,x),removeHeader:w=>y.res.headers.delete(w)},()=>m());}),await o();});}let S=O.nodeHandler;return S.spec=q,c&&(S.httpsOptions=c),S}exports.createCrudServer=Pn;exports.generateOpenAPISpec=ye;//# sourceMappingURL=index.cjs.map
12
+ </html>`}function Me(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var we=new async_hooks.AsyncLocalStorage;function Be(){return async(e,t)=>{await we.run({c:e},async()=>{await t();});}}var Ft=Object.freeze({}),re=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=Mt(t.routes,t.api),t.services&&this.app.use("*",Be());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let s of n)this.app.use("*",s);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return nodeServer.getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let s=this.nodeHandler;return n?t(n,s):t(s)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=ze(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Nt(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,s=this.options.verbose??false;for(let i of this.mountedRoutes){if(!i.path)throw new Error(`[HonoServer] route "${i.method.toUpperCase()} (no path)" \u2014 missing \`path\`. Run the codegen so the path is derived from the file location, or set it explicitly.`);let c=ne(t,i.path),a=i.middlewares??[],u=i.source??(i.method==="get"?"query":"json"),f=Kt(i,u,n,zt(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),g=i.method.toUpperCase();this.app.on(g,[c],...a,f),s&&console.log(`[HonoServer] ${i.method.toUpperCase().padEnd(6)} ${c}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",s=t.docsPath===void 0?"/docs":t.docsPath,i=ne(this.options.basePath??"",n),c=s===false?null:ne(this.options.basePath??"",s),a;if(Me(t.docsAuth)){let u=t.docsAuth;a=[u.middleware];let f=Bt(c??i);for(let g of u.routes)this.app.on(g.method,[ne(f,g.name)],g.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[i],...a,u=>u.json(this.buildOpenApiSpec())),c){let u=Ut(c,i);this.app.on("GET",[c],...a,f=>f.html(Ne(u,t.info.title)));}}};function Ue(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function zt(e){if(e)return Ue(e)?e.handler:e}function Nt(e){return Ue(e)?e:void 0}function Mt(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function ne(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,i=`${n}${s}`;return i===""?"/":i}function Bt(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Ut(e,t){let n=e.split("/").filter(Boolean),s=t.split("/").filter(Boolean);n.pop();let i=0;for(;i<n.length&&i<s.length&&n[i]===s[i];)i++;let c=n.length-i;return [...Array(c).fill(".."),...s.slice(i)].join("/")||"./"}function Kt(e,t,n,s,i,c,a){let u=e.input,f=e.output,g=e.status??200,R=i??Ft;return async k=>{let T=async O=>{if(c){let S=await c.handle({error:O,c:k,route:e,services:R,logger:a});if(S)return S}return $e(k,O)},$=async()=>{let O,S;try{S=await Lt(k,t,e.method);}catch(r){throw new W(r instanceof Error?r.message:String(r))}if(u){let r=u.safeParse(S);if(!r.success)throw new Z(r.error,t);O=r.data;}else O=S;let d=await e.handler({input:O,c:k,services:R,errorHandler:c,logger:a});if(n&&f&&!(d instanceof Response)){let r=f.safeParse(d);if(!r.success)throw new J(r.error);return r.data}return d},C;if(s)try{C=await s({next:$,route:e,c:k,services:R,errorHandler:c,logger:a});}catch(O){let S=await T(O);if(S)return S;throw O}else try{C=await $();}catch(O){let S=await T(O);if(S)return S;throw O}return C instanceof Response?C:k.json(C,g)}}async function Lt(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let s=await e.req.text();if(!s)return {};try{return JSON.parse(s)}catch(i){throw new Error(`Invalid JSON body: ${i instanceof Error?i.message:String(i)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function qn(e){let{basePath:t="/",repos:n,parseBody:s=true,securityHeaders:i,verbose:c=false,httpsOptions:a}=e,u=t==="/"?"":t.replace(/\/$/,""),f={};for(let[d,r]of Object.entries(n)){if(!r.repo)throw new Error(`[createCrudServer] Repository "${d}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let y=r.schema??r.repo.schema??null;if(!y)throw new Error(`[createCrudServer] Repository "${d}" has no Zod schema.`);let o,l,m,h;if(r.fieldsConfig){let x=r.fieldsConfig;o=[],l=[],m=[],h=[];for(let[v,A]of Object.entries(x))for(let P of A)P==="filterable"?o.push(v):P==="orderable"?l.push(v):P==="mutable"?m.push(v):P==="create"&&h.push(v);l.length===0&&(l=o),o.length===0&&(o=void 0),l&&l.length===0&&(l=void 0),m.length===0&&(m=void 0),h.length===0&&(h=void 0);}let p=(()=>{let x=r.repo._parentKeys;return x&&x.length>0?x:void 0})();if(p&&h)for(let x of p)h.includes(x)||h.push(x);let w={name:d,path:r.path,repo:r.repo,schema:y,systemKeys:r.repo._systemKeys??[r.documentKey??"docId"],documentKey:r.documentKey??"docId",pathKey:r.repo._pathKey??void 0,isGroup:!!r.repo._isGroup,parentKeys:p,createdKey:r.repo._createdKey??void 0,pageSize:r.pageSize??25,filterableFields:o,orderableFields:l,mutableFields:m,createFields:h,allowDelete:r.allowDelete??false,allowedIncludes:r.allowedIncludes,validate:r.validate,rules:r.rules};f[d]=w;}let g=De(f,u,c),R=e.openapi,k=R&&typeof R=="object"?R:{},T=null;function $(){return T||(T=ge(f,u,{...k,auth:k.auth??false})),T}let C=[];for(let d of Object.keys(f))C.push({api:"crud",method:"get",path:`/${d}`,source:"query",handler:g.handleList}),C.push({api:"crud",method:"post",path:`/${d}/query`,source:"json",handler:g.handleQuery}),C.push({api:"crud",method:"get",path:`/${d}/:id`,source:"query",handler:g.handleGet}),C.push({api:"crud",method:"post",path:`/${d}`,source:"json",handler:g.handleCreate}),C.push({api:"crud",method:"put",path:`/${d}/:id`,source:"json",handler:r=>g.handleUpdate(r,false)}),C.push({api:"crud",method:"patch",path:`/${d}/:id`,source:"json",handler:r=>g.handleUpdate(r,true)}),C.push({api:"crud",method:"delete",path:`/${d}/:id`,source:"query",handler:g.handleDelete}),C.push({api:"crud",method:"post",path:`/${d}/batch`,source:"json",handler:g.handleBatch});let O=new re({...e,openapi:R!==false?{path:k.path??"/openapi.json",docsPath:k.docsPath??"/docs",info:{title:k.title??"CRUD API",version:k.version??"1.0.0"},docsAuth:k.docsAuth}:void 0,basePath:t,api:"crud",routes:C,middlewares:[async(d,r)=>{if(d.req.method==="OPTIONS")return d.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});d.header("Access-Control-Allow-Origin","*"),d.header("Access-Control-Allow-Credentials","true"),await r();},...e.middlewares||[]]});if(R!==false&&(O.buildOpenApiSpec=$),i!==false){let{securityHeaders:d}=(We(),ot(Ge)),r=i===void 0?{csp:false}:i;O.hono.use("*",async(y,o)=>{let l=d(r);await new Promise(m=>{let h=y.req.raw;l(h,{setHeader:(w,x)=>y.header(w,x),removeHeader:w=>y.res.headers.delete(w)},()=>m());}),await o();});}let S=O.nodeHandler;return S.spec=$,a&&(S.httpsOptions=a),S}exports.createCrudServer=qn;exports.generateOpenAPISpec=ge;//# sourceMappingURL=index.cjs.map
13
13
  //# sourceMappingURL=index.cjs.map