@lpdjs/firestore-repo-service 2.6.34 → 2.6.35
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 +47 -47
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +47 -47
- 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 +46 -46
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.js +46 -46
- package/dist/servers/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {randomBytes}from'crypto';import {z}from'zod';import {Timestamp}from'firebase-admin/firestore';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {AsyncLocalStorage}from'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 Be={};We(Be,{DEFAULT_HTML_CSP:()=>Me,securityHeaders:()=>Ft});function Ft(e={}){let t=e.csp===void 0?Me:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,s=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,i=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(a,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,Me,_e=Ge(()=>{ze="https://cdn.jsdelivr.net",Ne="https://www.gstatic.com",Me=["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 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 a=[],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),a.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),a.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";a.push({fieldPath:y.field,order:h});}if(i&&!u.has(i.field)&&a.push({fieldPath:i.field,order:re(i.dir)}),a.length===1&&n)return st(e,t,a[0]);let p=i&&a.some(y=>y.fieldPath===i.field)?re(i.dir):"ASCENDING";return a.push({fieldPath:"__name__",order:p}),rt(e,t,n,a)}function rt(e,t,n,s,i="(default)"){let a=`projects/${e}/databases/${i}/collectionGroups/${t}/indexes/_`,u=[...ie(1,a),...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}`,a=[...ie(1,i),...Q(2,2),...be(3,xe(n))],u=s==="(default)"?"-default-":s,p=encodeURIComponent(Se(a));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 a=it(t.ref);if(a){let u=tt(t.path);i=nt(a,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 B(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 a=ve(t,n),u=a.type==="index",p=u?424:500,h={success:false,error:u?a.message:i&&t instanceof Error?t.message:s};return u&&(h.errorType="index",a.indexUrl&&(h.indexUrl=a.indexUrl)),de(e,h,p)}var ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Re(){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>=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 z.preprocess(s=>he(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,i={};for(let[a,u]of Object.entries(s))i[a]=K(u);return z.object(i)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return 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 a=K(s);return typeof i=="function"?a.default(i()):a.default(i)}}return e}function dt(e,t,n=[]){let s=e.shape,i={},a=t&&t.length>0?t:Object.keys(s);for(let u of a){if(n.includes(u))continue;let p=u.split(".")[0];p&&s[p]&&(i[p]=s[p]);}return z.object(i)}function V(e,t,n,s=false,i=[]){try{let a=dt(e,n,i),u=s?a.partial():a;return {success:!0,data:(ge()==="normalize"?K(u):u).parse(t)}}catch(a){return a instanceof z.ZodError?{success:false,error:`Validation failed: ${a.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[a,u]of Object.entries(e)){if(u===void 0||["cursor","limit","pageSize","orderBy","orderDir","select"].includes(a))continue;let p=Array.isArray(u)?u[0]:u;if(p===void 0||p==="")continue;let y=a.match(/^(\w+)__(\w+)$/),h,R="==";if(y&&y[1]&&y[2]){h=y[1];let O=y[2];if(i[O])R=i[O];else continue}else if(!y)h=a;else continue;if(s&&!s.has(h))continue;let k=p;R==="in"||R==="not-in"||R==="array-contains-any"?k=p.split(",").map(O=>Ae(O.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(c,o,l,r){if(!o.rules)return true;let f=o.rules?.[l];if(!f)return x(c,`Operation "${l}" is not allowed for this repository`,403),false;try{return await f(r)?!0:x(c,"Forbidden",403)}catch(m){let g=n&&m instanceof Error?m.message:"Forbidden";return x(c,g,403)}}async function i(c,o,l,r){if(!c.rules)return r;let f=c.rules?.filter;if(!f)return r;let m=[];for(let g of r)try{await f({user:o,doc:g,params:l})&&m.push(g);}catch{}return m}function a(c){return c.get("user")??c.get("docsUser")??null}function u(c,o){return !c||!e[c]?x(o,`Repository "${c}" not found`,404):e[c]}function p(c,o){if(!o)return;let l=c[o];if(typeof l!="string"||!l)return;let r=l.split("/").filter(Boolean),f=[];for(let m=1;m<r.length;m+=2)f.push(r[m]);return f.length>0?f:void 0}async function y(c,o){let l=`by${c.documentKey.charAt(0).toUpperCase()}${c.documentKey.slice(1)}`,r=c.repo.get[l];if(typeof r=="function")try{let m=await r(o);if(m)return m}catch{}return (await c.repo.query.by({where:[[c.documentKey,"==",o]],limit:1}))[0]??null}async function h(c){let o=c.c,l=o.req.param(),r=u(l.repoName,o);if(!r)return;let f=a(o);if(!await s(o,r,"list",{user:f,query:o.req.query(),params:l}))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($=>$.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 D=ut(d,r.filterableFields);m=D.map($=>({field:$.field,op:$.op,value:String($.value??"")})),A&&(g={field:A,dir:P});let z={pageSize:w,direction:v};if(b)try{let $=typeof b=="string"?JSON.parse(b):b;z.cursor=await ke(r,$);}catch{}if(A){if(r.orderableFields&&!r.orderableFields.includes(A))return x(o,`Field not orderable: ${A}`,400);z.orderBy=[{field:A,direction:P}];}D.length>0&&(z.where=D.map($=>[$.field,$.op,$.value])),I&&(z.select=I),E&&(z.include=E);let _=await r.repo.query.paginate(z),Ke={items:await i(r,a(o),l,_.data),hasNextPage:_.hasNextPage,hasPrevPage:_.hasPrevPage,nextCursor:X(_.nextCursor),prevCursor:X(_.prevCursor)};return B(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(c){let o=c.c,l=o.req.param(),r=u(l.repoName,o);if(!r)return;let f=a(o);if(!await s(o,r,"list",{user:f,query:c.input||{},params:l}))return;let m=[],g;try{let d=c.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(D=>!I.has(D[0]));if(E.length>0){x(o,`Fields not filterable: ${E.map(D=>D[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(D=>!I.has(D[0]));if(E.length>0){x(o,`Fields not filterable: ${E.map(D=>D[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 D=E.filter(z=>!I.has(z[0]));if(D.length>0){x(o,`Fields not filterable: ${D.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(D=>!I.has(D.field));if(E.length>0){x(o,`Fields not orderable: ${E.map(D=>D.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,a(o),l,A.data),hasNextPage:A.hasNextPage,hasPrevPage:A.hasPrevPage,nextCursor:X(A.nextCursor),prevCursor:X(A.prevCursor)};return B(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(c){let o=c.c,l=o.req.param(),r=u(l.repoName,o);if(!r)return;let f=l.id;if(!f)return x(o,"Document ID required",400);try{let m=await y(r,f);if(!m)return x(o,"Document not found",404);let g=a(o);if(!await s(o,r,"get",{user:g,doc:m,params:l}))return;if(r.rules?.filter)try{if(!await r.rules.filter({user:g,doc:m,params:l}))return x(o,"Document not found",404)}catch{return x(o,"Document not found",404)}return B(o,m)}catch(m){ae(o,m,{ref:r.repo.ref,path:r.path,isGroup:!!r.isGroup,filters:[{field:r.documentKey,op:"==",value:f}]},"Failed to fetch document",n);}}async function O(c){let o=c.c,l=o.req.param(),r=u(l.repoName,o);if(r)try{let f=c.input||{},m=a(o);if(!await s(o,r,"create",{user:m,body:f,params:l}))return;let g=V(r.schema,f,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 B(o,d,void 0,201)}catch(f){let m=n&&f instanceof Error?f.message:"Failed to create document";return x(o,m,500)}}async function j(c,o){let l=c.c,r=l.req.param(),f=u(r.repoName,l);if(!f)return;let m=r.id;if(!m)return x(l,"Document ID required",400);try{let g=c.input||{},d=await y(f,m);if(!d)return x(l,"Document not found",404);let w=a(l);if(!await s(l,f,"update",{user:w,doc:d,body:g,params:r}))return;let b=V(f.schema,g,f.mutableFields,o,f.systemKeys);if(!b.success)return x(l,b.error,400);if(f.validate){let P=await f.validate(b.data,"update");if(P)return x(l,P,400)}let v=p(d,f.pathKey)??[m],A=await f.repo.update(...v,b.data);return B(l,A)}catch(g){let d=n&&g instanceof Error?g.message:"Failed to update document";return x(l,d,500)}}async function C(c){let o=c.c,l=o.req.param(),r=u(l.repoName,o);if(!r)return;if(!r.allowDelete)return x(o,"Delete not allowed for this repository",403);let f=l.id;if(!f)return x(o,"Document ID required",400);try{let m=await y(r,f);if(!m)return x(o,"Document not found",404);let g=a(o);if(!await s(o,r,"delete",{user:g,doc:m,params:l}))return;let d=p(m,r.pathKey)??[f];return await r.repo.delete(...d),B(o,{deleted:!0})}catch(m){let g=n&&m instanceof Error?m.message:"Failed to delete document";return x(o,g,500)}}function T(c){return c.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(c){let o=c.c,l=o.req.param(),r=u(l.repoName,o);if(r)try{let f=c.input||{};if(!Array.isArray(f.operations))return x(o,"operations array is required",400);let m=a(o),g=r.repo.batch.create(),d=[];for(let w of f.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:l}))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:l}))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:l}))return;let v=p(b,r.pathKey)??[w.id];g.delete(...v),d.push({op:"delete",id:w.id});}}return await g.commit(),B(o,{results:d})}catch(f){let m=n&&f instanceof Error?f.message:"Batch operation failed";return x(o,m,500)}}return {handleList:h,handleQuery:R,handleGet:k,handleCreate:O,handleUpdate:j,handleDelete:C,handleBatch:S,handleOptions:T}}function ue(e){try{return 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 F(e){return {$ref:`#/components/schemas/${e}`}}function q(e){return {description:e,content:{"application/json":{schema:F("ErrorResponse")}}}}function Z(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Te(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 a of n)s.push({name:`${i}__${a}`,in:"query",schema:{type:"string"},description:`Filter ${i} with operator ${a}`});}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 a={},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"};a[p]={get:{operationId:`list${M(e.name)}`,summary:`List ${e.name} (paginated)`,tags:[u],parameters:[...pt(e),...lt(e)],responses:{200:Te(F(n)),500:q("Internal server error")}},post:{operationId:`create${M(e.name)}`,summary:`Create a ${N(e.name)}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:F(s??n)}}},responses:{201:Z("Document created",F(n)),400:q("Validation error"),500:q("Internal server error")}}},a[`${p}/query`]={post:{operationId:`query${M(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:F("QueryRequestBody")}}},responses:{200:Te(F(n)),400:q("Invalid query"),500:q("Internal server error")}}};let R={};return R.get={operationId:`get${M(N(e.name))}`,summary:`Get a single ${N(e.name)}`,tags:[u],parameters:[h],responses:{200:Z("Document found",F(n)),404:q("Document not found"),500:q("Internal server error")}},R.put={operationId:`update${M(N(e.name))}`,summary:`Update a ${N(e.name)} (full replace)`,tags:[u],parameters:[h],requestBody:{required:true,content:{"application/json":{schema:F(i??n)}}},responses:{200:Z("Document updated",F(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},R.patch={operationId:`patch${M(N(e.name))}`,summary:`Partially update a ${N(e.name)}`,tags:[u],parameters:[h],requestBody:{required:true,content:{"application/json":{schema:{allOf:[F(i??n)],description:"All fields are optional for partial updates"}}}},responses:{200:Z("Document patched",F(n)),400:q("Validation error"),404:q("Document not found"),500:q("Internal server error")}},e.allowDelete&&(R.delete={operationId:`delete${M(N(e.name))}`,summary:`Delete a ${N(e.name)}`,tags:[u],parameters:[h],responses:{200:Z("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:q("Document not found"),500:q("Internal server error")}}),a[y]=R,a}function le(e,t,n={}){let{title:s="CRUD API",version:i="1.0.0",description:a,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[T,S]of Object.entries(e)){let c=M(N(T)),o=`${c}Create`,l=`${c}Update`;h[c]=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},f=null,m=r(S.createFields);Object.keys(m).length>0&&(h[o]=ue(z.object(m)),f=o);let g=null,d=r(S.mutableFields);Object.keys(d).length>0&&(h[l]=ue(z.object(d)),g=l);let w=yt(S,y,c,f,g);Object.assign(R,w),k.push({name:T,description:`Operations on ${T} (collection: ${S.path})`});}let O={},j;return p==="basic"?(O.basicAuth={type:"http",scheme:"basic"},j=[{basicAuth:[]}]):p==="bearer"&&(O.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},j=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:i,...a?{description:a}:{}},...u&&u.length>0?{servers:u}:{},paths:R,components:{schemas:h,...Object.keys(O).length>0?{securitySchemes:O}:{}},...j?{security:j}:{},tags:k}}function M(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 L=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 Oe(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function Ce(e,t){return t instanceof L?e.json({success:false,error:"Validation failed",issues:Oe(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:Oe(t.zodError)},500):null}extendZodWithOpenApi(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 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,O=vt(y,h,p.input),j=De(h,p.input,"query"),C=De(h,p.input,"param"),T=kt(y,R),S=xt(p.output,s),c={[k]:S?{description:Pe,content:{"application/json":{schema:S}}}:{description:Pe}};if(s?.errors)for(let[o,l]of Object.entries(s.errors)){let{description:r,schema:f}=St(l);c[o]=f?{description:r,content:{"application/json":{schema:f}}}:{description:r};}i.registerPath({method:y,path:Rt(R),operationId:T,summary:p.summary,description:p.description,tags:p.tags,deprecated:p.deprecated,security:p.security,request:{...j?{query:j}:{},...C?{params:C}:{},...O?{body:O}:{}},responses:c});}return new 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,""");return `<!doctype html>
|
|
1
|
+
import {randomBytes}from'crypto';import {z}from'zod';import {Timestamp}from'firebase-admin/firestore';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {extendZodWithOpenApi,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {AsyncLocalStorage}from'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 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=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 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 z.object(i)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return 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 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 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 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(z.object(m)),l=o);let g=null,d=r(S.mutableFields);Object.keys(d).length>0&&(h[f]=ue(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}extendZodWithOpenApi(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 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 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,""");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}from'zod';import {Timestamp}from'fire
|
|
|
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
|
|
12
|
+
</html>`}function $e(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var fe=new 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,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 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}export{kn as createCrudServer,le as generateOpenAPISpec};//# sourceMappingURL=index.js.map
|
|
13
13
|
//# sourceMappingURL=index.js.map
|