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