@lpdjs/firestore-repo-service 2.6.35 → 2.6.37

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
- 'use strict';var crypto=require('crypto'),zod=require('zod'),firestore=require('firebase-admin/firestore'),hono=require('hono'),nodeServer=require('@hono/node-server'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),async_hooks=require('async_hooks');var te=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var Ge=(e,t)=>()=>(e&&(t=e(e=0)),t);var We=(e,t)=>{for(var n in t)te(e,n,{get:t[n],enumerable:true});},Je=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ue(t))!Ze.call(e,i)&&i!==n&&te(e,i,{get:()=>t[i],enumerable:!(s=Le(t,i))||s.enumerable});return e};var Qe=e=>Je(te({},"__esModule",{value:true}),e);var Me={};We(Me,{DEFAULT_HTML_CSP:()=>Be,securityHeaders:()=>Ft});function Ft(e={}){let t=e.csp===void 0?Be: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,u,p)=>{typeof u?.setHeader=="function"&&(u.setHeader("X-Content-Type-Options","nosniff"),n&&u.setHeader("X-Frame-Options",n),s&&u.setHeader("Referrer-Policy",s),i&&u.setHeader("Cache-Control",i),t&&u.setHeader("Content-Security-Policy",t)),await p();}}var ze,Ne,Be,_e=Ge(()=>{ze="https://cdn.jsdelivr.net",Ne="https://www.gstatic.com",Be=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${ze} ${Ne}`,`style-src 'self' 'unsafe-inline' ${ze}`,`connect-src 'self' ${Ne} 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 me="preserve";function ge(){return me}function Ve(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function he(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(Ve(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 we(e){return e}var Ye=new Set(["<","<=",">",">=","!="]),et=new Set(["array-contains","array-contains-any"]);function re(e){return e==="desc"?"DESCENDING":"ASCENDING"}function tt(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function nt(e,t,n,s,i){let c=[],u=new Set;for(let y of s)if(y.op==="=="||y.op==="in"||y.op==="not-in"){if(u.has(y.field))continue;u.add(y.field),c.push({fieldPath:y.field,order:"ASCENDING"});}for(let y of s)if(et.has(y.op)){if(u.has(y.field))continue;u.add(y.field),c.push({fieldPath:y.field,arrayConfig:"CONTAINS"});}for(let y of s)if(Ye.has(y.op)){if(u.has(y.field))continue;u.add(y.field);let h=i?.field===y.field?re(i.dir):"ASCENDING";c.push({fieldPath:y.field,order:h});}if(i&&!u.has(i.field)&&c.push({fieldPath:i.field,order:re(i.dir)}),c.length===1&&n)return st(e,t,c[0]);let p=i&&c.some(y=>y.fieldPath===i.field)?re(i.dir):"ASCENDING";return c.push({fieldPath:"__name__",order:p}),rt(e,t,n,c)}function rt(e,t,n,s,i="(default)"){let c=`projects/${e}/databases/${i}/collectionGroups/${t}/indexes/_`,u=[...ie(1,c),...Q(2,n?2:1)];for(let h of s)u.push(...be(3,xe(h)));let p=i==="(default)"?"-default-":i,y=encodeURIComponent(Se(u));return `https://console.firebase.google.com/project/${e}/firestore/databases/${p}/indexes?create_composite=${y}`}function ot(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function oe(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function se(e,t){return e<<3|t}function ie(e,t){let n=Array.from(new TextEncoder().encode(t));return [se(e,2),...oe(n.length),...n]}function Q(e,t){return [se(e,0),...oe(t)]}function be(e,t){return [se(e,2),...oe(t.length),...t]}function xe(e){let t=[...ie(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Q(3,1)):t.push(...Q(2,e.order==="DESCENDING"?2:1)),t}function Se(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 st(e,t,n,s="(default)"){let i=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,c=[...ie(1,i),...Q(2,2),...be(3,xe(n))],u=s==="(default)"?"-default-":s,p=encodeURIComponent(Se(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${u}/indexes/automatic?create_exemption=${p}`}function it(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 at(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function ve(e,t){let n=e??{},s=at(e),i;if(s&&(i=n.message?ot(n.message):void 0,!i)){let c=it(t.ref);if(c){let u=tt(t.path);i=nt(c,u,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 de(e,t,n=200){let s=we(t);return e.json(s,n)}function M(e,t,n,s=200){return de(e,{success:true,data:t,meta:n},s)}function x(e,t,n=400){return de(e,{success:false,error:t},n)}function ae(e,t,n,s,i){let c=ve(t,n),u=c.type==="index",p=u?424:500,h={success:false,error:u?c.message:i&&t instanceof Error?t.message:s};return u&&(h.errorType="index",c.indexUrl&&(h.indexUrl=c.indexUrl)),de(e,h,p)}var ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Re(){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>=ce.length*4||(e+=ce.charAt(s%ce.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=>he(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,i={};for(let[c,u]of Object.entries(s))i[c]=K(u);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 dt(e,t,n=[]){let s=e.shape,i={},c=t&&t.length>0?t:Object.keys(s);for(let u of c){if(n.includes(u))continue;let p=u.split(".")[0];p&&s[p]&&(i[p]=s[p]);}return zod.z.object(i)}function V(e,t,n,s=false,i=[]){try{let c=dt(e,n,i),u=s?c.partial():c;return {success:!0,data:(ge()==="normalize"?K(u):u).parse(t)}}catch(c){return c instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${c.issues.map(p=>`${p.path.join(".")}: ${p.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function ut(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,u]of Object.entries(e)){if(u===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(c))continue;let p=Array.isArray(u)?u[0]:u;if(p===void 0||p==="")continue;let y=c.match(/^(\w+)__(\w+)$/),h,R="==";if(y&&y[1]&&y[2]){h=y[1];let T=y[2];if(i[T])R=i[T];else continue}else if(!y)h=c;else continue;if(s&&!s.has(h))continue;let k=p;R==="in"||R==="not-in"||R==="array-contains-any"?k=p.split(",").map(T=>Ae(T.trim())):k=Ae(p),n.push({field:h,op:R,value:k});}return n}function Ae(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}:null}async function ke(e,t){if(!t||typeof t!="object")return;let n=t.docId;if(typeof n=="string")try{let s=e.repo.ref;if(typeof s.doc!="function")return;let i=await s.doc(n).get();return i.exists?i:void 0}catch{return}}function Ee(e,t,n){async function s(a,o,f,r){if(!o.rules)return true;let l=o.rules?.[f];if(!l)return x(a,`Operation "${f}" is not allowed for this repository`,403),false;try{return await l(r)?!0:x(a,"Forbidden",403)}catch(m){let g=n&&m instanceof Error?m.message:"Forbidden";return x(a,g,403)}}async function i(a,o,f,r){if(!a.rules)return r;let l=a.rules?.filter;if(!l)return r;let m=[];for(let g of r)try{await l({user:o,doc:g,params:f})&&m.push(g);}catch{}return m}function c(a){return a.get("user")??a.get("docsUser")??null}function u(a,o){return !a||!e[a]?x(o,`Repository "${a}" not found`,404):e[a]}function p(a,o){if(!o)return;let f=a[o];if(typeof f!="string"||!f)return;let r=f.split("/").filter(Boolean),l=[];for(let m=1;m<r.length;m+=2)l.push(r[m]);return l.length>0?l:void 0}async function y(a,o){let f=`by${a.documentKey.charAt(0).toUpperCase()}${a.documentKey.slice(1)}`,r=a.repo.get[f];if(typeof r=="function")try{let m=await r(o);if(m)return m}catch{}return (await a.repo.query.by({where:[[a.documentKey,"==",o]],limit:1}))[0]??null}async function h(a){let o=a.c,f=o.req.param(),r=u(f.repoName,o);if(!r)return;let l=c(o);if(!await s(o,r,"list",{user:l,query:o.req.query(),params:f}))return;let m=[],g;try{let d=o.req.query(),w=Math.min(Number(d.pageSize)||r.pageSize,100),b=d.cursor,v=d.direction?.toLowerCase()==="prev"?"prev":"next",A=d.orderBy,P=d.orderDir?.toLowerCase()==="desc"?"desc":"asc",H=d.select,I=H?H.split(",").map(F=>F.trim()):void 0,E;r.allowedIncludes&&d.includes&&(E=(typeof d.includes=="string"?d.includes.split(",").map(J=>J.trim()):Array.isArray(d.includes)?d.includes:[]).filter(J=>typeof J=="string"&&r.allowedIncludes.includes(J)),E?.length===0&&(E=void 0));let j=ut(d,r.filterableFields);m=j.map(F=>({field:F.field,op:F.op,value:String(F.value??"")})),A&&(g={field:A,dir:P});let z={pageSize:w,direction:v};if(b)try{let F=typeof b=="string"?JSON.parse(b):b;z.cursor=await ke(r,F);}catch{}if(A){if(r.orderableFields&&!r.orderableFields.includes(A))return x(o,`Field not orderable: ${A}`,400);z.orderBy=[{field:A,direction:P}];}j.length>0&&(z.where=j.map(F=>[F.field,F.op,F.value])),I&&(z.select=I),E&&(z.include=E);let _=await r.repo.query.paginate(z),Ke={items:await i(r,c(o),f,_.data),hasNextPage:_.hasNextPage,hasPrevPage:_.hasPrevPage,nextCursor:X(_.nextCursor),prevCursor:X(_.prevCursor)};return M(o,Ke,{pageSize:w,hasMore:_.hasNextPage})}catch(d){ae(o,d,{ref:r.repo.ref,path:r.path,isGroup:!!r.isGroup,filters:m,sort:g},"Failed to fetch documents",n);}}async function R(a){let o=a.c,f=o.req.param(),r=u(f.repoName,o);if(!r)return;let l=c(o);if(!await s(o,r,"list",{user:l,query:a.input||{},params:f}))return;let m=[],g;try{let d=a.input||{},w=Math.min(d.pageSize||r.pageSize,100),b=d.direction==="prev"?"prev":"next";d.where&&(m=d.where.map(I=>({field:String(I[0]),op:I[1],value:String(I[2]??"")}))),d.orderBy&&d.orderBy[0]&&(g={field:d.orderBy[0].field,dir:d.orderBy[0].direction==="desc"?"desc":"asc"});let v={pageSize:w,direction:b};if(d.cursor)try{let I=typeof d.cursor=="string"?JSON.parse(d.cursor):d.cursor;v.cursor=await ke(r,I);}catch{}if(r.allowedIncludes&&d.includes&&d.includes.length>0){let I=d.includes.filter(E=>typeof E=="string"?r.allowedIncludes.includes(E):typeof E=="object"&&E!==null&&"relation"in E&&typeof E.relation=="string"?r.allowedIncludes.includes(E.relation):!1);I.length>0&&(v.include=I);}if(d.where&&d.where.length>0){if(r.filterableFields){let I=new Set(r.filterableFields),E=d.where.filter(j=>!I.has(j[0]));if(E.length>0){x(o,`Fields not filterable: ${E.map(j=>j[0]).join(", ")}`,400);return}}v.where=d.where;}if(d.orWhere&&d.orWhere.length>0){if(r.filterableFields){let I=new Set(r.filterableFields),E=d.orWhere.filter(j=>!I.has(j[0]));if(E.length>0){x(o,`Fields not filterable: ${E.map(j=>j[0]).join(", ")}`,400);return}}v.orWhere=d.orWhere;}if(d.orWhereGroups&&d.orWhereGroups.length>0){if(r.filterableFields){let I=new Set(r.filterableFields);for(let E of d.orWhereGroups){let j=E.filter(z=>!I.has(z[0]));if(j.length>0){x(o,`Fields not filterable: ${j.map(z=>z[0]).join(", ")}`,400);return}}}v.orWhereGroups=d.orWhereGroups;}if(d.orderBy&&d.orderBy.length>0){if(r.orderableFields){let I=new Set(r.orderableFields),E=d.orderBy.filter(j=>!I.has(j.field));if(E.length>0){x(o,`Fields not orderable: ${E.map(j=>j.field).join(", ")}`,400);return}}v.orderBy=d.orderBy;}d.select&&d.select.length>0&&(v.select=d.select);let A=await r.repo.query.paginate(v),H={items:await i(r,c(o),f,A.data),hasNextPage:A.hasNextPage,hasPrevPage:A.hasPrevPage,nextCursor:X(A.nextCursor),prevCursor:X(A.prevCursor)};return M(o,H,{pageSize:w,hasMore:A.hasNextPage})}catch(d){ae(o,d,{ref:r.repo.ref,path:r.path,isGroup:!!r.isGroup,filters:m,sort:g},"Failed to query documents",n);}}async function k(a){let o=a.c,f=o.req.param(),r=u(f.repoName,o);if(!r)return;let l=f.id;if(!l)return x(o,"Document ID required",400);try{let m=await y(r,l);if(!m)return x(o,"Document not found",404);let g=c(o);if(!await s(o,r,"get",{user:g,doc:m,params:f}))return;if(r.rules?.filter)try{if(!await r.rules.filter({user:g,doc:m,params:f}))return x(o,"Document not found",404)}catch{return x(o,"Document not found",404)}return M(o,m)}catch(m){ae(o,m,{ref:r.repo.ref,path:r.path,isGroup:!!r.isGroup,filters:[{field:r.documentKey,op:"==",value:l}]},"Failed to fetch document",n);}}async function T(a){let o=a.c,f=o.req.param(),r=u(f.repoName,o);if(r)try{let l=a.input||{},m=c(o);if(!await s(o,r,"create",{user:m,body:l,params:f}))return;let g=V(r.schema,l,r.createFields,!1,r.systemKeys);if(!g.success)return x(o,g.error,400);if(r.validate){let w=await r.validate(g.data,"create");if(w)return x(o,w,400)}let d;if(r.isGroup&&r.parentKeys&&r.parentKeys.length>0){let w={...g.data};r.createdKey&&(w[r.createdKey]=new Date);let b=r.parentKeys.filter(P=>!w[P]);if(b.length>0){x(o,`Missing parent key(s) for subcollection create: ${b.join(", ")}`,400);return}let v=r.parentKeys.map(P=>w[P]),A=w[r.documentKey]||Re();d=await r.repo.set(...v,A,w);}else d=await r.repo.create(g.data);return M(o,d,void 0,201)}catch(l){let m=n&&l instanceof Error?l.message:"Failed to create document";return x(o,m,500)}}async function q(a,o){let f=a.c,r=f.req.param(),l=u(r.repoName,f);if(!l)return;let m=r.id;if(!m)return x(f,"Document ID required",400);try{let g=a.input||{},d=await y(l,m);if(!d)return x(f,"Document not found",404);let w=c(f);if(!await s(f,l,"update",{user:w,doc:d,body:g,params:r}))return;let b=V(l.schema,g,l.mutableFields,o,l.systemKeys);if(!b.success)return x(f,b.error,400);if(l.validate){let P=await l.validate(b.data,"update");if(P)return x(f,P,400)}let v=p(d,l.pathKey)??[m],A=await l.repo.update(...v,b.data);return M(f,A)}catch(g){let d=n&&g instanceof Error?g.message:"Failed to update document";return x(f,d,500)}}async function C(a){let o=a.c,f=o.req.param(),r=u(f.repoName,o);if(!r)return;if(!r.allowDelete)return x(o,"Delete not allowed for this repository",403);let l=f.id;if(!l)return x(o,"Document ID required",400);try{let m=await y(r,l);if(!m)return x(o,"Document not found",404);let g=c(o);if(!await s(o,r,"delete",{user:g,doc:m,params:f}))return;let d=p(m,r.pathKey)??[l];return await r.repo.delete(...d),M(o,{deleted:!0})}catch(m){let g=n&&m instanceof Error?m.message:"Failed to delete document";return x(o,g,500)}}function O(a){return a.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(a){let o=a.c,f=o.req.param(),r=u(f.repoName,o);if(r)try{let l=a.input||{};if(!Array.isArray(l.operations))return x(o,"operations array is required",400);let m=c(o),g=r.repo.batch.create(),d=[];for(let w of l.operations){if(!w.type||!["create","update","delete"].includes(w.type))return x(o,"Invalid operation type",400);if(w.type==="create"){if(!await s(o,r,"create",{user:m,body:w.data,params:f}))return;let b=V(r.schema,w.data,r.createFields,!1,r.systemKeys);if(!b.success)return x(o,b.error,400);let v=w.data[r.documentKey]||Re(),A={...b.data};if(r.createdKey&&(A[r.createdKey]=new Date),r.isGroup&&r.parentKeys){let P=r.parentKeys.map(H=>A[H]);g.set(...P,v,A);}else g.set(v,A);d.push({op:"create",id:v});}else if(w.type==="update"){if(!w.id)return x(o,"id required for update",400);let b=await y(r,w.id);if(!b)return x(o,`Document ${w.id} not found`,404);if(!await s(o,r,"update",{user:m,doc:b,body:w.data,params:f}))return;let v=V(r.schema,w.data,r.mutableFields,!0,r.systemKeys);if(!v.success)return x(o,v.error,400);let A=p(b,r.pathKey)??[w.id];g.update(...A,v.data),d.push({op:"update",id:w.id});}else if(w.type==="delete"){if(!r.allowDelete)return x(o,"Delete not allowed",403);if(!w.id)return x(o,"id required for delete",400);let b=await y(r,w.id);if(!b)return x(o,`Document ${w.id} not found`,404);if(!await s(o,r,"delete",{user:m,doc:b,params:f}))return;let v=p(b,r.pathKey)??[w.id];g.delete(...v),d.push({op:"delete",id:w.id});}}return await g.commit(),M(o,{results:d})}catch(l){let m=n&&l instanceof Error?l.message:"Batch operation failed";return x(o,m,500)}}return {handleList:h,handleQuery:R,handleGet:k,handleCreate:T,handleUpdate:q,handleDelete:C,handleBatch:S,handleOptions:O}}function ue(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=t.zodSchema?._zod?.def;n&&(n.type==="date"?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):n.type==="bigint"&&(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 $(e){return {$ref:`#/components/schemas/${e}`}}function D(e){return {description:e,content:{"application/json":{schema:$("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 Oe(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 pt(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 lt(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 c of n)s.push({name:`${i}__${c}`,in:"query",schema:{type:"string"},description:`Filter ${i} with operator ${c}`});}return s}function ft(){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 yt(e,t,n,s,i){let c={},u=e.name,p=`${t}/${e.name}`,y=`${p}/{${e.documentKey}}`,h={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};c[p]={get:{operationId:`list${B(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[u],parameters:[...pt(e),...lt(e)],responses:{200:Oe($(n)),500:D("Internal server error")}},post:{operationId:`create${B(e.name)}`,summary:`Create a ${N(e.name)}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:$(s??n)}}},responses:{201:L("Document created",$(n)),400:D("Validation error"),500:D("Internal server error")}}},c[`${p}/query`]={post:{operationId:`query${B(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:$("QueryRequestBody")}}},responses:{200:Oe($(n)),400:D("Invalid query"),500:D("Internal server error")}}},c[`${p}/batch`]={post:{operationId:`batch${B(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:$(`${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${B(N(e.name))}`,summary:`Get a single ${N(e.name)}`,tags:[u],parameters:[h],responses:{200:L("Document found",$(n)),404:D("Document not found"),500:D("Internal server error")}},R.put={operationId:`update${B(N(e.name))}`,summary:`Update a ${N(e.name)} (full replace)`,tags:[u],parameters:[h],requestBody:{required:true,content:{"application/json":{schema:$(i??n)}}},responses:{200:L("Document updated",$(n)),400:D("Validation error"),404:D("Document not found"),500:D("Internal server error")}},R.patch={operationId:`patch${B(N(e.name))}`,summary:`Partially update a ${N(e.name)}`,tags:[u],parameters:[h],requestBody:{required:true,content:{"application/json":{schema:{allOf:[$(i??n)],description:"All fields are optional for partial updates"}}}},responses:{200:L("Document patched",$(n)),400:D("Validation error"),404:D("Document not found"),500:D("Internal server error")}},e.allowDelete&&(R.delete={operationId:`delete${B(N(e.name))}`,summary:`Delete a ${N(e.name)}`,tags:[u],parameters:[h],responses:{200:L("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:D("Document not found"),500:D("Internal server error")}}),c[y]=R,c}function le(e,t,n={}){let{title:s="CRUD API",version:i="1.0.0",description:c,servers:u,auth:p=false}=n,y=t==="/"?"":t.replace(/\/$/,""),h={},R={},k=[];h.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},h.QueryRequestBody=ft();for(let[O,S]of Object.entries(e)){let a=B(N(O)),o=`${a}Create`,f=`${a}Update`;h[a]=ue(S.schema);let r=b=>{let v=b&&b.length>0?b:Object.keys(S.schema.shape),A={};for(let P of v){let H=P.split(".")[0];H&&S.schema.shape[H]&&!S.systemKeys.includes(H)&&(A[H]=S.schema.shape[H]);}return A},l=null,m=r(S.createFields);Object.keys(m).length>0&&(h[o]=ue(zod.z.object(m)),l=o);let g=null,d=r(S.mutableFields);Object.keys(d).length>0&&(h[f]=ue(zod.z.object(d)),g=f),h[`${a}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:$(l??a)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[$(g??a)],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=yt(S,y,a,l,g);Object.assign(R,w),k.push({name:O,description:`Operations on ${O} (collection: ${S.path})`});}let T={},q;return p==="basic"?(T.basicAuth={type:"http",scheme:"basic"},q=[{basicAuth:[]}]):p==="bearer"&&(T.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},q=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:i,...c?{description:c}:{}},...u&&u.length>0?{servers:u}:{},paths:R,components:{schemas:h,...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 U=class extends Error{constructor(n,s){super("Request validation failed");this.zodError=n;this.source=s;this.statusCode=400;this.name="ValidationError";}};var G=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},W=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Te(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Ce(e,t){return t instanceof U?e.json({success:false,error:"Validation failed",issues:Te(t.zodError)},400):t instanceof G?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof W?e.json({success:false,error:"Output validation failed",issues:Te(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var Pe="Successful response",Ie="Error response";function bt(e){return e==="get"?"query":"json"}function xt(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function St(e){if(typeof e.safeParse=="function")return {description:Ie,schema:e};let t=e;return {description:t.description??Ie,schema:t.schema}}function je(e,t,n,s){let i=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[p,y]of Object.entries(n.securitySchemes))i.registerComponent("securitySchemes",p,y);for(let p of e){let y=p.method,h=p.source??bt(y),R=At(t,p.path??"/"),k=p.status??200,T=vt(y,h,p.input),q=De(h,p.input,"query"),C=De(h,p.input,"param"),O=kt(y,R),S=xt(p.output,s),a={[k]:S?{description:Pe,content:{"application/json":{schema:S}}}:{description:Pe}};if(s?.errors)for(let[o,f]of Object.entries(s.errors)){let{description:r,schema:l}=St(f);a[o]=l?{description:r,content:{"application/json":{schema:l}}}:{description:r};}i.registerPath({method:y,path:Rt(R),operationId:O,summary:p.summary,description:p.description,tags:p.tags,deprecated:p.deprecated,security:p.security,request:{...q?{query:q}:{},...C?{params:C}:{},...T?{body:T}:{}},responses:a});}return new zodToOpenapi.OpenApiGeneratorV31(i.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function vt(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 De(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Rt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function At(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,i=`${n}${s}`;return i===""?"/":i}function kt(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function qe(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'),hono=require('hono'),nodeServer=require('@hono/node-server'),zodToOpenapi=require('@asteasolutions/zod-to-openapi'),async_hooks=require('async_hooks');var te=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var Ge=(e,t)=>()=>(e&&(t=e(e=0)),t);var We=(e,t)=>{for(var n in t)te(e,n,{get:t[n],enumerable:true});},Je=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ue(t))!Ze.call(e,i)&&i!==n&&te(e,i,{get:()=>t[i],enumerable:!(s=Le(t,i))||s.enumerable});return e};var Qe=e=>Je(te({},"__esModule",{value:true}),e);var Me={};We(Me,{DEFAULT_HTML_CSP:()=>Be,securityHeaders:()=>Ft});function Ft(e={}){let t=e.csp===void 0?Be: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,u,p)=>{typeof u?.setHeader=="function"&&(u.setHeader("X-Content-Type-Options","nosniff"),n&&u.setHeader("X-Frame-Options",n),s&&u.setHeader("Referrer-Policy",s),i&&u.setHeader("Cache-Control",i),t&&u.setHeader("Content-Security-Policy",t)),await p();}}var ze,Ne,Be,_e=Ge(()=>{ze="https://cdn.jsdelivr.net",Ne="https://www.gstatic.com",Be=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${ze} ${Ne}`,`style-src 'self' 'unsafe-inline' ${ze}`,`connect-src 'self' ${Ne} 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 me="preserve";function ge(){return me}function Ve(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function he(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(Ve(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 we(e){return e}var Ye=new Set(["<","<=",">",">=","!="]),et=new Set(["array-contains","array-contains-any"]);function re(e){return e==="desc"?"DESCENDING":"ASCENDING"}function tt(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function nt(e,t,n,s,i){let c=[],u=new Set;for(let y of s)if(y.op==="=="||y.op==="in"||y.op==="not-in"){if(u.has(y.field))continue;u.add(y.field),c.push({fieldPath:y.field,order:"ASCENDING"});}for(let y of s)if(et.has(y.op)){if(u.has(y.field))continue;u.add(y.field),c.push({fieldPath:y.field,arrayConfig:"CONTAINS"});}for(let y of s)if(Ye.has(y.op)){if(u.has(y.field))continue;u.add(y.field);let h=i?.field===y.field?re(i.dir):"ASCENDING";c.push({fieldPath:y.field,order:h});}if(i&&!u.has(i.field)&&c.push({fieldPath:i.field,order:re(i.dir)}),c.length===1&&n)return st(e,t,c[0]);let p=i&&c.some(y=>y.fieldPath===i.field)?re(i.dir):"ASCENDING";return c.push({fieldPath:"__name__",order:p}),rt(e,t,n,c)}function rt(e,t,n,s,i="(default)"){let c=`projects/${e}/databases/${i}/collectionGroups/${t}/indexes/_`,u=[...ie(1,c),...Q(2,n?2:1)];for(let h of s)u.push(...be(3,xe(h)));let p=i==="(default)"?"-default-":i,y=encodeURIComponent(Se(u));return `https://console.firebase.google.com/project/${e}/firestore/databases/${p}/indexes?create_composite=${y}`}function ot(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function oe(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function se(e,t){return e<<3|t}function ie(e,t){let n=Array.from(new TextEncoder().encode(t));return [se(e,2),...oe(n.length),...n]}function Q(e,t){return [se(e,0),...oe(t)]}function be(e,t){return [se(e,2),...oe(t.length),...t]}function xe(e){let t=[...ie(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...Q(3,1)):t.push(...Q(2,e.order==="DESCENDING"?2:1)),t}function Se(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 st(e,t,n,s="(default)"){let i=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,c=[...ie(1,i),...Q(2,2),...be(3,xe(n))],u=s==="(default)"?"-default-":s,p=encodeURIComponent(Se(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${u}/indexes/automatic?create_exemption=${p}`}function it(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 at(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Re(e,t){let n=e??{},s=at(e),i;if(s&&(i=n.message?ot(n.message):void 0,!i)){let c=it(t.ref);if(c){let u=tt(t.path);i=nt(c,u,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 de(e,t,n=200){let s=we(t);return e.json(s,n)}function M(e,t,n,s=200){return de(e,{success:true,data:t,meta:n},s)}function b(e,t,n=400){return de(e,{success:false,error:t},n)}function ae(e,t,n,s,i){let c=Re(t,n),u=c.type==="index",p=u?424:500,h={success:false,error:u?c.message:i&&t instanceof Error?t.message:s};return u&&(h.errorType="index",c.indexUrl&&(h.indexUrl=c.indexUrl)),de(e,h,p)}var ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ve(){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>=ce.length*4||(e+=ce.charAt(s%ce.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=>he(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,i={};for(let[c,u]of Object.entries(s))i[c]=K(u);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 dt(e,t,n=[]){let s=e.shape,i={},c=t&&t.length>0?t:Object.keys(s);for(let u of c){if(n.includes(u))continue;let p=u.split(".")[0];p&&s[p]&&(i[p]=s[p]);}return zod.z.object(i)}function V(e,t,n,s=false,i=[]){try{let c=dt(e,n,i),u=s?c.partial():c;return {success:!0,data:(ge()==="normalize"?K(u):u).parse(t)}}catch(c){return c instanceof zod.z.ZodError?{success:false,error:`Validation failed: ${c.issues.map(p=>`${p.path.join(".")}: ${p.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function ut(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,u]of Object.entries(e)){if(u===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(c))continue;let p=Array.isArray(u)?u[0]:u;if(p===void 0||p==="")continue;let y=c.match(/^(\w+)__(\w+)$/),h,v="==";if(y&&y[1]&&y[2]){h=y[1];let T=y[2];if(i[T])v=i[T];else continue}else if(!y)h=c;else continue;if(s&&!s.has(h))continue;let k=p;v==="in"||v==="not-in"||v==="array-contains-any"?k=p.split(",").map(T=>Ae(T.trim())):k=Ae(p),n.push({field:h,op:v,value:k});}return n}function Ae(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}:null}async function ke(e,t){if(!t||typeof t!="object")return;let n=t.docId;if(typeof n=="string")try{let s=e.repo.ref;if(typeof s.doc!="function")return;let i=await s.doc(n).get();return i.exists?i:void 0}catch{return}}function Ee(e,t,n){async function s(a,r,l,o){if(!r.rules)return true;let f=r.rules?.[l];if(!f)return b(a,`Operation "${l}" is not allowed for this repository`,403),false;try{return await f(o)?!0:b(a,"Forbidden",403)}catch(m){let g=n&&m instanceof Error?m.message:"Forbidden";return b(a,g,403)}}async function i(a,r,l,o){if(!a.rules)return o;let f=a.rules?.filter;if(!f)return o;let m=[];for(let g of o)try{await f({user:r,doc:g,params:l})&&m.push(g);}catch{}return m}function c(a){return a.get("user")??a.get("docsUser")??null}function u(a,r){if(!a){let l=r.req.path.split("/");for(let o of l)if(e[o]){a=o;break}}return !a||!e[a]?null:e[a]??null}function p(a,r){if(!r)return;let l=a[r];if(typeof l!="string"||!l)return;let o=l.split("/").filter(Boolean),f=[];for(let m=1;m<o.length;m+=2)f.push(o[m]);return f.length>0?f:void 0}async function y(a,r){let l=`by${a.documentKey.charAt(0).toUpperCase()}${a.documentKey.slice(1)}`,o=a.repo.get[l];if(typeof o=="function")try{let m=await o(r);if(m)return m}catch{}return (await a.repo.query.by({where:[[a.documentKey,"==",r]],limit:1}))[0]??null}async function h(a){let r=a.c,l=r.req.param(),o=u(l.repoName,r);if(!o)return b(r,"Repository not found",404);let f=c(r);if(!await s(r,o,"list",{user:f,query:r.req.query(),params:l}))return;let m=[],g;try{let d=r.req.query(),w=Math.min(Number(d.pageSize)||o.pageSize,100),x=d.cursor,R=d.direction?.toLowerCase()==="prev"?"prev":"next",A=d.orderBy,P=d.orderDir?.toLowerCase()==="desc"?"desc":"asc",H=d.select,I=H?H.split(",").map(F=>F.trim()):void 0,E;o.allowedIncludes&&d.includes&&(E=(typeof d.includes=="string"?d.includes.split(",").map(J=>J.trim()):Array.isArray(d.includes)?d.includes:[]).filter(J=>typeof J=="string"&&o.allowedIncludes.includes(J)),E?.length===0&&(E=void 0));let j=ut(d,o.filterableFields);m=j.map(F=>({field:F.field,op:F.op,value:String(F.value??"")})),A&&(g={field:A,dir:P});let z={pageSize:w,direction:R};if(x)try{let F=typeof x=="string"?JSON.parse(x):x;z.cursor=await ke(o,F);}catch{}if(A){if(o.orderableFields&&!o.orderableFields.includes(A))return b(r,`Field not orderable: ${A}`,400);z.orderBy=[{field:A,direction:P}];}j.length>0&&(z.where=j.map(F=>[F.field,F.op,F.value])),I&&(z.select=I),E&&(z.include=E);let _=await o.repo.query.paginate(z),Ke={items:await i(o,c(r),l,_.data),hasNextPage:_.hasNextPage,hasPrevPage:_.hasPrevPage,nextCursor:X(_.nextCursor),prevCursor:X(_.prevCursor)};return M(r,Ke,{pageSize:w,hasMore:_.hasNextPage})}catch(d){ae(r,d,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:m,sort:g},"Failed to fetch documents",n);}}async function v(a){let r=a.c,l=r.req.param(),o=u(l.repoName,r);if(!o)return b(r,"Repository not found",404);let f=c(r);if(!await s(r,o,"list",{user:f,query:a.input||{},params:l}))return;let m=[],g;try{let d=a.input||{},w=Math.min(d.pageSize||o.pageSize,100),x=d.direction==="prev"?"prev":"next";d.where&&(m=d.where.map(I=>({field:String(I[0]),op:I[1],value:String(I[2]??"")}))),d.orderBy&&d.orderBy[0]&&(g={field:d.orderBy[0].field,dir:d.orderBy[0].direction==="desc"?"desc":"asc"});let R={pageSize:w,direction:x};if(d.cursor)try{let I=typeof d.cursor=="string"?JSON.parse(d.cursor):d.cursor;R.cursor=await ke(o,I);}catch{}if(o.allowedIncludes&&d.includes&&d.includes.length>0){let I=d.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(d.where&&d.where.length>0){if(o.filterableFields){let I=new Set(o.filterableFields),E=d.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=d.where;}if(d.orWhere&&d.orWhere.length>0){if(o.filterableFields){let I=new Set(o.filterableFields),E=d.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=d.orWhere;}if(d.orWhereGroups&&d.orWhereGroups.length>0){if(o.filterableFields){let I=new Set(o.filterableFields);for(let E of d.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=d.orWhereGroups;}if(d.orderBy&&d.orderBy.length>0){if(o.orderableFields){let I=new Set(o.orderableFields),E=d.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=d.orderBy;}d.select&&d.select.length>0&&(R.select=d.select);let A=await o.repo.query.paginate(R),H={items:await i(o,c(r),l,A.data),hasNextPage:A.hasNextPage,hasPrevPage:A.hasPrevPage,nextCursor:X(A.nextCursor),prevCursor:X(A.prevCursor)};return M(r,H,{pageSize:w,hasMore:A.hasNextPage})}catch(d){ae(r,d,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:m,sort:g},"Failed to query documents",n);}}async function k(a){let r=a.c,l=r.req.param(),o=u(l.repoName,r);if(!o)return b(r,"Repository not found",404);let f=l.id;if(!f)return b(r,"Document ID required",400);try{let m=await y(o,f);if(!m)return b(r,"Document not found",404);let g=c(r);if(!await s(r,o,"get",{user:g,doc:m,params:l}))return;if(o.rules?.filter)try{if(!await o.rules.filter({user:g,doc:m,params:l}))return b(r,"Document not found",404)}catch{return b(r,"Document not found",404)}return M(r,m)}catch(m){ae(r,m,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:[{field:o.documentKey,op:"==",value:f}]},"Failed to fetch document",n);}}async function T(a){let r=a.c,l=r.req.param(),o=u(l.repoName,r);if(!o)return b(r,"Repository not found",404);try{let f=a.input||{},m=c(r);if(!await s(r,o,"create",{user:m,body:f,params:l}))return;let g=V(o.schema,f,o.createFields,!1,o.systemKeys);if(!g.success)return b(r,g.error,400);if(o.validate){let w=await o.validate(g.data,"create");if(w)return b(r,w,400)}let d;if(o.isGroup&&o.parentKeys&&o.parentKeys.length>0){let w={...g.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]||ve();d=await o.repo.set(...R,A,w);}else d=await o.repo.create(g.data);return M(r,d,void 0,201)}catch(f){let m=n&&f instanceof Error?f.message:"Failed to create document";return b(r,m,500)}}async function q(a,r){let l=a.c,o=l.req.param(),f=u(o.repoName,l);if(!f)return b(l,"Repository not found",404);let m=o.id;if(!m)return b(l,"Document ID required",400);try{let g=a.input||{},d=await y(f,m);if(!d)return b(l,"Document not found",404);let w=c(l);if(!await s(l,f,"update",{user:w,doc:d,body:g,params:o}))return;let x=V(f.schema,g,f.mutableFields,r,f.systemKeys);if(!x.success)return b(l,x.error,400);if(f.validate){let P=await f.validate(x.data,"update");if(P)return b(l,P,400)}let R=p(d,f.pathKey)??[m],A=await f.repo.update(...R,x.data);return M(l,A)}catch(g){let d=n&&g instanceof Error?g.message:"Failed to update document";return b(l,d,500)}}async function C(a){let r=a.c,l=r.req.param(),o=u(l.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 f=l.id;if(!f)return b(r,"Document ID required",400);try{let m=await y(o,f);if(!m)return b(r,"Document not found",404);let g=c(r);if(!await s(r,o,"delete",{user:g,doc:m,params:l}))return;let d=p(m,o.pathKey)??[f];return await o.repo.delete(...d),M(r,{deleted:!0})}catch(m){let g=n&&m instanceof Error?m.message:"Failed to delete document";return b(r,g,500)}}function O(a){return a.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(a){let r=a.c,l=r.req.param(),o=u(l.repoName,r);if(!o)return b(r,"Repository not found",404);try{let f=a.input||{};if(!Array.isArray(f.operations))return b(r,"operations array is required",400);let m=c(r),g=o.repo.batch.create(),d=[];for(let w of f.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:l}))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]||ve(),A={...x.data};if(o.createdKey&&(A[o.createdKey]=new Date),o.isGroup&&o.parentKeys){let P=o.parentKeys.map(H=>A[H]);g.set(...P,R,A);}else g.set(R,A);d.push({op:"create",id:R});}else if(w.type==="update"){if(!w.id)return b(r,"id required for update",400);let x=await y(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:l}))return;let R=V(o.schema,w.data,o.mutableFields,!0,o.systemKeys);if(!R.success)return b(r,R.error,400);let A=p(x,o.pathKey)??[w.id];g.update(...A,R.data),d.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 y(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:l}))return;let R=p(x,o.pathKey)??[w.id];g.delete(...R),d.push({op:"delete",id:w.id});}}return await g.commit(),M(r,{results:d})}catch(f){let m=n&&f instanceof Error?f.message:"Batch operation failed";return b(r,m,500)}}return {handleList:h,handleQuery:v,handleGet:k,handleCreate:T,handleUpdate:q,handleDelete:C,handleBatch:S,handleOptions:O}}function ue(e){try{return zod.z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=t.zodSchema?._zod?.def;n&&(n.type==="date"?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):n.type==="bigint"&&(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 $(e){return {$ref:`#/components/schemas/${e}`}}function D(e){return {description:e,content:{"application/json":{schema:$("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 Oe(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 pt(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 lt(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 c of n)s.push({name:`${i}__${c}`,in:"query",schema:{type:"string"},description:`Filter ${i} with operator ${c}`});}return s}function ft(){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 yt(e,t,n,s,i){let c={},u=e.name,p=`${t}/${e.name}`,y=`${p}/{${e.documentKey}}`,h={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};c[p]={get:{operationId:`list${B(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[u],parameters:[...pt(e),...lt(e)],responses:{200:Oe($(n)),500:D("Internal server error")}},post:{operationId:`create${B(e.name)}`,summary:`Create a ${N(e.name)}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:$(s??n)}}},responses:{201:L("Document created",$(n)),400:D("Validation error"),500:D("Internal server error")}}},c[`${p}/query`]={post:{operationId:`query${B(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:$("QueryRequestBody")}}},responses:{200:Oe($(n)),400:D("Invalid query"),500:D("Internal server error")}}},c[`${p}/batch`]={post:{operationId:`batch${B(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:$(`${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 v={};return v.get={operationId:`get${B(N(e.name))}`,summary:`Get a single ${N(e.name)}`,tags:[u],parameters:[h],responses:{200:L("Document found",$(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:[u],parameters:[h],requestBody:{required:true,content:{"application/json":{schema:$(i??n)}}},responses:{200:L("Document updated",$(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:[u],parameters:[h],requestBody:{required:true,content:{"application/json":{schema:{allOf:[$(i??n)],description:"All fields are optional for partial updates"}}}},responses:{200:L("Document patched",$(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:[u],parameters:[h],responses:{200:L("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:D("Document not found"),500:D("Internal server error")}}),c[y]=v,c}function le(e,t,n={}){let{title:s="CRUD API",version:i="1.0.0",description:c,servers:u,auth:p=false}=n,y=t==="/"?"":t.replace(/\/$/,""),h={},v={},k=[];h.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},h.QueryRequestBody=ft();for(let[O,S]of Object.entries(e)){let a=B(N(O)),r=`${a}Create`,l=`${a}Update`;h[a]=ue(S.schema);let o=x=>{let R=x&&x.length>0?x:Object.keys(S.schema.shape),A={};for(let P of R){let H=P.split(".")[0];H&&S.schema.shape[H]&&!S.systemKeys.includes(H)&&(A[H]=S.schema.shape[H]);}return A},f=null,m=o(S.createFields);Object.keys(m).length>0&&(h[r]=ue(zod.z.object(m)),f=r);let g=null,d=o(S.mutableFields);Object.keys(d).length>0&&(h[l]=ue(zod.z.object(d)),g=l),h[`${a}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:$(f??a)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[$(g??a)],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=yt(S,y,a,f,g);Object.assign(v,w),k.push({name:O,description:`Operations on ${O} (collection: ${S.path})`});}let T={},q;return p==="basic"?(T.basicAuth={type:"http",scheme:"basic"},q=[{basicAuth:[]}]):p==="bearer"&&(T.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},q=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:i,...c?{description:c}:{}},...u&&u.length>0?{servers:u}:{},paths:v,components:{schemas:h,...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 U=class extends Error{constructor(n,s){super("Request validation failed");this.zodError=n;this.source=s;this.statusCode=400;this.name="ValidationError";}};var G=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},W=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Te(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Ce(e,t){return t instanceof U?e.json({success:false,error:"Validation failed",issues:Te(t.zodError)},400):t instanceof G?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof W?e.json({success:false,error:"Output validation failed",issues:Te(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var Pe="Successful response",Ie="Error response";function bt(e){return e==="get"?"query":"json"}function xt(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function St(e){if(typeof e.safeParse=="function")return {description:Ie,schema:e};let t=e;return {description:t.description??Ie,schema:t.schema}}function je(e,t,n,s){let i=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[p,y]of Object.entries(n.securitySchemes))i.registerComponent("securitySchemes",p,y);for(let p of e){let y=p.method,h=p.source??bt(y),v=At(t,p.path??"/"),k=p.status??200,T=Rt(y,h,p.input),q=De(h,p.input,"query"),C=De(h,p.input,"param"),O=kt(y,v),S=xt(p.output,s),a={[k]:S?{description:Pe,content:{"application/json":{schema:S}}}:{description:Pe}};if(s?.errors)for(let[r,l]of Object.entries(s.errors)){let{description:o,schema:f}=St(l);a[r]=f?{description:o,content:{"application/json":{schema:f}}}:{description:o};}i.registerPath({method:y,path:vt(v),operationId:O,summary:p.summary,description:p.description,tags:p.tags,deprecated:p.deprecated,security:p.security,request:{...q?{query:q}:{},...C?{params:C}:{},...T?{body:T}:{}},responses:a});}return new zodToOpenapi.OpenApiGeneratorV31(i.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function Rt(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 De(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function vt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function At(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,i=`${n}${s}`;return i===""?"/":i}function kt(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function qe(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 $e(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var fe=new async_hooks.AsyncLocalStorage;function He(){return async(e,t)=>{await fe.run({c:e},async()=>{await t();});}}var Ct=Object.freeze({}),ee=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=Dt(t.routes,t.api),t.services&&this.app.use("*",He());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=je(this.mountedRoutes,this.options.basePath??"",this.options.openapi,It(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=Y(t,i.path),u=i.middlewares??[],p=i.source??(i.method==="get"?"query":"json"),y=$t(i,p,n,Pt(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),h=i.method.toUpperCase();this.app.on(h,[c],...u,y),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=Y(this.options.basePath??"",n),c=s===false?null:Y(this.options.basePath??"",s),u;if($e(t.docsAuth)){let p=t.docsAuth;u=[p.middleware];let y=jt(c??i);for(let h of p.routes)this.app.on(h.method,[Y(y,h.name)],h.handler);}else u=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[i],...u,p=>p.json(this.buildOpenApiSpec())),c){let p=qt(c,i);this.app.on("GET",[c],...u,y=>y.html(qe(p,t.info.title)));}}};function Fe(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function Pt(e){if(e)return Fe(e)?e.handler:e}function It(e){return Fe(e)?e:void 0}function Dt(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 jt(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function qt(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 $t(e,t,n,s,i,c,u){let p=e.input,y=e.output,h=e.status??200,R=i??Ct;return async k=>{let T=async O=>{if(c){let S=await c.handle({error:O,c:k,route:e,services:R,logger:u});if(S)return S}return Ce(k,O)},q=async()=>{let O;if(p){let a;try{a=await Ht(k,t,e.method);}catch(f){throw new G(f instanceof Error?f.message:String(f))}let o=p.safeParse(a);if(!o.success)throw new U(o.error,t);O=o.data;}let S=await e.handler({input:O,c:k,services:R,errorHandler:c,logger:u});if(n&&y&&!(S instanceof Response)){let a=y.safeParse(S);if(!a.success)throw new W(a.error);return a.data}return S},C;if(s)try{C=await s({next:q,route:e,c:k,services:R,errorHandler:c,logger:u});}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,h)}}async function Ht(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 kn(e){let{basePath:t="/",repos:n,parseBody:s=true,securityHeaders:i,verbose:c=false,httpsOptions:u}=e,p=t==="/"?"":t.replace(/\/$/,""),y={};for(let[a,o]of Object.entries(n)){let f=o.schema??o.repo.schema??null;if(!f)throw new Error(`[createCrudServer] Repository "${a}" has no Zod schema.`);let r,l,m,g;if(o.fieldsConfig){let b=o.fieldsConfig;r=[],l=[],m=[],g=[];for(let[v,A]of Object.entries(b))for(let P of A)P==="filterable"?r.push(v):P==="orderable"?l.push(v):P==="mutable"?m.push(v):P==="create"&&g.push(v);l.length===0&&(l=r),r.length===0&&(r=void 0),l&&l.length===0&&(l=void 0),m.length===0&&(m=void 0),g.length===0&&(g=void 0);}let d=(()=>{let b=o.repo._parentKeys;return b&&b.length>0?b:void 0})();if(d&&g)for(let b of d)g.includes(b)||g.push(b);let w={name:a,path:o.path,repo:o.repo,schema:f,systemKeys:o.repo._systemKeys??[o.documentKey??"docId"],documentKey:o.documentKey??"docId",pathKey:o.repo._pathKey??void 0,isGroup:!!o.repo._isGroup,parentKeys:d,createdKey:o.repo._createdKey??void 0,pageSize:o.pageSize??25,filterableFields:r,orderableFields:l,mutableFields:m,createFields:g,allowDelete:o.allowDelete??false,allowedIncludes:o.allowedIncludes,validate:o.validate,rules:o.rules};y[a]=w;}let h=Ee(y,p,c),R=e.openapi,k=R&&typeof R=="object"?R:{},T=null;function q(){return T||(T=le(y,p,{...k,auth:k.auth??false})),T}let C=[];for(let a of Object.keys(y))C.push({api:"crud",method:"get",path:`/${a}`,source:"query",handler:h.handleList}),C.push({api:"crud",method:"post",path:`/${a}/query`,source:"json",handler:h.handleQuery}),C.push({api:"crud",method:"get",path:`/${a}/:id`,source:"query",handler:h.handleGet}),C.push({api:"crud",method:"post",path:`/${a}`,source:"json",handler:h.handleCreate}),C.push({api:"crud",method:"put",path:`/${a}/:id`,source:"json",handler:o=>h.handleUpdate(o,false)}),C.push({api:"crud",method:"patch",path:`/${a}/:id`,source:"json",handler:o=>h.handleUpdate(o,true)}),C.push({api:"crud",method:"delete",path:`/${a}/:id`,source:"query",handler:h.handleDelete}),C.push({api:"crud",method:"post",path:`/${a}/batch`,source:"json",handler:h.handleBatch});let O=new ee({...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(a,o)=>{if(a.req.method==="OPTIONS")return a.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"});a.header("Access-Control-Allow-Origin","*"),a.header("Access-Control-Allow-Credentials","true"),await o();},...e.middlewares||[]]});if(R!==false&&(O.buildOpenApiSpec=q),i!==false){let{securityHeaders:a}=(_e(),Qe(Me)),o=i===void 0?{csp:false}:i;O.hono.use("*",async(f,r)=>{let l=a(o);await new Promise(m=>{let g=f.req.raw;l(g,{setHeader:(w,b)=>f.header(w,b),removeHeader:w=>f.res.headers.delete(w)},()=>m());}),await r();});}let S=O.nodeHandler;return S.spec=q,u&&(S.httpsOptions=u),S}exports.createCrudServer=kn;exports.generateOpenAPISpec=le;//# sourceMappingURL=index.cjs.map
12
+ </html>`}function $e(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var fe=new async_hooks.AsyncLocalStorage;function He(){return async(e,t)=>{await fe.run({c:e},async()=>{await t();});}}var Ct=Object.freeze({}),ee=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=Dt(t.routes,t.api),t.services&&this.app.use("*",He());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=je(this.mountedRoutes,this.options.basePath??"",this.options.openapi,It(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=Y(t,i.path),u=i.middlewares??[],p=i.source??(i.method==="get"?"query":"json"),y=$t(i,p,n,Pt(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),h=i.method.toUpperCase();this.app.on(h,[c],...u,y),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=Y(this.options.basePath??"",n),c=s===false?null:Y(this.options.basePath??"",s),u;if($e(t.docsAuth)){let p=t.docsAuth;u=[p.middleware];let y=jt(c??i);for(let h of p.routes)this.app.on(h.method,[Y(y,h.name)],h.handler);}else u=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[i],...u,p=>p.json(this.buildOpenApiSpec())),c){let p=qt(c,i);this.app.on("GET",[c],...u,y=>y.html(qe(p,t.info.title)));}}};function Fe(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function Pt(e){if(e)return Fe(e)?e.handler:e}function It(e){return Fe(e)?e:void 0}function Dt(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 jt(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function qt(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 $t(e,t,n,s,i,c,u){let p=e.input,y=e.output,h=e.status??200,v=i??Ct;return async k=>{let T=async O=>{if(c){let S=await c.handle({error:O,c:k,route:e,services:v,logger:u});if(S)return S}return Ce(k,O)},q=async()=>{let O;if(p){let a;try{a=await Ht(k,t,e.method);}catch(l){throw new G(l instanceof Error?l.message:String(l))}let r=p.safeParse(a);if(!r.success)throw new U(r.error,t);O=r.data;}let S=await e.handler({input:O,c:k,services:v,errorHandler:c,logger:u});if(n&&y&&!(S instanceof Response)){let a=y.safeParse(S);if(!a.success)throw new W(a.error);return a.data}return S},C;if(s)try{C=await s({next:q,route:e,c:k,services:v,errorHandler:c,logger:u});}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,h)}}async function Ht(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 An(e){let{basePath:t="/",repos:n,parseBody:s=true,securityHeaders:i,verbose:c=false,httpsOptions:u}=e,p=t==="/"?"":t.replace(/\/$/,""),y={};for(let[a,r]of Object.entries(n)){if(!r.repo)throw new Error(`[createCrudServer] Repository "${a}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let l=r.schema??r.repo.schema??null;if(!l)throw new Error(`[createCrudServer] Repository "${a}" has no Zod schema.`);let o,f,m,g;if(r.fieldsConfig){let x=r.fieldsConfig;o=[],f=[],m=[],g=[];for(let[R,A]of Object.entries(x))for(let P of A)P==="filterable"?o.push(R):P==="orderable"?f.push(R):P==="mutable"?m.push(R):P==="create"&&g.push(R);f.length===0&&(f=o),o.length===0&&(o=void 0),f&&f.length===0&&(f=void 0),m.length===0&&(m=void 0),g.length===0&&(g=void 0);}let d=(()=>{let x=r.repo._parentKeys;return x&&x.length>0?x:void 0})();if(d&&g)for(let x of d)g.includes(x)||g.push(x);let w={name:a,path:r.path,repo:r.repo,schema:l,systemKeys:r.repo._systemKeys??[r.documentKey??"docId"],documentKey:r.documentKey??"docId",pathKey:r.repo._pathKey??void 0,isGroup:!!r.repo._isGroup,parentKeys:d,createdKey:r.repo._createdKey??void 0,pageSize:r.pageSize??25,filterableFields:o,orderableFields:f,mutableFields:m,createFields:g,allowDelete:r.allowDelete??false,allowedIncludes:r.allowedIncludes,validate:r.validate,rules:r.rules};y[a]=w;}let h=Ee(y,p,c),v=e.openapi,k=v&&typeof v=="object"?v:{},T=null;function q(){return T||(T=le(y,p,{...k,auth:k.auth??false})),T}let C=[];for(let a of Object.keys(y))C.push({api:"crud",method:"get",path:`/${a}`,source:"query",handler:h.handleList}),C.push({api:"crud",method:"post",path:`/${a}/query`,source:"json",handler:h.handleQuery}),C.push({api:"crud",method:"get",path:`/${a}/:id`,source:"query",handler:h.handleGet}),C.push({api:"crud",method:"post",path:`/${a}`,source:"json",handler:h.handleCreate}),C.push({api:"crud",method:"put",path:`/${a}/:id`,source:"json",handler:r=>h.handleUpdate(r,false)}),C.push({api:"crud",method:"patch",path:`/${a}/:id`,source:"json",handler:r=>h.handleUpdate(r,true)}),C.push({api:"crud",method:"delete",path:`/${a}/:id`,source:"query",handler:h.handleDelete}),C.push({api:"crud",method:"post",path:`/${a}/batch`,source:"json",handler:h.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(a,r)=>{if(a.req.method==="OPTIONS")return a.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"});a.header("Access-Control-Allow-Origin","*"),a.header("Access-Control-Allow-Credentials","true"),await r();},...e.middlewares||[]]});if(v!==false&&(O.buildOpenApiSpec=q),i!==false){let{securityHeaders:a}=(_e(),Qe(Me)),r=i===void 0?{csp:false}:i;O.hono.use("*",async(l,o)=>{let f=a(r);await new Promise(m=>{let g=l.req.raw;f(g,{setHeader:(w,x)=>l.header(w,x),removeHeader:w=>l.res.headers.delete(w)},()=>m());}),await o();});}let S=O.nodeHandler;return S.spec=q,u&&(S.httpsOptions=u),S}exports.createCrudServer=An;exports.generateOpenAPISpec=le;//# sourceMappingURL=index.cjs.map
13
13
  //# sourceMappingURL=index.cjs.map