@lpdjs/firestore-repo-service 2.6.46 → 2.6.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +51 -51
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +51 -51
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +1 -1
- package/dist/llms.txt +1 -1
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/index.cjs +1 -1
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.js +1 -1
- package/dist/servers/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {randomBytes}from'crypto';import {z as z$1}from'zod';import {Timestamp}from'firebase-admin/firestore';import {extendZodWithOpenApi,getOpenApiMetadata,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {AsyncLocalStorage}from'async_hooks';var oe=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Xe=Object.prototype.hasOwnProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var et=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:true});},tt=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ve(t))!Xe.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(s=Qe(t,i))||s.enumerable});return e};var nt=e=>tt(oe({},"__esModule",{value:true}),e);var Ge={};et(Ge,{DEFAULT_HTML_CSP:()=>Ze,securityHeaders:()=>Kt});function Kt(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,d)=>{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 d();}}var Ue,Ke,Ze,We=Ye(()=>{Ue="https://cdn.jsdelivr.net",Ke="https://www.gstatic.com",Ze=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Ue} ${Ke}`,`style-src 'self' 'unsafe-inline' ${Ue}`,`connect-src 'self' ${Ke} 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 be="preserve";function Se(){return be}function rt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function xe(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(rt(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Re(e){return e}var st=new Set(["<","<=",">",">=","!="]),it=new Set(["array-contains","array-contains-any"]);function ie(e){return e==="desc"?"DESCENDING":"ASCENDING"}function at(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function ct(e,t,n,s,i){let c=[],a=new Set;for(let u of s)if(u.op==="=="||u.op==="in"||u.op==="not-in"){if(a.has(u.field))continue;a.add(u.field),c.push({fieldPath:u.field,order:"ASCENDING"});}for(let u of s)if(it.has(u.op)){if(a.has(u.field))continue;a.add(u.field),c.push({fieldPath:u.field,arrayConfig:"CONTAINS"});}for(let u of s)if(st.has(u.op)){if(a.has(u.field))continue;a.add(u.field);let m=i?.field===u.field?ie(i.dir):"ASCENDING";c.push({fieldPath:u.field,order:m});}if(i&&!a.has(i.field)&&c.push({fieldPath:i.field,order:ie(i.dir)}),c.length===1&&n)return pt(e,t,c[0]);let d=i&&c.some(u=>u.fieldPath===i.field)?ie(i.dir):"ASCENDING";return c.push({fieldPath:"__name__",order:d}),dt(e,t,n,c)}function dt(e,t,n,s,i="(default)"){let c=`projects/${e}/databases/${i}/collectionGroups/${t}/indexes/_`,a=[...de(1,c),...V(2,n?2:1)];for(let m of s)a.push(...ve(3,Ae(m)));let d=i==="(default)"?"-default-":i,u=encodeURIComponent(ke(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${d}/indexes?create_composite=${u}`}function ut(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function ae(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function ce(e,t){return e<<3|t}function de(e,t){let n=Array.from(new TextEncoder().encode(t));return [ce(e,2),...ae(n.length),...n]}function V(e,t){return [ce(e,0),...ae(t)]}function ve(e,t){return [ce(e,2),...ae(t.length),...t]}function Ae(e){let t=[...de(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...V(3,1)):t.push(...V(2,e.order==="DESCENDING"?2:1)),t}function ke(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 pt(e,t,n,s="(default)"){let i=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,c=[...de(1,i),...V(2,2),...ve(3,Ae(n))],a=s==="(default)"?"-default-":s,d=encodeURIComponent(ke(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${d}`}function lt(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 ft(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Oe(e,t){let n=e??{},s=ft(e),i;if(s&&(i=n.message?ut(n.message):void 0,!i)){let c=lt(t.ref);if(c){let a=at(t.path);i=ct(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 le(e,t,n=200){let s=Re(t);return e.json(s,n)}function L(e,t,n,s=200){return le(e,{success:true,data:t,meta:n},s)}function b(e,t,n=400){return le(e,{success:false,error:t},n)}function ue(e,t,n,s,i){let c=Oe(t,n),a=c.type==="index",d=a?424:500,m={success:false,error:a?c.message:i&&t instanceof Error?t.message:s};return a&&(m.errorType="index",c.indexUrl&&(m.indexUrl=c.indexUrl)),le(e,m,d)}var pe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Te(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let s=t[n];s>=pe.length*4||(e+=pe.charAt(s%pe.length));}}return e}function U(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z$1.preprocess(s=>xe(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,i={};for(let[c,a]of Object.entries(s))i[c]=U(a);return z$1.object(i)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return z$1.array(U(s))}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(s)return U(s).optional()}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(s)return U(s).nullable()}if(n==="ZodDefault"||n==="default"){let s=t.innerType,i=t.defaultValue;if(s){let c=U(s);return typeof i=="function"?c.default(i()):c.default(i)}}return e}function mt(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 d=a.split(".")[0];d&&s[d]&&(i[d]=s[d]);}return z$1.object(i)}function X(e,t,n,s=false,i=[]){try{let c=mt(e,n,i),a=s?c.partial():c;return {success:!0,data:(Se()==="normalize"?U(a):a).parse(t)}}catch(c){return c instanceof z$1.ZodError?{success:false,error:`Validation failed: ${c.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function Y(e,t,n){let s=e?.shape?.[t];if(!s||typeof s.safeParse!="function")return {success:true,data:n};let i=s.safeParse(n);if(i.success)return {success:true,data:i.data};if(Array.isArray(n)){let a=[];for(let d of n){let u=s.safeParse(d);if(u.success)a.push(u.data);else return {success:false,error:u.error.issues.map(v=>v.message).join(", ")}}return {success:true,data:a}}return {success:false,error:i.error.issues.map(a=>a.message).join(", ")}}function ht(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 d=Array.isArray(a)?a[0]:a;if(d===void 0||d==="")continue;let u=c.match(/^(\w+)__(\w+)$/),m,v="==";if(u&&u[1]&&u[2]){m=u[1];let I=u[2];if(i[I])v=i[I];else continue}else if(!u)m=c;else continue;if(s&&!s.has(m))continue;let R=d;v==="in"||v==="not-in"||v==="array-contains-any"?R=d.split(",").map(I=>Ee(I.trim())):R=Ee(d),n.push({field:m,op:v,value:R});}return n}function Ee(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 ee(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Ce(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 d=await a.doc(s).get();if(d.exists)return d}if(i&&i.includes("/")&&a&&typeof a.doc=="function"){let d=await a.doc(i).get();if(d.exists)return d}if(i&&typeof c.doc=="function"){let d=await c.doc(i).get();if(d.exists)return d}return}catch{return}}function Pe(e,t,n){async function s(p,r,y,o){if(!r.rules)return true;let f=r.rules?.[y];if(!f)return b(p,`Operation "${y}" is not allowed for this repository`,403),false;try{return await f(o)?!0:b(p,"Forbidden",403)}catch(h){let g=n&&h instanceof Error?h.message:"Forbidden";return b(p,g,403)}}async function i(p,r,y,o){if(!p.rules)return o;let f=p.rules?.filter;if(!f)return o;let h=[];for(let g of o)try{await f({user:r,doc:g,params:y})&&h.push(g);}catch{}return h}function c(p){return p.get("user")??p.get("docsUser")??null}function a(p,r){if(!p){let y=r.req.path.split("/");for(let o of y)if(e[o]){p=o;break}}return !p||!e[p]?null:e[p]??null}function d(p,r){if(!r)return;let y=p[r];if(typeof y!="string"||!y)return;let o=y.split("/").filter(Boolean),f=[];for(let h=1;h<o.length;h+=2)f.push(o[h]);return f.length>0?f:void 0}async function u(p,r){let y=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,o=p.repo.get[y];if(typeof o=="function")try{let h=await o(r);if(h)return h}catch{}return (await p.repo.query.by({where:[[p.documentKey,"==",r]],limit:1}))[0]??null}async function m(p){let r=p.c,y=r.req.param(),o=a(y.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:y}))return;let h=[],g;try{let l=r.req.query(),w=Math.min(Number(l.pageSize)||o.pageSize,100),S=l.cursor,k=l.direction?.toLowerCase()==="prev"?"prev":"next",O=l.orderBy,j=l.orderDir?.toLowerCase()==="desc"?"desc":"asc",B=l.select,T=B?B.split(",").map(_=>_.trim()):void 0,x;o.allowedIncludes&&l.includes&&(x=(typeof l.includes=="string"?l.includes.split(",").map(M=>M.trim()):Array.isArray(l.includes)?l.includes:[]).filter(M=>typeof M=="string"&&o.allowedIncludes.includes(M)),x?.length===0&&(x=void 0));let E=ht(l,o.filterableFields);h=E.map(_=>({field:_.field,op:_.op,value:String(_.value??"")})),O&&(g={field:O,dir:j});let P={pageSize:w,direction:k};if(S)try{let _=typeof S=="string"?JSON.parse(S):S;P.cursor=await Ce(o,_);}catch{}if(O){if(o.orderableFields&&!o.orderableFields.includes(O))return b(r,`Field not orderable: ${O}`,400);P.orderBy=[{field:O,direction:j}];}if(E.length>0){P.where=[];for(let _ of E){let M=Y(o.schema,_.field,_.value);if(!M.success)return b(r,`Invalid filter value for '${_.field}': ${M.error}`,400);P.where.push([_.field,_.op,M.data]);}}T&&(P.select=T),x&&(P.include=x);let F=await o.repo.query.paginate(P),Je={items:await i(o,c(r),y,F.data),hasNextPage:F.hasNextPage,hasPrevPage:F.hasPrevPage,nextCursor:ee(F.nextCursor),prevCursor:ee(F.prevCursor)};return L(r,Je,{pageSize:w,hasMore:F.hasNextPage})}catch(l){ue(r,l,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:h,sort:g},"Failed to fetch documents",n);}}async function v(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let f=c(r);if(!await s(r,o,"list",{user:f,query:p.input||{},params:y}))return;let h=[],g;try{let l=p.input||{},w=Math.min(l.pageSize||o.pageSize,100),S=l.direction==="prev"?"prev":"next";l.where&&(h=l.where.map(T=>({field:String(T[0]),op:T[1],value:String(T[2]??"")}))),l.orderBy&&l.orderBy[0]&&(g={field:l.orderBy[0].field,dir:l.orderBy[0].direction==="desc"?"desc":"asc"});let k={pageSize:w,direction:S};if(l.cursor)try{let T=typeof l.cursor=="string"?JSON.parse(l.cursor):l.cursor;k.cursor=await Ce(o,T);}catch{}if(o.allowedIncludes&&l.includes&&l.includes.length>0){let T=l.includes.filter(x=>typeof x=="string"?o.allowedIncludes.includes(x):typeof x=="object"&&x!==null&&"relation"in x&&typeof x.relation=="string"?o.allowedIncludes.includes(x.relation):!1);T.length>0&&(k.include=T);}if(l.where&&l.where.length>0){if(o.filterableFields){let x=new Set(o.filterableFields),E=l.where.filter(P=>!x.has(P[0]));if(E.length>0){b(r,`Fields not filterable: ${E.map(P=>P[0]).join(", ")}`,400);return}}let T=[];for(let x of l.where){let E=Y(o.schema,x[0],x[2]);if(!E.success){b(r,`Invalid filter value for '${x[0]}': ${E.error}`,400);return}T.push([x[0],x[1],E.data]);}k.where=T;}if(l.orWhere&&l.orWhere.length>0){if(o.filterableFields){let x=new Set(o.filterableFields),E=l.orWhere.filter(P=>!x.has(P[0]));if(E.length>0){b(r,`Fields not filterable: ${E.map(P=>P[0]).join(", ")}`,400);return}}let T=[];for(let x of l.orWhere){let E=Y(o.schema,x[0],x[2]);if(!E.success){b(r,`Invalid filter value for '${x[0]}': ${E.error}`,400);return}T.push([x[0],x[1],E.data]);}k.orWhere=T;}if(l.orWhereGroups&&l.orWhereGroups.length>0){if(o.filterableFields){let x=new Set(o.filterableFields);for(let E of l.orWhereGroups){let P=E.filter(F=>!x.has(F[0]));if(P.length>0){b(r,`Fields not filterable: ${P.map(F=>F[0]).join(", ")}`,400);return}}}let T=[];for(let x of l.orWhereGroups){let E=[];for(let P of x){let F=Y(o.schema,P[0],P[2]);if(!F.success){b(r,`Invalid filter value for '${P[0]}': ${F.error}`,400);return}E.push([P[0],P[1],F.data]);}T.push(E);}k.orWhereGroups=T;}if(l.orderBy&&l.orderBy.length>0){if(o.orderableFields){let T=new Set(o.orderableFields),x=l.orderBy.filter(E=>!T.has(E.field));if(x.length>0){b(r,`Fields not orderable: ${x.map(E=>E.field).join(", ")}`,400);return}}k.orderBy=l.orderBy;}l.select&&l.select.length>0&&(k.select=l.select);let O=await o.repo.query.paginate(k),B={items:await i(o,c(r),y,O.data),hasNextPage:O.hasNextPage,hasPrevPage:O.hasPrevPage,nextCursor:ee(O.nextCursor),prevCursor:ee(O.prevCursor)};return L(r,B,{pageSize:w,hasMore:O.hasNextPage})}catch(l){ue(r,l,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:h,sort:g},"Failed to query documents",n);}}async function R(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let f=y.id;if(!f)return b(r,"Document ID required",400);try{let h=await u(o,f);if(!h)return b(r,"Document not found",404);let g=c(r);if(!await s(r,o,"get",{user:g,doc:h,params:y}))return;if(o.rules?.filter)try{if(!await o.rules.filter({user:g,doc:h,params:y}))return b(r,"Document not found",404)}catch{return b(r,"Document not found",404)}return L(r,h)}catch(h){ue(r,h,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:[{field:o.documentKey,op:"==",value:f}]},"Failed to fetch document",n);}}async function I(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);try{let f=p.input||{},h=c(r);if(!await s(r,o,"create",{user:h,body:f,params:y}))return;let g=X(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 l;if(o.isGroup&&o.parentKeys&&o.parentKeys.length>0){let w={...g.data};o.createdKey&&(w[o.createdKey]=new Date);let S=o.parentKeys.filter(j=>!w[j]);if(S.length>0){b(r,`Missing parent key(s) for subcollection create: ${S.join(", ")}`,400);return}let k=o.parentKeys.map(j=>w[j]),O=w[o.documentKey]||Te();l=await o.repo.set(...k,O,w);}else l=await o.repo.create(g.data);return L(r,l,void 0,201)}catch(f){let h=n&&f instanceof Error?f.message:"Failed to create document";return b(r,h,500)}}async function $(p,r){let y=p.c,o=y.req.param(),f=a(o.repoName,y);if(!f)return b(y,"Repository not found",404);let h=o.id;if(!h)return b(y,"Document ID required",400);try{let g=p.input||{},l=await u(f,h);if(!l)return b(y,"Document not found",404);let w=c(y);if(!await s(y,f,"update",{user:w,doc:l,body:g,params:o}))return;let S=X(f.schema,g,f.mutableFields,r,f.systemKeys);if(!S.success)return b(y,S.error,400);if(f.validate){let j=await f.validate(S.data,"update");if(j)return b(y,j,400)}let k=d(l,f.pathKey)??[h],O=await f.repo.update(...k,S.data);return L(y,O)}catch(g){let l=n&&g instanceof Error?g.message:"Failed to update document";return b(y,l,500)}}async function D(p){let r=p.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 f=y.id;if(!f)return b(r,"Document ID required",400);try{let h=await u(o,f);if(!h)return b(r,"Document not found",404);let g=c(r);if(!await s(r,o,"delete",{user:g,doc:h,params:y}))return;let l=d(h,o.pathKey)??[f];return await o.repo.delete(...l),L(r,{deleted:!0})}catch(h){let g=n&&h instanceof Error?h.message:"Failed to delete document";return b(r,g,500)}}function C(p){return p.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 A(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);try{let f=p.input||{};if(!Array.isArray(f.operations))return b(r,"operations array is required",400);let h=c(r),g=o.repo.batch.create(),l=[];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:h,body:w.data,params:y}))return;let S=X(o.schema,w.data,o.createFields,!1,o.systemKeys);if(!S.success)return b(r,S.error,400);let k=w.data[o.documentKey]||Te(),O={...S.data};if(o.createdKey&&(O[o.createdKey]=new Date),o.isGroup&&o.parentKeys){let j=o.parentKeys.map(B=>O[B]);g.set(...j,k,O);}else g.set(k,O);l.push({op:"create",id:k});}else if(w.type==="update"){if(!w.id)return b(r,"id required for update",400);let S=await u(o,w.id);if(!S)return b(r,`Document ${w.id} not found`,404);if(!await s(r,o,"update",{user:h,doc:S,body:w.data,params:y}))return;let k=X(o.schema,w.data,o.mutableFields,!0,o.systemKeys);if(!k.success)return b(r,k.error,400);let O=d(S,o.pathKey)??[w.id];g.update(...O,k.data),l.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 S=await u(o,w.id);if(!S)return b(r,`Document ${w.id} not found`,404);if(!await s(r,o,"delete",{user:h,doc:S,params:y}))return;let k=d(S,o.pathKey)??[w.id];g.delete(...k),l.push({op:"delete",id:w.id});}}return await g.commit(),L(r,{results:l})}catch(f){let h=n&&f instanceof Error?f.message:"Batch operation failed";return b(r,h,500)}}return {handleList:m,handleQuery:v,handleGet:R,handleCreate:I,handleUpdate:$,handleDelete:D,handleBatch:A,handleOptions:C}}function te(e){try{return z$1.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&Object.assign(t.jsonSchema,n);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 z(e){return {$ref:`#/components/schemas/${e}`}}function q(e){return {description:e,content:{"application/json":{schema:z("ErrorResponse")}}}}function K(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Ie(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 W(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function wt(e,t){let n=t.split("."),s=W(e);for(let i=0;i<n.length;i++){let c=n[i];if(!c)continue;let a=s?.shape;if(!a||!a[c])return;s=W(a[c]);}return s}function De(e,t="",n=0){if(n>5)return [];let i=W(e)?.shape;if(!i)return [];let c=[];for(let[a,d]of Object.entries(i)){let u=t?`${t}.${a}`:a,m=W(d);m?.shape&&typeof m.shape=="object"?c.push(...De(m,u,n+1)):c.push({path:u,zodSchema:d});}return c}function me(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:wt(e.schema,t)})):De(e.schema)}function ye(e){if(!e)return {type:"string"};let t=te(e);return delete t.$schema,delete t.title,t}function bt(e){let t=me(e),n=e.orderableFields??t.map(s=>s.path);return [{name:"pageSize",in:"query",schema:{type:"integer",default:e.pageSize,maximum:100},description:"Number of items per page"},{name:"cursor",in:"query",schema:{type:"string"},description:"Base64 pagination cursor"},{name:"orderBy",in:"query",schema:{type:"string",...n.length>0?{enum:n}:{}},description:"Field name to order by"},{name:"orderDir",in:"query",schema:{type:"string",enum:["asc","desc"]},description:"Order direction"},{name:"select",in:"query",schema:{type:"string"},description:`Comma-separated list of fields to return${t.length>0?` (${t.map(s=>s.path).join(", ")})`:""}`}]}function St(e){let t=me(e),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{path:c,zodSchema:a}of t){let d=ye(a);i.push({name:c,in:"query",schema:d,description:`Filter by ${c} (equality). Use 'null' or '__null__' for null values`});for(let u of n){let m=s[u]?` (${s[u]})`:"",v=u==="in"||u==="nin"||u==="containsAny";i.push({name:`${c}__${u}`,in:"query",schema:v?{type:"string",description:"Comma-separated list of values"}:d,description:`Filter ${c} with operator ${u}${m}`});}}return i}function je(){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 xt(e){let t=me(e),n=e.orderableFields??t.map(a=>a.path),s=t.map(a=>a.path);if(t.length===0)return je();let i=[];for(let{path:a,zodSchema:d}of t){let u=ye(d),m=W(d),R=m?._zod?.def?.type==="array"||m?._def?.typeName==="ZodArray"||m?._def?.type==="array"?ye(m?._zod?.def?.element??m?._def?.type??m?._def?.element):u;i.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},u],minItems:3,maxItems:3}),i.push({type:"array",description:`List condition on '${a}' (in, not-in)`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:u}],minItems:3,maxItems:3}),i.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},R],minItems:3,maxItems:3}),i.push({type:"array",description:`Array contains-any condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:R}],minItems:3,maxItems:3});}let c={oneOf:i};return {type:"object",properties:{where:{type:"array",items:c,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:c,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:c},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:s},description:"Fields to select (projection)"},pageSize:{type:"integer",maximum:100,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"}}}}function Rt(e,t,n,s,i,c="QueryRequestBody"){let a={},d=e.name,u=`${t}/${e.name}`,m=`${u}/{${e.documentKey}}`,v={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[u]={get:{operationId:`list${N(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[d],parameters:[...bt(e),...St(e)],responses:{200:Ie(z(n)),500:q("Internal server error")}},post:{operationId:`create${N(e.name)}`,summary:`Create a ${H(e.name)}`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:z(s??n)}}},responses:{201:K("Document created",z(n)),400:q("Validation error"),500:q("Internal server error")}}},a[`${u}/query`]={post:{operationId:`query${N(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:z(c)}}},responses:{200:Ie(z(n)),400:q("Invalid query"),500:q("Internal server error")}}},a[`${u}/batch`]={post:{operationId:`batch${N(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:z(`${n}BatchRequest`)}}},responses:{200:K("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:q("Validation error"),403:q("Forbidden"),404:q("Document not found"),500:q("Internal server error")}}};let R={};return R.get={operationId:`get${N(H(e.name))}`,summary:`Get a single ${H(e.name)}`,tags:[d],parameters:[v],responses:{200:K("Document found",z(n)),404:q("Document not found"),500:q("Internal server error")}},R.put={operationId:`update${N(H(e.name))}`,summary:`Update a ${H(e.name)} (full replace)`,tags:[d],parameters:[v],requestBody:{required:true,content:{"application/json":{schema:z(i??n)}}},responses:{200:K("Document updated",z(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},R.patch={operationId:`patch${N(H(e.name))}`,summary:`Partially update a ${H(e.name)}`,tags:[d],parameters:[v],requestBody:{required:true,content:{"application/json":{schema:{allOf:[z(i??n)],description:"All fields are optional for partial updates"}}}},responses:{200:K("Document patched",z(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},e.allowDelete&&(R.delete={operationId:`delete${N(H(e.name))}`,summary:`Delete a ${H(e.name)}`,tags:[d],parameters:[v],responses:{200:K("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:q("Document not found"),500:q("Internal server error")}}),a[m]=R,a}function he(e,t,n={}){let{title:s="CRUD API",version:i="1.0.0",description:c,servers:a,auth:d=false}=n,u=t==="/"?"":t.replace(/\/$/,""),m={},v={},R=[];m.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},m.QueryRequestBody=je();for(let[C,A]of Object.entries(e)){let p=N(H(C)),r=`${p}Create`,y=`${p}Update`,o=`${p}QueryRequestBody`;m[p]=te(A.schema),m[o]=xt(A);let f=k=>{let O=k&&k.length>0?k:Object.keys(A.schema.shape),j={};for(let B of O){let T=B.split(".")[0];T&&A.schema.shape[T]&&!A.systemKeys.includes(T)&&(j[T]=A.schema.shape[T]);}return j},h=null,g=f(A.createFields);Object.keys(g).length>0&&(m[r]=te(z$1.object(g)),h=r);let l=null,w=f(A.mutableFields);Object.keys(w).length>0&&(m[y]=te(z$1.object(w)),l=y),m[`${p}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:z(h??p)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[z(l??p)],description:"Partial updates allowed"}},required:["type","id","data"]},...A.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let S=Rt(A,u,p,h,l,o);Object.assign(v,S),R.push({name:C,description:`Operations on ${C} (collection: ${A.path})`});}let I={},$;return d==="basic"?(I.basicAuth={type:"http",scheme:"basic"},$=[{basicAuth:[]}]):d==="bearer"&&(I.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:v,components:{schemas:m,...Object.keys(I).length>0?{securitySchemes:I}:{}},...$?{security:$}:{},tags:R}}function N(e){return e.charAt(0).toUpperCase()+e.slice(1)}function H(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 J=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},Q=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 J?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof Q?e.json({success:false,error:"Output validation failed",issues:qe(t.zodError)},500):null}extendZodWithOpenApi(z$1);var Fe="Successful response",_e="Error response";function Tt(e){return e==="get"?"query":"json"}function Et(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Ct(e){if(typeof e.safeParse=="function")return {description:_e,schema:e};let t=e;return {description:t.description??_e,schema:t.schema}}function He(e,t,n,s){let i=new OpenAPIRegistry;if(n.securitySchemes)for(let[d,u]of Object.entries(n.securitySchemes))i.registerComponent("securitySchemes",d,u);for(let d of e){let u=d.method,m=d.source??Tt(u),v=Dt(t,d.path??"/"),R=d.status??200,I=Pt(u,m,d.input),$=ze(m,d.input,"query"),D=ze(m,d.input,"param"),C=jt(u,v),A=Et(d.output,s),p={[R]:A?{description:Fe,content:{"application/json":{schema:A}}}:{description:Fe}};if(s?.errors)for(let[r,y]of Object.entries(s.errors)){let{description:o,schema:f}=Ct(y);p[r]=f?{description:o,content:{"application/json":{schema:f}}}:{description:o};}i.registerPath({method:u,path:It(v),operationId:C,summary:d.summary,description:d.description,tags:d.tags,deprecated:d.deprecated,security:d.security,request:{...$?{query:$}:{},...D?{params:D}:{},...I?{body:I}:{}},responses:p});}return new OpenApiGeneratorV31(i.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function Pt(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 ze(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function It(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Dt(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,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,""");return `<!doctype html>
|
|
1
|
+
import {randomBytes}from'crypto';import {z}from'zod';import {Timestamp}from'firebase-admin/firestore';import {extendZodWithOpenApi,getOpenApiMetadata,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {AsyncLocalStorage}from'async_hooks';var oe=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Xe=Object.prototype.hasOwnProperty;var Ye=(e,t)=>()=>(e&&(t=e(e=0)),t);var et=(e,t)=>{for(var n in t)oe(e,n,{get:t[n],enumerable:true});},tt=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ve(t))!Xe.call(e,i)&&i!==n&&oe(e,i,{get:()=>t[i],enumerable:!(s=Qe(t,i))||s.enumerable});return e};var nt=e=>tt(oe({},"__esModule",{value:true}),e);var Ge={};et(Ge,{DEFAULT_HTML_CSP:()=>Ze,securityHeaders:()=>Kt});function Kt(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(d,a,c)=>{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 c();}}var Ue,Ke,Ze,We=Ye(()=>{Ue="https://cdn.jsdelivr.net",Ke="https://www.gstatic.com",Ze=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Ue} ${Ke}`,`style-src 'self' 'unsafe-inline' ${Ue}`,`connect-src 'self' ${Ke} 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 be="preserve";function Se(){return be}function rt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function xe(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(rt(e))return new Date(e._seconds*1e3+Math.floor(e._nanoseconds/1e6));if(typeof e=="string"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function Re(e){return e}var st=new Set(["<","<=",">",">=","!="]),it=new Set(["array-contains","array-contains-any"]);function ie(e){return e==="desc"?"DESCENDING":"ASCENDING"}function at(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function ct(e,t,n,s,i){let d=[],a=new Set;for(let u of s)if(u.op==="=="||u.op==="in"||u.op==="not-in"){if(a.has(u.field))continue;a.add(u.field),d.push({fieldPath:u.field,order:"ASCENDING"});}for(let u of s)if(it.has(u.op)){if(a.has(u.field))continue;a.add(u.field),d.push({fieldPath:u.field,arrayConfig:"CONTAINS"});}for(let u of s)if(st.has(u.op)){if(a.has(u.field))continue;a.add(u.field);let m=i?.field===u.field?ie(i.dir):"ASCENDING";d.push({fieldPath:u.field,order:m});}if(i&&!a.has(i.field)&&d.push({fieldPath:i.field,order:ie(i.dir)}),d.length===1&&n)return pt(e,t,d[0]);let c=i&&d.some(u=>u.fieldPath===i.field)?ie(i.dir):"ASCENDING";return d.push({fieldPath:"__name__",order:c}),dt(e,t,n,d)}function dt(e,t,n,s,i="(default)"){let d=`projects/${e}/databases/${i}/collectionGroups/${t}/indexes/_`,a=[...de(1,d),...V(2,n?2:1)];for(let m of s)a.push(...ve(3,Ae(m)));let c=i==="(default)"?"-default-":i,u=encodeURIComponent(Oe(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${u}`}function ut(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function ae(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function ce(e,t){return e<<3|t}function de(e,t){let n=Array.from(new TextEncoder().encode(t));return [ce(e,2),...ae(n.length),...n]}function V(e,t){return [ce(e,0),...ae(t)]}function ve(e,t){return [ce(e,2),...ae(t.length),...t]}function Ae(e){let t=[...de(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...V(3,1)):t.push(...V(2,e.order==="DESCENDING"?2:1)),t}function Oe(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 pt(e,t,n,s="(default)"){let i=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,d=[...de(1,i),...V(2,2),...ve(3,Ae(n))],a=s==="(default)"?"-default-":s,c=encodeURIComponent(Oe(d));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function lt(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 ft(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function ke(e,t){let n=e??{},s=ft(e),i;if(s&&(i=n.message?ut(n.message):void 0,!i)){let d=lt(t.ref);if(d){let a=at(t.path);i=ct(d,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 le(e,t,n=200){let s=Re(t);return e.json(s,n)}function L(e,t,n,s=200){return le(e,{success:true,data:t,meta:n},s)}function b(e,t,n=400){return le(e,{success:false,error:t},n)}function ue(e,t,n,s,i){let d=ke(t,n),a=d.type==="index",c=a?424:500,m={success:false,error:a?d.message:i&&t instanceof Error?t.message:s};return a&&(m.errorType="index",d.indexUrl&&(m.indexUrl=d.indexUrl)),le(e,m,c)}var pe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Te(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let s=t[n];s>=pe.length*4||(e+=pe.charAt(s%pe.length));}}return e}function U(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z.preprocess(s=>xe(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,i={};for(let[d,a]of Object.entries(s))i[d]=U(a);return z.object(i)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return z.array(U(s))}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(s)return U(s).optional()}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(s)return U(s).nullable()}if(n==="ZodDefault"||n==="default"){let s=t.innerType,i=t.defaultValue;if(s){let d=U(s);return typeof i=="function"?d.default(i()):d.default(i)}}return e}function mt(e,t,n=[]){let s=e.shape,i={},d=t&&t.length>0?t:Object.keys(s);for(let a of d){if(n.includes(a))continue;let c=a.split(".")[0];c&&s[c]&&(i[c]=s[c]);}return z.object(i)}function X(e,t,n,s=false,i=[]){try{let d=mt(e,n,i),a=s?d.partial():d;return {success:!0,data:(Se()==="normalize"?U(a):a).parse(t)}}catch(d){return d instanceof z.ZodError?{success:false,error:`Validation failed: ${d.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}function Y(e,t,n){let s=e?.shape?.[t];if(!s||typeof s.safeParse!="function")return {success:true,data:n};let i=s.safeParse(n);if(i.success)return {success:true,data:i.data};if(Array.isArray(n)){let a=[];for(let c of n){let u=s.safeParse(c);if(u.success)a.push(u.data);else return {success:false,error:u.error.issues.map(v=>v.message).join(", ")}}return {success:true,data:a}}return {success:false,error:i.error.issues.map(a=>a.message).join(", ")}}function ht(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[d,a]of Object.entries(e)){if(a===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(d))continue;let c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let u=d.match(/^(\w+)__(\w+)$/),m,v="==";if(u&&u[1]&&u[2]){m=u[1];let I=u[2];if(i[I])v=i[I];else continue}else if(!u)m=d;else continue;if(s&&!s.has(m))continue;let R=c;v==="in"||v==="not-in"||v==="array-contains-any"?R=c.split(",").map(I=>Ee(I.trim())):R=Ee(c),n.push({field:m,op:v,value:R});}return n}function Ee(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 ee(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Ce(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 d=e.repo.ref,a=d?.firestore;if(s&&a&&typeof a.doc=="function"){let c=await a.doc(s).get();if(c.exists)return c}if(i&&i.includes("/")&&a&&typeof a.doc=="function"){let c=await a.doc(i).get();if(c.exists)return c}if(i&&typeof d.doc=="function"){let c=await d.doc(i).get();if(c.exists)return c}return}catch{return}}function Pe(e,t,n){async function s(p,r,y,o){if(!r.rules)return true;let f=r.rules?.[y];if(!f)return b(p,`Operation "${y}" is not allowed for this repository`,403),false;try{return await f(o)?!0:b(p,"Forbidden",403)}catch(h){let g=n&&h instanceof Error?h.message:"Forbidden";return b(p,g,403)}}async function i(p,r,y,o){if(!p.rules)return o;let f=p.rules?.filter;if(!f)return o;let h=[];for(let g of o)try{await f({user:r,doc:g,params:y})&&h.push(g);}catch{}return h}function d(p){return p.get("user")??p.get("docsUser")??null}function a(p,r){if(!p){let y=r.req.path.split("/");for(let o of y)if(e[o]){p=o;break}}return !p||!e[p]?null:e[p]??null}function c(p,r){if(!r)return;let y=p[r];if(typeof y!="string"||!y)return;let o=y.split("/").filter(Boolean),f=[];for(let h=1;h<o.length;h+=2)f.push(o[h]);return f.length>0?f:void 0}async function u(p,r){let y=`by${p.documentKey.charAt(0).toUpperCase()}${p.documentKey.slice(1)}`,o=p.repo.get[y];if(typeof o=="function")try{let h=await o(r);if(h)return h}catch{}return (await p.repo.query.by({where:[[p.documentKey,"==",r]],limit:1}))[0]??null}async function m(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let f=d(r);if(!await s(r,o,"list",{user:f,query:r.req.query(),params:y}))return;let h=[],g;try{let l=r.req.query(),w=Math.min(Number(l.pageSize)||o.pageSize,100),S=l.cursor,O=l.direction?.toLowerCase()==="prev"?"prev":"next",k=l.orderBy,j=l.orderDir?.toLowerCase()==="desc"?"desc":"asc",B=l.select,T=B?B.split(",").map(z=>z.trim()):void 0,x;o.allowedIncludes&&l.includes&&(x=(typeof l.includes=="string"?l.includes.split(",").map(M=>M.trim()):Array.isArray(l.includes)?l.includes:[]).filter(M=>typeof M=="string"&&o.allowedIncludes.includes(M)),x?.length===0&&(x=void 0));let E=ht(l,o.filterableFields);h=E.map(z=>({field:z.field,op:z.op,value:String(z.value??"")})),k&&(g={field:k,dir:j});let P={pageSize:w,direction:O};if(S)try{let z=typeof S=="string"?JSON.parse(S):S;P.cursor=await Ce(o,z);}catch{}if(k){if(o.orderableFields&&!o.orderableFields.includes(k))return b(r,`Field not orderable: ${k}`,400);P.orderBy=[{field:k,direction:j}];}if(E.length>0){P.where=[];for(let z of E){let M=Y(o.schema,z.field,z.value);if(!M.success)return b(r,`Invalid filter value for '${z.field}': ${M.error}`,400);P.where.push([z.field,z.op,M.data]);}}T&&(P.select=T),x&&(P.include=x);let F=await o.repo.query.paginate(P),Je={items:await i(o,d(r),y,F.data),hasNextPage:F.hasNextPage,hasPrevPage:F.hasPrevPage,nextCursor:ee(F.nextCursor),prevCursor:ee(F.prevCursor)};return L(r,Je,{pageSize:w,hasMore:F.hasNextPage})}catch(l){ue(r,l,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:h,sort:g},"Failed to fetch documents",n);}}async function v(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let f=d(r);if(!await s(r,o,"list",{user:f,query:p.input||{},params:y}))return;let h=[],g;try{let l=p.input||{},w=Math.min(l.pageSize||o.pageSize,100),S=l.direction==="prev"?"prev":"next";l.where&&(h=l.where.map(T=>({field:String(T[0]),op:T[1],value:String(T[2]??"")}))),l.orderBy&&l.orderBy[0]&&(g={field:l.orderBy[0].field,dir:l.orderBy[0].direction==="desc"?"desc":"asc"});let O={pageSize:w,direction:S};if(l.cursor)try{let T=typeof l.cursor=="string"?JSON.parse(l.cursor):l.cursor;O.cursor=await Ce(o,T);}catch{}if(o.allowedIncludes&&l.includes&&l.includes.length>0){let T=l.includes.filter(x=>typeof x=="string"?o.allowedIncludes.includes(x):typeof x=="object"&&x!==null&&"relation"in x&&typeof x.relation=="string"?o.allowedIncludes.includes(x.relation):!1);T.length>0&&(O.include=T);}if(l.where&&l.where.length>0){if(o.filterableFields){let x=new Set(o.filterableFields),E=l.where.filter(P=>!x.has(P[0]));if(E.length>0){b(r,`Fields not filterable: ${E.map(P=>P[0]).join(", ")}`,400);return}}let T=[];for(let x of l.where){let E=Y(o.schema,x[0],x[2]);if(!E.success){b(r,`Invalid filter value for '${x[0]}': ${E.error}`,400);return}T.push([x[0],x[1],E.data]);}O.where=T;}if(l.orWhere&&l.orWhere.length>0){if(o.filterableFields){let x=new Set(o.filterableFields),E=l.orWhere.filter(P=>!x.has(P[0]));if(E.length>0){b(r,`Fields not filterable: ${E.map(P=>P[0]).join(", ")}`,400);return}}let T=[];for(let x of l.orWhere){let E=Y(o.schema,x[0],x[2]);if(!E.success){b(r,`Invalid filter value for '${x[0]}': ${E.error}`,400);return}T.push([x[0],x[1],E.data]);}O.orWhere=T;}if(l.orWhereGroups&&l.orWhereGroups.length>0){if(o.filterableFields){let x=new Set(o.filterableFields);for(let E of l.orWhereGroups){let P=E.filter(F=>!x.has(F[0]));if(P.length>0){b(r,`Fields not filterable: ${P.map(F=>F[0]).join(", ")}`,400);return}}}let T=[];for(let x of l.orWhereGroups){let E=[];for(let P of x){let F=Y(o.schema,P[0],P[2]);if(!F.success){b(r,`Invalid filter value for '${P[0]}': ${F.error}`,400);return}E.push([P[0],P[1],F.data]);}T.push(E);}O.orWhereGroups=T;}if(l.orderBy&&l.orderBy.length>0){if(o.orderableFields){let T=new Set(o.orderableFields),x=l.orderBy.filter(E=>!T.has(E.field));if(x.length>0){b(r,`Fields not orderable: ${x.map(E=>E.field).join(", ")}`,400);return}}O.orderBy=l.orderBy;}l.select&&l.select.length>0&&(O.select=l.select);let k=await o.repo.query.paginate(O),B={items:await i(o,d(r),y,k.data),hasNextPage:k.hasNextPage,hasPrevPage:k.hasPrevPage,nextCursor:ee(k.nextCursor),prevCursor:ee(k.prevCursor)};return L(r,B,{pageSize:w,hasMore:k.hasNextPage})}catch(l){ue(r,l,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:h,sort:g},"Failed to query documents",n);}}async function R(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);let f=y.id;if(!f)return b(r,"Document ID required",400);try{let h=await u(o,f);if(!h)return b(r,"Document not found",404);let g=d(r);if(!await s(r,o,"get",{user:g,doc:h,params:y}))return;if(o.rules?.filter)try{if(!await o.rules.filter({user:g,doc:h,params:y}))return b(r,"Document not found",404)}catch{return b(r,"Document not found",404)}return L(r,h)}catch(h){ue(r,h,{ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:[{field:o.documentKey,op:"==",value:f}]},"Failed to fetch document",n);}}async function I(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);try{let f=p.input||{},h=d(r);if(!await s(r,o,"create",{user:h,body:f,params:y}))return;let g=X(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 l;if(o.isGroup&&o.parentKeys&&o.parentKeys.length>0){let w={...g.data};o.createdKey&&(w[o.createdKey]=new Date);let S=o.parentKeys.filter(j=>!w[j]);if(S.length>0){b(r,`Missing parent key(s) for subcollection create: ${S.join(", ")}`,400);return}let O=o.parentKeys.map(j=>w[j]),k=w[o.documentKey]||Te();l=await o.repo.set(...O,k,w);}else l=await o.repo.create(g.data);return L(r,l,void 0,201)}catch(f){let h=n&&f instanceof Error?f.message:"Failed to create document";return b(r,h,500)}}async function $(p,r){let y=p.c,o=y.req.param(),f=a(o.repoName,y);if(!f)return b(y,"Repository not found",404);let h=o.id;if(!h)return b(y,"Document ID required",400);try{let g=p.input||{},l=await u(f,h);if(!l)return b(y,"Document not found",404);let w=d(y);if(!await s(y,f,"update",{user:w,doc:l,body:g,params:o}))return;let S=X(f.schema,g,f.mutableFields,r,f.systemKeys);if(!S.success)return b(y,S.error,400);if(f.validate){let j=await f.validate(S.data,"update");if(j)return b(y,j,400)}let O=c(l,f.pathKey)??[h],k=await f.repo.update(...O,S.data);return L(y,k)}catch(g){let l=n&&g instanceof Error?g.message:"Failed to update document";return b(y,l,500)}}async function D(p){let r=p.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 f=y.id;if(!f)return b(r,"Document ID required",400);try{let h=await u(o,f);if(!h)return b(r,"Document not found",404);let g=d(r);if(!await s(r,o,"delete",{user:g,doc:h,params:y}))return;let l=c(h,o.pathKey)??[f];return await o.repo.delete(...l),L(r,{deleted:!0})}catch(h){let g=n&&h instanceof Error?h.message:"Failed to delete document";return b(r,g,500)}}function C(p){return p.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 A(p){let r=p.c,y=r.req.param(),o=a(y.repoName,r);if(!o)return b(r,"Repository not found",404);try{let f=p.input||{};if(!Array.isArray(f.operations))return b(r,"operations array is required",400);let h=d(r),g=o.repo.batch.create(),l=[];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:h,body:w.data,params:y}))return;let S=X(o.schema,w.data,o.createFields,!1,o.systemKeys);if(!S.success)return b(r,S.error,400);let O=w.data[o.documentKey]||Te(),k={...S.data};if(o.createdKey&&(k[o.createdKey]=new Date),o.isGroup&&o.parentKeys){let j=o.parentKeys.map(B=>k[B]);g.set(...j,O,k);}else g.set(O,k);l.push({op:"create",id:O});}else if(w.type==="update"){if(!w.id)return b(r,"id required for update",400);let S=await u(o,w.id);if(!S)return b(r,`Document ${w.id} not found`,404);if(!await s(r,o,"update",{user:h,doc:S,body:w.data,params:y}))return;let O=X(o.schema,w.data,o.mutableFields,!0,o.systemKeys);if(!O.success)return b(r,O.error,400);let k=c(S,o.pathKey)??[w.id];g.update(...k,O.data),l.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 S=await u(o,w.id);if(!S)return b(r,`Document ${w.id} not found`,404);if(!await s(r,o,"delete",{user:h,doc:S,params:y}))return;let O=c(S,o.pathKey)??[w.id];g.delete(...O),l.push({op:"delete",id:w.id});}}return await g.commit(),L(r,{results:l})}catch(f){let h=n&&f instanceof Error?f.message:"Batch operation failed";return b(r,h,500)}}return {handleList:m,handleQuery:v,handleGet:R,handleCreate:I,handleUpdate:$,handleDelete:D,handleBatch:A,handleOptions:C}}function te(e){try{return z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let s=t.zodSchema?._zod?.def;s&&(s.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):s.type==="bigint"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf&&(t.jsonSchema.type="string",t.jsonSchema.format="int64"));}})}catch(t){return typeof console<"u"&&console.warn&&console.warn("[generateOpenAPISpec] Failed to convert Zod schema to JSON Schema; falling back to {type:object}.",t),{type:"object"}}}function _(e){return {$ref:`#/components/schemas/${e}`}}function q(e){return {description:e,content:{"application/json":{schema:_("ErrorResponse")}}}}function K(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Ie(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 W(e){let t=e;for(;t;){let n=t._zod?.def??t._def;if(!n)break;if(n.innerType)t=n.innerType;else if(n.schema)t=n.schema;else if(n.type==="optional"||n.type==="nullable"||n.type==="default"||n.type==="catch"||n.type==="effects")t=n.innerType??n.schema;else break}return t}function wt(e,t){let n=t.split("."),s=W(e);for(let i=0;i<n.length;i++){let d=n[i];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(i===n.length-1)return c;s=W(c);}return s}function De(e,t="",n=0){if(n>5)return [];let i=W(e)?.shape;if(!i)return [];let d=[];for(let[a,c]of Object.entries(i)){let u=t?`${t}.${a}`:a,m=W(c);m?.shape&&typeof m.shape=="object"?(d.push({path:u,zodSchema:c}),d.push(...De(m,u,n+1))):d.push({path:u,zodSchema:c});}return d}function me(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:wt(e.schema,t)})):De(e.schema)}function ye(e){if(!e)return {type:"string"};let t=te(e);return delete t.$schema,delete t.title,t}function bt(e){let t=me(e),n=e.orderableFields??t.map(s=>s.path);return [{name:"pageSize",in:"query",schema:{type:"integer",default:e.pageSize,maximum:100},description:"Number of items per page"},{name:"cursor",in:"query",schema:{type:"string"},description:"Base64 pagination cursor"},{name:"orderBy",in:"query",schema:{type:"string",...n.length>0?{enum:n}:{}},description:"Field name to order by"},{name:"orderDir",in:"query",schema:{type:"string",enum:["asc","desc"]},description:"Order direction"},{name:"select",in:"query",schema:{type:"string"},description:`Comma-separated list of fields to return${t.length>0?` (${t.map(s=>s.path).join(", ")})`:""}`}]}function St(e){let t=me(e),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{path:d,zodSchema:a}of t){let c=ye(a);i.push({name:d,in:"query",schema:c,description:`Filter by ${d} (equality). Use 'null' or '__null__' for null values`});for(let u of n){let m=s[u]?` (${s[u]})`:"",v=u==="in"||u==="nin"||u==="containsAny";i.push({name:`${d}__${u}`,in:"query",schema:v?{type:"string",description:"Comma-separated list of values"}:c,description:`Filter ${d} with operator ${u}${m}`});}}return i}function je(){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 xt(e){let t=me(e),n=e.orderableFields??t.map(a=>a.path),s=t.map(a=>a.path);if(t.length===0)return je();let i=[];for(let{path:a,zodSchema:c}of t){let u=ye(c),m=W(c),R=m?._zod?.def?.type==="array"||m?._def?.typeName==="ZodArray"||m?._def?.type==="array"?ye(m?._zod?.def?.element??m?._def?.type??m?._def?.element):u;i.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},u],minItems:3,maxItems:3}),i.push({type:"array",description:`List condition on '${a}' (in, not-in)`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:u}],minItems:3,maxItems:3}),i.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},R],minItems:3,maxItems:3}),i.push({type:"array",description:`Array contains-any condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:R}],minItems:3,maxItems:3});}let d={oneOf:i};return {type:"object",properties:{where:{type:"array",items:d,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:d,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:d},description:"Advanced OR groups (AND within, OR across groups)"},orderBy:{type:"array",items:{type:"object",properties:{field:{type:"string",enum:n},direction:{type:"string",enum:["asc","desc"]}},required:["field"]}},select:{type:"array",items:{type:"string",enum:s},description:"Fields to select (projection)"},pageSize:{type:"integer",maximum:100,description:"Number of items per page"},cursor:{oneOf:[{type:"string"},{type:"object"}],description:"Pagination cursor"},direction:{type:"string",enum:["next","prev"],description:"Pagination direction"},includes:{type:"array",items:e.allowedIncludes&&e.allowedIncludes.length>0?{oneOf:[{type:"string",enum:e.allowedIncludes},{type:"object",properties:{relation:{type:"string",enum:e.allowedIncludes},select:{type:"array",items:{type:"string"}}},required:["relation"]}]}:{oneOf:[{type:"string"},{type:"object",properties:{relation:{type:"string"},select:{type:"array",items:{type:"string"}}},required:["relation"]}]},description:"Relations to include (populate)"}}}}function Rt(e,t,n,s,i,d="QueryRequestBody"){let a={},c=e.name,u=`${t}/${e.name}`,m=`${u}/{${e.documentKey}}`,v={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[u]={get:{operationId:`list${N(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[c],parameters:[...bt(e),...St(e)],responses:{200:Ie(_(n)),500:q("Internal server error")}},post:{operationId:`create${N(e.name)}`,summary:`Create a ${H(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(s??n)}}},responses:{201:K("Document created",_(n)),400:q("Validation error"),500:q("Internal server error")}}},a[`${u}/query`]={post:{operationId:`query${N(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(d)}}},responses:{200:Ie(_(n)),400:q("Invalid query"),500:q("Internal server error")}}},a[`${u}/batch`]={post:{operationId:`batch${N(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:_(`${n}BatchRequest`)}}},responses:{200:K("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:q("Validation error"),403:q("Forbidden"),404:q("Document not found"),500:q("Internal server error")}}};let R={};return R.get={operationId:`get${N(H(e.name))}`,summary:`Get a single ${H(e.name)}`,tags:[c],parameters:[v],responses:{200:K("Document found",_(n)),404:q("Document not found"),500:q("Internal server error")}},R.put={operationId:`update${N(H(e.name))}`,summary:`Update a ${H(e.name)} (full replace)`,tags:[c],parameters:[v],requestBody:{required:true,content:{"application/json":{schema:_(i??n)}}},responses:{200:K("Document updated",_(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},R.patch={operationId:`patch${N(H(e.name))}`,summary:`Partially update a ${H(e.name)}`,tags:[c],parameters:[v],requestBody:{required:true,content:{"application/json":{schema:{allOf:[_(i??n)],description:"All fields are optional for partial updates"}}}},responses:{200:K("Document patched",_(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},e.allowDelete&&(R.delete={operationId:`delete${N(H(e.name))}`,summary:`Delete a ${H(e.name)}`,tags:[c],parameters:[v],responses:{200:K("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:q("Document not found"),500:q("Internal server error")}}),a[m]=R,a}function he(e,t,n={}){let{title:s="CRUD API",version:i="1.0.0",description:d,servers:a,auth:c=false}=n,u=t==="/"?"":t.replace(/\/$/,""),m={},v={},R=[];m.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},m.QueryRequestBody=je();for(let[C,A]of Object.entries(e)){let p=N(H(C)),r=`${p}Create`,y=`${p}Update`,o=`${p}QueryRequestBody`;m[p]=te(A.schema),m[o]=xt(A);let f=O=>{let k=O&&O.length>0?O:Object.keys(A.schema.shape),j={};for(let B of k){let T=B.split(".")[0];T&&A.schema.shape[T]&&!A.systemKeys.includes(T)&&(j[T]=A.schema.shape[T]);}return j},h=null,g=f(A.createFields);Object.keys(g).length>0&&(m[r]=te(z.object(g)),h=r);let l=null,w=f(A.mutableFields);Object.keys(w).length>0&&(m[y]=te(z.object(w)),l=y),m[`${p}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[{type:"object",properties:{type:{type:"string",enum:["create"]},data:_(h??p)},required:["type","data"]},{type:"object",properties:{type:{type:"string",enum:["update"]},id:{type:"string"},data:{allOf:[_(l??p)],description:"Partial updates allowed"}},required:["type","id","data"]},...A.allowDelete?[{type:"object",properties:{type:{type:"string",enum:["delete"]},id:{type:"string"}},required:["type","id"]}]:[]]}}},required:["operations"]};let S=Rt(A,u,p,h,l,o);Object.assign(v,S),R.push({name:C,description:`Operations on ${C} (collection: ${A.path})`});}let I={},$;return c==="basic"?(I.basicAuth={type:"http",scheme:"basic"},$=[{basicAuth:[]}]):c==="bearer"&&(I.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},$=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:i,...d?{description:d}:{}},...a&&a.length>0?{servers:a}:{},paths:v,components:{schemas:m,...Object.keys(I).length>0?{securitySchemes:I}:{}},...$?{security:$}:{},tags:R}}function N(e){return e.charAt(0).toUpperCase()+e.slice(1)}function H(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 J=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},Q=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 J?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof Q?e.json({success:false,error:"Output validation failed",issues:qe(t.zodError)},500):null}extendZodWithOpenApi(z);var Fe="Successful response",ze="Error response";function Tt(e){return e==="get"?"query":"json"}function Et(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Ct(e){if(typeof e.safeParse=="function")return {description:ze,schema:e};let t=e;return {description:t.description??ze,schema:t.schema}}function He(e,t,n,s){let i=new OpenAPIRegistry;if(n.securitySchemes)for(let[c,u]of Object.entries(n.securitySchemes))i.registerComponent("securitySchemes",c,u);for(let c of e){let u=c.method,m=c.source??Tt(u),v=Dt(t,c.path??"/"),R=c.status??200,I=Pt(u,m,c.input),$=_e(m,c.input,"query"),D=_e(m,c.input,"param"),C=jt(u,v),A=Et(c.output,s),p={[R]:A?{description:Fe,content:{"application/json":{schema:A}}}:{description:Fe}};if(s?.errors)for(let[r,y]of Object.entries(s.errors)){let{description:o,schema:f}=Ct(y);p[r]=f?{description:o,content:{"application/json":{schema:f}}}:{description:o};}i.registerPath({method:u,path:It(v),operationId:C,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...$?{query:$}:{},...D?{params:D}:{},...I?{body:I}:{}},responses:p});}return new OpenApiGeneratorV31(i.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function Pt(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 _e(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function It(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Dt(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,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,""");return `<!doctype html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8" />
|
|
@@ -9,5 +9,5 @@ import {randomBytes}from'crypto';import {z as z$1}from'zod';import {Timestamp}fr
|
|
|
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 Be(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var ge=new AsyncLocalStorage;function Me(){return async(e,t)=>{await ge.run({c:e},async()=>{await t();});}}var
|
|
12
|
+
</html>`}function Be(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var ge=new AsyncLocalStorage;function Me(){return async(e,t)=>{await ge.run({c:e},async()=>{await t();});}}var zt=Object.freeze({}),re=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=Nt(t.routes,t.api),t.services&&this.app.use("*",Me());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 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=He(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 d=ne(t,i.path),a=i.middlewares??[],c=i.source??(i.method==="get"?"query":"json"),u=Lt(i,c,n,_t(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),m=i.method.toUpperCase();this.app.on(m,[d],...a,u),s&&console.log(`[HonoServer] ${i.method.toUpperCase().padEnd(6)} ${d}`);}}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),d=s===false?null:ne(this.options.basePath??"",s),a;if(Be(t.docsAuth)){let c=t.docsAuth;a=[c.middleware];let u=Bt(d??i);for(let m of c.routes)this.app.on(m.method,[ne(u,m.name)],m.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[i],...a,c=>c.json(this.buildOpenApiSpec())),d){let c=Mt(d,i);this.app.on("GET",[d],...a,u=>u.html(Ne(c,t.info.title)));}}};function Le(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function _t(e){if(e)return Le(e)?e.handler:e}function Ht(e){return Le(e)?e:void 0}function Nt(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 Mt(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 d=n.length-i;return [...Array(d).fill(".."),...s.slice(i)].join("/")||"./"}function Lt(e,t,n,s,i,d,a){let c=e.input,u=e.output,m=e.status??200,v=i??zt;return async R=>{let I=async C=>{if(d){let A=await d.handle({error:C,c:R,route:e,services:v,logger:a});if(A)return A}return $e(R,C)},$=async()=>{let C,A;try{A=await Ut(R,t,e.method);}catch(r){throw new J(r instanceof Error?r.message:String(r))}if(c){let r=c.safeParse(A);if(!r.success)throw new Z(r.error,t);C=r.data;}else C=A;let p=await e.handler({input:C,c:R,services:v,errorHandler:d,logger:a});if(n&&u&&!(p instanceof Response)){let r=u.safeParse(p);if(!r.success)throw new Q(r.error);return r.data}return p},D;if(s)try{D=await s({next:$,route:e,c:R,services:v,errorHandler:d,logger:a});}catch(C){let A=await I(C);if(A)return A;throw C}else try{D=await $();}catch(C){let A=await I(C);if(A)return A;throw C}return D instanceof Response?D:R.json(D,m)}}async function Ut(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 jn(e){let{basePath:t="/",repos:n,parseBody:s=true,securityHeaders:i,verbose:d=false,httpsOptions:a}=e,c=t==="/"?"":t.replace(/\/$/,""),u={};for(let[p,r]of Object.entries(n)){if(!r.repo)throw new Error(`[createCrudServer] Repository "${p}" 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 "${p}" has no Zod schema.`);let o,f,h,g;if(r.fieldsConfig){let S=r.fieldsConfig;o=[],f=[],h=[],g=[];for(let[O,k]of Object.entries(S))for(let j of k)j==="filterable"?o.push(O):j==="orderable"?f.push(O):j==="mutable"?h.push(O):j==="create"&&g.push(O);f.length===0&&(f=o),o.length===0&&(o=void 0),f&&f.length===0&&(f=void 0),h.length===0&&(h=void 0),g.length===0&&(g=void 0);}let l=(()=>{let S=r.repo._parentKeys;return S&&S.length>0?S:void 0})();if(l&&g)for(let S of l)g.includes(S)||g.push(S);let w={name:p,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:l,createdKey:r.repo._createdKey??void 0,pageSize:r.pageSize??25,filterableFields:o,orderableFields:f,mutableFields:h,createFields:g,allowDelete:r.allowDelete??false,allowedIncludes:r.allowedIncludes,validate:r.validate,rules:r.rules};u[p]=w;}let m=Pe(u,c,d),v=e.openapi,R=v&&typeof v=="object"?v:{},I=null;function $(){return I||(I=he(u,c,{...R,auth:R.auth??false})),I}let D=[];for(let p of Object.keys(u))D.push({api:"crud",method:"get",path:`/${p}`,source:"query",handler:m.handleList}),D.push({api:"crud",method:"post",path:`/${p}/query`,source:"json",handler:m.handleQuery}),D.push({api:"crud",method:"get",path:`/${p}/:id`,source:"query",handler:m.handleGet}),D.push({api:"crud",method:"post",path:`/${p}`,source:"json",handler:m.handleCreate}),D.push({api:"crud",method:"put",path:`/${p}/:id`,source:"json",handler:r=>m.handleUpdate(r,false)}),D.push({api:"crud",method:"patch",path:`/${p}/:id`,source:"json",handler:r=>m.handleUpdate(r,true)}),D.push({api:"crud",method:"delete",path:`/${p}/:id`,source:"query",handler:m.handleDelete}),D.push({api:"crud",method:"post",path:`/${p}/batch`,source:"json",handler:m.handleBatch});let C=new re({...e,openapi:v!==false?{path:R.path??"/openapi.json",docsPath:R.docsPath??"/docs",info:{title:R.title??"CRUD API",version:R.version??"1.0.0"},docsAuth:R.docsAuth}:void 0,basePath:t,api:"crud",routes:D,middlewares:[async(p,r)=>{if(p.req.method==="OPTIONS")return p.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"});p.header("Access-Control-Allow-Origin","*"),p.header("Access-Control-Allow-Credentials","true"),await r();},...e.middlewares||[]]});if(v!==false&&(C.buildOpenApiSpec=$),i!==false){let{securityHeaders:p}=(We(),nt(Ge)),r=i===void 0?{csp:false}:i;C.hono.use("*",async(y,o)=>{let f=p(r);await new Promise(h=>{let g=y.req.raw;f(g,{setHeader:(w,S)=>y.header(w,S),removeHeader:w=>y.res.headers.delete(w)},()=>h());}),await o();});}let A=C.nodeHandler;return A.spec=$,a&&(A.httpsOptions=a),A}export{jn as createCrudServer,he as generateOpenAPISpec};//# sourceMappingURL=index.js.map
|
|
13
13
|
//# sourceMappingURL=index.js.map
|