@lpdjs/firestore-repo-service 2.6.57 → 3.0.1
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/README.md +45 -27
- package/dist/{create-servers-BxkVVkg9.d.cts → create-servers-Cbvzs_ou.d.cts} +5 -5
- package/dist/{create-servers-B84cbslf.d.ts → create-servers-aWdDTcSu.d.ts} +5 -5
- package/dist/{firebase-auth-DZ8lb2Ec.d.cts → firebase-auth-Ds5P0kXT.d.cts} +1 -1
- package/dist/{firebase-auth-DZ8lb2Ec.d.ts → firebase-auth-Ds5P0kXT.d.ts} +1 -1
- package/dist/index.cjs +97 -85
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.js +97 -85
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +237 -263
- package/dist/llms.txt +5 -4
- package/dist/{openapi-BpbfjSHK.d.ts → openapi-BTu_1vSc.d.ts} +1 -1
- package/dist/{openapi-DG7aQUlX.d.cts → openapi-CoKsSOIU.d.cts} +1 -1
- package/dist/{queue-B4uwef6c.d.ts → queue-BQxyuEXb.d.ts} +8 -23
- package/dist/{queue-CQyWCQBk.d.cts → queue-CMiKvIW1.d.cts} +8 -23
- package/dist/rules-B3b-BZLf.d.cts +30 -0
- package/dist/rules-BJMT0N0i.d.ts +30 -0
- package/dist/servers/admin/index.d.cts +402 -6
- package/dist/servers/admin/index.d.ts +402 -6
- package/dist/servers/auth/index.d.cts +1 -1
- package/dist/servers/auth/index.d.ts +1 -1
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +7 -6
- package/dist/servers/crud/index.d.ts +7 -6
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/hono/index.d.cts +3 -3
- package/dist/servers/hono/index.d.ts +3 -3
- package/dist/servers/index.cjs +106 -94
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +10 -9
- package/dist/servers/index.d.ts +10 -9
- package/dist/servers/index.js +106 -94
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/bigquery.cjs +5 -5
- package/dist/sync/bigquery.cjs.map +1 -1
- package/dist/sync/bigquery.d.cts +28 -3
- package/dist/sync/bigquery.d.ts +28 -3
- package/dist/sync/bigquery.js +5 -5
- package/dist/sync/bigquery.js.map +1 -1
- package/dist/sync/index.cjs +74 -54
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.d.cts +63 -17
- package/dist/sync/index.d.ts +63 -17
- package/dist/sync/index.js +74 -54
- package/dist/sync/index.js.map +1 -1
- package/dist/sync/meilisearch.cjs +4 -0
- package/dist/sync/meilisearch.cjs.map +1 -0
- package/dist/sync/meilisearch.d.cts +114 -0
- package/dist/sync/meilisearch.d.ts +114 -0
- package/dist/sync/meilisearch.js +4 -0
- package/dist/sync/meilisearch.js.map +1 -0
- package/dist/{types-CE-EfugW.d.cts → types-B2e-T8EM.d.cts} +160 -8
- package/dist/{types-B4dMmfet.d.cts → types-BIZz3sxN.d.cts} +1 -1
- package/dist/{types-DT7Nypd_.d.ts → types-BbFZ57eK.d.ts} +101 -41
- package/dist/{types-DyKJJ9UQ.d.ts → types-DSMiiOrU.d.ts} +1 -1
- package/dist/{types-cY03CMya.d.ts → types-XRjVKN9r.d.ts} +160 -8
- package/dist/{types-BwH1C-wi.d.cts → types-zFrp8RnM.d.cts} +101 -41
- package/package.json +19 -1
- package/dist/index-D47y5giY.d.ts +0 -469
- package/dist/index-dW_7jrlK.d.cts +0 -469
|
@@ -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 ce=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var ot=Object.prototype.hasOwnProperty;var st=(e,t)=>()=>(e&&(t=e(e=0)),t);var it=(e,t)=>{for(var n in t)ce(e,n,{get:t[n],enumerable:true});},at=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of rt(t))!ot.call(e,o)&&o!==n&&ce(e,o,{get:()=>t[o],enumerable:!(i=nt(t,o))||i.enumerable});return e};var ct=e=>at(ce({},"__esModule",{value:true}),e);var Ye={};it(Ye,{DEFAULT_HTML_CSP:()=>Xe,securityHeaders:()=>Xt});function Xt(e={}){let t=e.csp===void 0?Xe: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 Je,Qe,Xe,et=st(()=>{Je="https://cdn.jsdelivr.net",Qe="https://www.gstatic.com",Xe=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${Je} ${Qe}`,`style-src 'self' 'unsafe-inline' ${Je}`,`connect-src 'self' ${Qe} 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 ve="preserve";function ue(){return ve}function dt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Re(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof firestore.Timestamp)return e.toDate();if(dt(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 Te(e){return e}function Oe(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var pt=new Set(["<","<=",">",">=","!="]),lt=new Set(["array-contains","array-contains-any"]);function pe(e){return e==="desc"?"DESCENDING":"ASCENDING"}function ft(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function yt(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(lt.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(pt.has(u.op)){if(a.has(u.field))continue;a.add(u.field);let f=o?.field===u.field?pe(o.dir):"ASCENDING";d.push({fieldPath:u.field,order:f});}if(o&&!a.has(o.field)&&d.push({fieldPath:o.field,order:pe(o.dir)}),d.length===1&&n)return gt(e,t,d[0]);let c=o&&d.some(u=>u.fieldPath===o.field)?pe(o.dir):"ASCENDING";return d.push({fieldPath:"__name__",order:c}),mt(e,t,n,d)}function mt(e,t,n,i,o="(default)"){let d=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,a=[...ye(1,d),...ee(2,n?2:1)];for(let f of i)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 ht(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function le(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function fe(e,t){return e<<3|t}function ye(e,t){let n=Array.from(new TextEncoder().encode(t));return [fe(e,2),...le(n.length),...n]}function ee(e,t){return [fe(e,0),...le(t)]}function ke(e,t){return [fe(e,2),...le(t.length),...t]}function Ce(e){let t=[...ye(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ee(3,1)):t.push(...ee(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 gt(e,t,n,i="(default)"){let o=`projects/${e}/databases/${i}/collectionGroups/${t}/fields/${n.fieldPath}`,d=[...ye(1,o),...ee(2,2),...ke(3,Ce(n))],a=i==="(default)"?"-default-":i,c=encodeURIComponent(Ee(d));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function wt(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 bt(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??{},i=bt(e),o;if(i&&(o=n.message?ht(n.message):void 0,!o)){let d=wt(t.ref);if(d){let a=ft(t.path);o=yt(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 ge(e,t,n=200){let i=Te(t);return e.json(i,n)}function L(e,t,n,i=200){return ge(e,{success:true,data:t,meta:n},i)}function S(e,t,n=400){return ge(e,{success:false,error:t},n)}function me(e,t,n,i,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:i};return a&&(f.errorType="index",d.indexUrl&&(f.indexUrl=d.indexUrl)),ge(e,f,c)}var he="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 i=t[n];i>=he.length*4||(e+=he.charAt(i%he.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=>Re(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 xt(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 oe(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 ze(e,t){let n=t.split("."),i=oe(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=oe(c);}return i}function _e(e){let t=oe(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]=_e(c);return zod.z.object(d).partial()}return e}function te(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 x=u.split(".")[0];if(o.includes(u)||o.includes(x))continue;if(n&&n.length>0&&!n.includes(u)&&!n.includes(x))return {success:!1,error:`Field '${u}' is not allowed for this operation`};let g=ze(e,u);if(!g)return {success:!1,error:`Field '${u}' does not exist in schema`};let P=(ue()==="normalize"?K(g):g).parse(f);a[u]=P;}else c[u]=f;if(Object.keys(c).length>0||Object.keys(a).length===0){let u=xt(e,n,o),f=i?_e(u):u,g=(ue()==="normalize"?K(f):f).parse(c);Object.assign(a,g);}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"}}}var qe={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function J(e){return qe[e]??e}function At(e){return e in qe}function ne(e,t,n,i){let o=ze(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let d=i?J(i):void 0,a=oe(o),c=Oe(a);if(d==="array-contains"){let x=c??o;if(typeof x.safeParse=="function"){let g=x.safeParse(n);return g.success?{success:true,data:g.data}:{success:false,error:g.error.issues.map(P=>P.message).join(", ")}}return {success:true,data:n}}if(d==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let x=c??o,g=[];for(let I of n)if(typeof x.safeParse=="function"){let P=x.safeParse(I);if(P.success)g.push(P.data);else return {success:false,error:P.error.issues.map(E=>E.message).join(", ")}}else g.push(I);return {success:true,data:g}}let u=o.safeParse(n);if(u.success)return {success:true,data:u.data};if(Array.isArray(n)){let x=c??o,g=[];for(let I of n)if(typeof x.safeParse=="function"){let P=x.safeParse(I);if(P.success)g.push(P.data);else return {success:false,error:P.error.issues.map(E=>E.message).join(", ")}}else g.push(I);return {success:true,data:g}}return {success:false,error:u.error.issues.map(x=>x.message).join(", ")}}function vt(e,t){let n=[],i=t?new Set(t):null;for(let[o,d]of Object.entries(e)){if(d===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let a=Array.isArray(d)?d[0]:d;if(a===void 0||a==="")continue;let c=o.lastIndexOf("__"),u,f="==";if(c!==-1){let g=o.slice(0,c),I=o.slice(c+2);At(I)?(u=g,f=J(I)):(u=o,f="==");}else u=o;if(i&&!i.has(u))continue;let x=a;f==="in"||f==="not-in"||f==="array-contains-any"?x=a.split(",").map(g=>je(g.trim())):x=je(a),n.push({field:u,op:f,value:x});}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 re(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 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 $e(e,t,n){async function i(p,r,m,s){if(!r.rules)return true;let y=r.rules?.[m];if(!y)return S(p,`Operation "${m}" is not allowed for this repository`,403),false;try{return await y(s)?!0:S(p,"Forbidden",403)}catch(h){let w=n&&h instanceof Error?h.message:"Forbidden";return S(p,w,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 w of s)try{await y({user:r,doc:w,params:m})&&h.push(w);}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 S(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=[],w;try{let l=r.req.query(),b=Math.min(Number(l.pageSize)||s.pageSize,100),A=l.cursor,j=l.direction?.toLowerCase()==="prev"?"prev":"next",T=l.orderBy,O=l.orderDir?.toLowerCase()==="desc"?"desc":"asc",Z=l.select,B=Z?Z.split(",").map(N=>N.trim()):void 0,D=l.withTotal,v=D==="true"||D==="1"||D===!0,C;s.allowedIncludes&&l.includes&&(C=(typeof l.includes=="string"?l.includes.split(",").map(M=>M.trim()):Array.isArray(l.includes)?l.includes:[]).filter(M=>typeof M=="string"&&s.allowedIncludes.includes(M)),C?.length===0&&(C=void 0));let k=vt(l,s.filterableFields);h=k.map(N=>({field:N.field,op:N.op,value:String(N.value??"")})),T&&(w={field:T,dir:O});let F={pageSize:b,direction:j,...v?{withTotal:!0}:{}};if(A)try{let N=typeof A=="string"?JSON.parse(A):A;F.cursor=await De(s,N);}catch{}if(T){if(s.orderableFields&&!s.orderableFields.includes(T))return S(r,`Field not orderable: ${T}`,400);F.orderBy=[{field:T,direction:O}];}if(k.length>0){F.where=[];for(let N of k){let M=ne(s.schema,N.field,N.value,N.op);if(!M.success)return S(r,`Invalid filter value for '${N.field}': ${M.error}`,400);F.where.push([N.field,N.op,M.data]);}}B&&(F.select=B),C&&(F.include=C);let q=await s.repo.query.paginate(F),tt={items:await o(s,d(r),m,q.data),hasNextPage:q.hasNextPage,hasPrevPage:q.hasPrevPage,nextCursor:re(q.nextCursor),prevCursor:re(q.prevCursor),...q.totalCount!==void 0?{totalCount:q.totalCount,totalCountIsExact:q.totalCountIsExact}:{}};return L(r,tt,{pageSize:b,hasMore:q.hasNextPage,...q.totalCount!==void 0?{totalCount:q.totalCount,totalCountIsExact:q.totalCountIsExact}:{}})}catch(l){me(r,l,{ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:h,sort:w},"Failed to fetch documents",n);}}async function x(p){let r=p.c,m=r.req.param(),s=a(m.repoName,r);if(!s)return S(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=[],w;try{let l=p.input||{},b=Math.min(l.pageSize||s.pageSize,100),A=l.direction==="prev"?"prev":"next";l.where&&(h=l.where.map(D=>({field:String(D[0]),op:D[1],value:String(D[2]??"")}))),l.orderBy&&l.orderBy[0]&&(w={field:l.orderBy[0].field,dir:l.orderBy[0].direction==="desc"?"desc":"asc"});let j=l.withTotal===!0||String(l.withTotal)==="true",T={pageSize:b,direction:A,...j?{withTotal:!0}:{}};if(l.cursor)try{let D=typeof l.cursor=="string"?JSON.parse(l.cursor):l.cursor;T.cursor=await De(s,D);}catch{}if(s.allowedIncludes&&l.includes&&l.includes.length>0){let D=l.includes.filter(v=>typeof v=="string"?s.allowedIncludes.includes(v):typeof v=="object"&&v!==null&&"relation"in v&&typeof v.relation=="string"?s.allowedIncludes.includes(v.relation):!1);D.length>0&&(T.include=D);}if(l.where&&l.where.length>0){if(s.filterableFields){let v=new Set(s.filterableFields),C=l.where.filter(k=>!v.has(k[0]));if(C.length>0){S(r,`Fields not filterable: ${C.map(k=>k[0]).join(", ")}`,400);return}}let D=[];for(let v of l.where){let C=J(v[1]),k=ne(s.schema,v[0],v[2],C);if(!k.success){S(r,`Invalid filter value for '${v[0]}': ${k.error}`,400);return}D.push([v[0],C,k.data]);}T.where=D;}if(l.orWhere&&l.orWhere.length>0){if(s.filterableFields){let v=new Set(s.filterableFields),C=l.orWhere.filter(k=>!v.has(k[0]));if(C.length>0){S(r,`Fields not filterable: ${C.map(k=>k[0]).join(", ")}`,400);return}}let D=[];for(let v of l.orWhere){let C=J(v[1]),k=ne(s.schema,v[0],v[2],C);if(!k.success){S(r,`Invalid filter value for '${v[0]}': ${k.error}`,400);return}D.push([v[0],C,k.data]);}T.orWhere=D;}if(l.orWhereGroups&&l.orWhereGroups.length>0){if(s.filterableFields){let v=new Set(s.filterableFields);for(let C of l.orWhereGroups){let k=C.filter(F=>!v.has(F[0]));if(k.length>0){S(r,`Fields not filterable: ${k.map(F=>F[0]).join(", ")}`,400);return}}}let D=[];for(let v of l.orWhereGroups){let C=[];for(let k of v){let F=J(k[1]),q=ne(s.schema,k[0],k[2],F);if(!q.success){S(r,`Invalid filter value for '${k[0]}': ${q.error}`,400);return}C.push([k[0],F,q.data]);}D.push(C);}T.orWhereGroups=D;}if(l.orderBy&&l.orderBy.length>0){if(s.orderableFields){let D=new Set(s.orderableFields),v=l.orderBy.filter(C=>!D.has(C.field));if(v.length>0){S(r,`Fields not orderable: ${v.map(C=>C.field).join(", ")}`,400);return}}T.orderBy=l.orderBy;}l.select&&l.select.length>0&&(T.select=l.select);let O=await s.repo.query.paginate(T),B={items:await o(s,d(r),m,O.data),hasNextPage:O.hasNextPage,hasPrevPage:O.hasPrevPage,nextCursor:re(O.nextCursor),prevCursor:re(O.prevCursor),...O.totalCount!==void 0?{totalCount:O.totalCount,totalCountIsExact:O.totalCountIsExact}:{}};return L(r,B,{pageSize:b,hasMore:O.hasNextPage,...O.totalCount!==void 0?{totalCount:O.totalCount,totalCountIsExact:O.totalCountIsExact}:{}})}catch(l){me(r,l,{ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:h,sort:w},"Failed to query documents",n);}}async function g(p){let r=p.c,m=r.req.param(),s=a(m.repoName,r);if(!s)return S(r,"Repository not found",404);let y=m.id;if(!y)return S(r,"Document ID required",400);try{let h=await u(s,y);if(!h)return S(r,"Document not found",404);let w=d(r);if(!await i(r,s,"get",{user:w,doc:h,params:m}))return;if(s.rules?.filter)try{if(!await s.rules.filter({user:w,doc:h,params:m}))return S(r,"Document not found",404)}catch{return S(r,"Document not found",404)}return L(r,h)}catch(h){me(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 I(p){let r=p.c,m=r.req.param(),s=a(m.repoName,r);if(!s)return S(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 w=te(s.schema,y,s.createFields,!1,s.systemKeys);if(!w.success)return S(r,w.error,400);if(s.validate){let b=await s.validate(w.data,"create");if(b)return S(r,b,400)}let l;if(s.isGroup&&s.parentKeys&&s.parentKeys.length>0){let b={...w.data};s.createdKey&&(b[s.createdKey]=new Date);let A=s.parentKeys.filter(O=>!b[O]);if(A.length>0){S(r,`Missing parent key(s) for subcollection create: ${A.join(", ")}`,400);return}let j=s.parentKeys.map(O=>b[O]),T=b[s.documentKey]||Pe();l=await s.repo.set(...j,T,b);}else l=await s.repo.create(w.data);return L(r,l,void 0,201)}catch(y){let h=n&&y instanceof Error?y.message:"Failed to create document";return S(r,h,500)}}async function P(p,r){let m=p.c,s=m.req.param(),y=a(s.repoName,m);if(!y)return S(m,"Repository not found",404);let h=s.id;if(!h)return S(m,"Document ID required",400);try{let w=p.input||{},l=await u(y,h);if(!l)return S(m,"Document not found",404);let b=d(m);if(!await i(m,y,"update",{user:b,doc:l,body:w,params:s}))return;let A=te(y.schema,w,y.mutableFields,r,y.systemKeys);if(!A.success)return S(m,A.error,400);if(y.validate){let O=await y.validate(A.data,"update");if(O)return S(m,O,400)}let j=c(l,y.pathKey)??[h],T=await y.repo.update(...j,A.data);return L(m,T)}catch(w){let l=n&&w instanceof Error?w.message:"Failed to update document";return S(m,l,500)}}async function z(p){let r=p.c,m=r.req.param(),s=a(m.repoName,r);if(!s)return S(r,"Repository not found",404);if(!s.allowDelete)return S(r,"Delete not allowed for this repository",403);let y=m.id;if(!y)return S(r,"Document ID required",400);try{let h=await u(s,y);if(!h)return S(r,"Document not found",404);let w=d(r);if(!await i(r,s,"delete",{user:w,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 w=n&&h instanceof Error?h.message:"Failed to delete document";return S(r,w,500)}}function E(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 R(p){let r=p.c,m=r.req.param(),s=a(m.repoName,r);if(!s)return S(r,"Repository not found",404);try{let y=p.input||{};if(!Array.isArray(y.operations))return S(r,"operations array is required",400);let h=d(r),w=s.repo.batch.create(),l=[];for(let b of y.operations){if(!b.type||!["create","update","delete"].includes(b.type))return S(r,"Invalid operation type",400);if(b.type==="create"){if(!await i(r,s,"create",{user:h,body:b.data,params:m}))return;let A=te(s.schema,b.data,s.createFields,!1,s.systemKeys);if(!A.success)return S(r,A.error,400);let j=b.data[s.documentKey]||Pe(),T={...A.data};if(s.createdKey&&(T[s.createdKey]=new Date),s.isGroup&&s.parentKeys){let O=s.parentKeys.map(Z=>T[Z]);w.set(...O,j,T);}else w.set(j,T);l.push({op:"create",id:j});}else if(b.type==="update"){if(!b.id)return S(r,"id required for update",400);let A=await u(s,b.id);if(!A)return S(r,`Document ${b.id} not found`,404);if(!await i(r,s,"update",{user:h,doc:A,body:b.data,params:m}))return;let j=te(s.schema,b.data,s.mutableFields,!0,s.systemKeys);if(!j.success)return S(r,j.error,400);let T=c(A,s.pathKey)??[b.id];w.update(...T,j.data),l.push({op:"update",id:b.id});}else if(b.type==="delete"){if(!s.allowDelete)return S(r,"Delete not allowed",403);if(!b.id)return S(r,"id required for delete",400);let A=await u(s,b.id);if(!A)return S(r,`Document ${b.id} not found`,404);if(!await i(r,s,"delete",{user:h,doc:A,params:m}))return;let j=c(A,s.pathKey)??[b.id];w.delete(...j),l.push({op:"delete",id:b.id});}}return await w.commit(),L(r,{results:l})}catch(y){let h=n&&y instanceof Error?y.message:"Batch operation failed";return S(r,h,500)}}return {handleList:f,handleQuery:x,handleGet:g,handleCreate:I,handleUpdate:P,handleDelete:z,handleBatch:R,handleOptions:E}}function se(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 $(e){return {$ref:`#/components/schemas/${e}`}}function _(e){return {description:e,content:{"application/json":{schema:$("ErrorResponse")}}}}function G(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Tt(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 Ot(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 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 kt(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Ot(e.schema,t)})):be(e.schema)}function Ne(e){if(!e)return {type:"string"};let t=se(e);return delete t.$schema,delete t.title,t}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 Ct(e){let t=kt(e),n=e.orderableFields??t.map(a=>a.path),i=t.map(a=>a.path);if(t.length===0)return Fe();let o=[];for(let{path:a,zodSchema:c}of t){let u=Ne(c),f=Q(c),g=f?._zod?.def?.type==="array"||f?._def?.typeName==="ZodArray"||f?._def?.type==="array"?Ne(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"]},g],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:g}],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 Et(e,t,n,i,o,d="QueryRequestBody"){let a={},c=e.name,u=`${t}/${e.name}`,f=`${u}/{${e.documentKey}}`,x={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[u]={post:{operationId:`create${U(e.name)}`,summary:`Create a ${H(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:$(i??n)}}},responses:{201:G("Document created",$(n)),400:_("Validation error"),500:_("Internal server error")}}},a[`${u}/query`]={post:{operationId:`query${U(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:$(d)}}},responses:{200:Tt($(n)),400:_("Invalid query"),500:_("Internal server error")}}},a[`${u}/batch`]={post:{operationId:`batch${U(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:$(`${n}BatchRequest`)}}},responses:{200:G("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:_("Validation error"),403:_("Forbidden"),404:_("Document not found"),500:_("Internal server error")}}};let g={};return g.get={operationId:`get${U(H(e.name))}`,summary:`Get a single ${H(e.name)}`,tags:[c],parameters:[x],responses:{200:G("Document found",$(n)),404:_("Document not found"),500:_("Internal server error")}},g.put={operationId:`update${U(H(e.name))}`,summary:`Update a ${H(e.name)} (full replace)`,tags:[c],parameters:[x],requestBody:{required:true,content:{"application/json":{schema:$(o??n)}}},responses:{200:G("Document updated",$(n)),400:_("Validation error"),404:_("Document not found"),500:_("Internal server error")}},g.patch={operationId:`patch${U(H(e.name))}`,summary:`Partially update a ${H(e.name)}`,tags:[c],parameters:[x],requestBody:{required:true,content:{"application/json":{schema:{allOf:[$(o??n)],description:"All fields are optional for partial updates"}}}},responses:{200:G("Document patched",$(n)),400:_("Validation error"),404:_("Document not found"),500:_("Internal server error")}},e.allowDelete&&(g.delete={operationId:`delete${U(H(e.name))}`,summary:`Delete a ${H(e.name)}`,tags:[c],parameters:[x],responses:{200:G("Document deleted",{type:"object",properties:{id:{type:"string"}}}),404:_("Document not found"),500:_("Internal server error")}}),a[f]=g,a}function Se(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={},x={},g=[];f.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string"}},required:["success","error"]},f.QueryRequestBody=Fe();for(let[E,R]of Object.entries(e)){let p=U(H(E)),r=`${p}Create`,m=`${p}Update`,s=`${p}QueryRequestBody`;f[p]=se(R.schema),f[s]=Ct(R);let y=Z=>{let B={},D=be(R.schema);for(let{path:v,zodSchema:C}of D){let k=v.split(".")[0];R.systemKeys.includes(k)||R.systemKeys.includes(v)||Z&&Z.length>0&&!Z.includes(v)&&!Z.includes(k)||(v.includes(".")?B[v]=C.optional():B[v]=C);}return B},h=null,w=y(R.createFields);Object.keys(w).length>0&&(f[r]=se(zod.z.object(w)),h=r);let l=null,b=y(R.mutableFields);Object.keys(b).length>0&&(f[m]=se(zod.z.object(b)),l=m);let A=`${p}BatchCreateOperation`,j=`${p}BatchUpdateOperation`,T=`${p}BatchDeleteOperation`;f[A]={type:"object",title:`${p} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:$(h??p)},required:["type","data"]},f[j]={type:"object",title:`${p} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:{allOf:[$(l??p)],description:"Partial updates allowed"}},required:["type","id","data"]},R.allowDelete&&(f[T]={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:[$(A),$(j),...R.allowDelete?[$(T)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let O=Et(R,u,p,h,l,s);Object.assign(x,O),g.push({name:E,description:`Operations on ${E} (collection: ${R.path})`});}let I={},P;return c==="basic"?(I.basicAuth={type:"http",scheme:"basic"},P=[{basicAuth:[]}]):c==="bearer"&&(I.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},P=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:i,version:o,...d?{description:d}:{}},...a&&a.length>0?{servers:a}:{},paths:x,components:{schemas:f,...Object.keys(I).length>0?{securitySchemes:I}:{}},...P?{security:P}:{},tags:g}}function U(e){return e.charAt(0).toUpperCase()+e.slice(1)}function H(e){return e.endsWith("ies")?e.slice(0,-3)+"y":e.endsWith("ses")||e.endsWith("xes")||e.endsWith("zes")?e.slice(0,-2):e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e}var V=class extends Error{constructor(n,i){super("Request validation failed");this.zodError=n;this.source=i;this.statusCode=400;this.name="ValidationError";}};var X=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},Y=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 He(e,t){return t instanceof V?e.json({success:false,error:"Validation failed",issues:Ze(t.zodError)},400):t instanceof X?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof Y?e.json({success:false,error:"Output validation failed",issues:Ze(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var Be="Successful response",Me="Error response";function zt(e){return e==="get"?"query":"json"}function _t(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:Me,schema:e};let t=e;return {description:t.description??Me,schema:t.schema}}function Le(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??zt(u),x=Ft(t,c.path??"/"),g=c.status??200,I=$t(u,f,c.input),P=Ue(f,c.input,"query"),z=Ue(f,c.input,"param"),E=Zt(u,x),R=_t(c.output,i),p={[g]:R?{description:Be,content:{"application/json":{schema:R}}}:{description:Be}};if(i?.errors)for(let[r,m]of Object.entries(i.errors)){let{description:s,schema:y}=qt(m);p[r]=y?{description:s,content:{"application/json":{schema:y}}}:{description:s};}o.registerPath({method:u,path:Nt(x),operationId:E,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...P?{query:P}:{},...z?{params:z}:{},...I?{body:I}:{}},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 Ue(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Nt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Ft(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 Ke(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 fe=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var pt=(e,t)=>()=>(e&&(t=e(e=0)),t);var lt=(e,t)=>{for(var n in t)fe(e,n,{get:t[n],enumerable:true});},ft=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of dt(t))!ut.call(e,r)&&r!==n&&fe(e,r,{get:()=>t[r],enumerable:!(s=ct(t,r))||s.enumerable});return e};var yt=e=>ft(fe({},"__esModule",{value:true}),e);var st={};lt(st,{DEFAULT_HTML_CSP:()=>ot,securityHeaders:()=>an});function an(e={}){let t=e.csp===void 0?ot:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,s=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,r=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),r&&a.setHeader("Cache-Control",r),t&&a.setHeader("Content-Security-Policy",t)),await c();}}var nt,rt,ot,it=pt(()=>{nt="https://cdn.jsdelivr.net",rt="https://www.gstatic.com",ot=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${nt} ${rt}`,`style-src 'self' 'unsafe-inline' ${nt}`,`connect-src 'self' ${rt} 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 Ce="preserve";function me(){return Ce}function mt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Ee(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(mt(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 Ie(e){return e}function Pe(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var gt=new Set(["<","<=",">",">=","!="]),wt=new Set(["array-contains","array-contains-any"]);function he(e){return e==="desc"?"DESCENDING":"ASCENDING"}function bt(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function xt(e,t,n,s,r){let d=[],a=new Set;for(let p of s)if(p.op==="=="||p.op==="in"||p.op==="not-in"){if(a.has(p.field))continue;a.add(p.field),d.push({fieldPath:p.field,order:"ASCENDING"});}for(let p of s)if(wt.has(p.op)){if(a.has(p.field))continue;a.add(p.field),d.push({fieldPath:p.field,arrayConfig:"CONTAINS"});}for(let p of s)if(gt.has(p.op)){if(a.has(p.field))continue;a.add(p.field);let m=r?.field===p.field?he(r.dir):"ASCENDING";d.push({fieldPath:p.field,order:m});}if(r&&!a.has(r.field)&&d.push({fieldPath:r.field,order:he(r.dir)}),d.length===1&&n)return Tt(e,t,d[0]);let c=r&&d.some(p=>p.fieldPath===r.field)?he(r.dir):"ASCENDING";return d.push({fieldPath:"__name__",order:c}),Rt(e,t,n,d)}function Rt(e,t,n,s,r="(default)"){let d=`projects/${e}/databases/${r}/collectionGroups/${t}/indexes/_`,a=[...be(1,d),...ne(2,n?2:1)];for(let m of s)a.push(...De(3,je(m)));let c=r==="(default)"?"-default-":r,p=encodeURIComponent(ze(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes?create_composite=${p}`}function St(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function ge(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function we(e,t){return e<<3|t}function be(e,t){let n=Array.from(new TextEncoder().encode(t));return [we(e,2),...ge(n.length),...n]}function ne(e,t){return [we(e,0),...ge(t)]}function De(e,t){return [we(e,2),...ge(t.length),...t]}function je(e){let t=[...be(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ne(3,1)):t.push(...ne(2,e.order==="DESCENDING"?2:1)),t}function ze(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 Tt(e,t,n,s="(default)"){let r=`projects/${e}/databases/${s}/collectionGroups/${t}/fields/${n.fieldPath}`,d=[...be(1,r),...ne(2,2),...De(3,je(n))],a=s==="(default)"?"-default-":s,c=encodeURIComponent(ze(d));return `https://console.firebase.google.com/project/${e}/firestore/databases/${a}/indexes/automatic?create_exemption=${c}`}function At(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 r of n)if(typeof r=="string"&&r.length>0)return r;return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.FIREBASE_PROJECT_ID||void 0}function kt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function _e(e,t){let n=e??{},s=kt(e),r;if(s&&(r=n.message?St(n.message):void 0,!r)){let d=At(t.ref);if(d){let a=bt(t.path);r=xt(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:r}}function oe(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let s=0;s<e.length;s++)if(!oe(e[s],t[s],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof firestore.Timestamp||t instanceof firestore.Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let s=Object.keys(e),r=Object.keys(t);if(s.length!==r.length)return false;for(let d of s)if(!Object.prototype.hasOwnProperty.call(t,d)||!oe(e[d],t[d],n))return false;return true}return false}function se(e,t){let n=e||{},s={},r={...n};for(let[d,a]of Object.entries(t||{})){let c=n[d];oe(c,a)||(s[d]=a,r[d]=a);}return {before:n,after:r,changes:s}}function vt(e){return e}async function qe(e,t,n){let s=e.changes||{};for(let r of Object.keys(s)){let d=t[r];if(d&&d.length>0){for(let a of d)if(await a.rule({diff:e,key:r,user:n,authenticatedUser:n})===false)return {allowed:false,reason:a.description}}}return {allowed:true}}function Ot(e){return async t=>qe(t.diff,e,t.user)}function Se(e,t,n=200){let s=Ie(t);return e.json(s,n)}function W(e,t,n,s=200){return Se(e,{success:true,data:t,meta:n},s)}function w(e,t,n=400){return Se(e,{success:false,error:t},n)}async function xe(e,t,n,s,r,d){let a=_e(t,n),c=a.type==="index",p=c?424:500,b={success:false,error:c?a.message:r&&t instanceof Error?t.message:s};if(c&&(b.errorType="index",a.indexUrl&&(b.indexUrl=a.indexUrl,d)))try{let g=d({indexUrl:a.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});g instanceof Promise&&await g;}catch(g){r&&console.error("[crudServer] Error in indexesError callback:",g);}return Se(e,b,p)}var Re="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function $e(){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>=Re.length*4||(e+=Re.charAt(s%Re.length));}}return e}function G(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=>Ee(s)??s,e);if(n==="ZodObject"||n==="object"){let s=e.shape,r={};for(let[d,a]of Object.entries(s))r[d]=G(a);return zod.z.object(r)}if(n==="ZodArray"||n==="array"){let s=t.element??t.type;if(s)return zod.z.array(G(s))}if(n==="ZodOptional"||n==="optional"){let s=t.innerType;if(s)return G(s).optional()}if(n==="ZodNullable"||n==="nullable"){let s=t.innerType;if(s)return G(s).nullable()}if(n==="ZodDefault"||n==="default"){let s=t.innerType,r=t.defaultValue;if(s){let d=G(s);return typeof r=="function"?d.default(r()):d.default(r)}}return e}function Et(e,t,n=[]){let s=e.shape,r={},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]&&(r[c]=s[c]);}return zod.z.object(r)}function de(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 Ze(e,t){let n=t.split("."),s=de(e);for(let r=0;r<n.length;r++){let d=n[r];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(r===n.length-1)return c;s=de(c);}return s}function He(e){let t=de(e),n=t?._zod?.def??t?._def,s=n?.typeName??n?.type;if(s==="ZodObject"||s==="object"){let r=t.shape,d={};for(let[a,c]of Object.entries(r))d[a]=He(c);return zod.z.object(d).partial()}return e}function ie(e,t,n,s=false,r=[]){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[p,m]of Object.entries(d))if(p.includes(".")){let b=p.split(".")[0];if(r.includes(p)||r.includes(b))continue;if(n&&n.length>0&&!n.includes(p)&&!n.includes(b))return {success:!1,error:`Field '${p}' is not allowed for this operation`};let g=Ze(e,p);if(!g)return {success:!1,error:`Field '${p}' does not exist in schema`};let I=(me()==="normalize"?G(g):g).parse(m);a[p]=I;}else c[p]=m;if(Object.keys(c).length>0||Object.keys(a).length===0){let p=Et(e,n,r),m=s?He(p):p,g=(me()==="normalize"?G(m):m).parse(c);Object.assign(a,g);}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"}}}var Me={eq:"==","==":"==",ne:"!=","!=":"!=",lt:"<","<":"<",lte:"<=","<=":"<=",gt:">",">":">",gte:">=",">=":">=",in:"in",nin:"not-in","not-in":"not-in",not_in:"not-in",contains:"array-contains","array-contains":"array-contains",array_contains:"array-contains",arrayContains:"array-contains",containsAny:"array-contains-any","array-contains-any":"array-contains-any",array_contains_any:"array-contains-any",arrayContainsAny:"array-contains-any"};function X(e){return Me[e]??e}function It(e){return e in Me}function ae(e,t,n,s){let r=Ze(e,t);if(!r||typeof r.safeParse!="function")return {success:true,data:n};let d=s?X(s):void 0,a=de(r),c=Pe(a);if(d==="array-contains"){let b=c??r;if(typeof b.safeParse=="function"){let g=b.safeParse(n);return g.success?{success:true,data:g.data}:{success:false,error:g.error.issues.map(I=>I.message).join(", ")}}return {success:true,data:n}}if(d==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let b=c??r,g=[];for(let C of n)if(typeof b.safeParse=="function"){let I=b.safeParse(C);if(I.success)g.push(I.data);else return {success:false,error:I.error.issues.map(k=>k.message).join(", ")}}else g.push(C);return {success:true,data:g}}let p=r.safeParse(n);if(p.success)return {success:true,data:p.data};if(Array.isArray(n)){let b=c??r,g=[];for(let C of n)if(typeof b.safeParse=="function"){let I=b.safeParse(C);if(I.success)g.push(I.data);else return {success:false,error:I.error.issues.map(k=>k.message).join(", ")}}else g.push(C);return {success:true,data:g}}return {success:false,error:p.error.issues.map(b=>b.message).join(", ")}}function Pt(e,t){let n=[],s=t?new Set(t):null;for(let[r,d]of Object.entries(e)){if(d===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(r))continue;let a=Array.isArray(d)?d[0]:d;if(a===void 0||a==="")continue;let c=r.lastIndexOf("__"),p,m="==";if(c!==-1){let g=r.slice(0,c),C=r.slice(c+2);It(C)?(p=g,m=X(C)):(p=r,m="==");}else p=r;if(s&&!s.has(p))continue;let b=a;m==="in"||m==="not-in"||m==="array-contains-any"?b=a.split(",").map(g=>Fe(g.trim())):b=Fe(a),n.push({field:p,op:m,value:b});}return n}function Fe(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 ce(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Ne(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,r=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(r&&r.includes("/")&&a&&typeof a.doc=="function"){let c=await a.doc(r).get();if(c.exists)return c}if(r&&typeof d.doc=="function"){let c=await d.doc(r).get();if(c.exists)return c}return}catch{return}}function Be(e,t,n,s){async function r(l,i,f,o){if(!i.rules)return {allowed:true};let h=i.rules?.[f];if(!h)return {allowed:false,errorResponse:w(l,`Operation "${f}" is not allowed for this repository`,403)};try{let y=await h(o);return y===!1?{allowed:!1,errorResponse:w(l,"Forbidden",403)}:typeof y=="string"?{allowed:!1,errorResponse:w(l,y,403)}:typeof y=="object"&&y!==null&&!y.allowed?{allowed:!1,errorResponse:w(l,y.reason||"Forbidden",403)}:{allowed:!0}}catch(y){let x=n&&y instanceof Error?y.message:"Forbidden";return {allowed:false,errorResponse:w(l,x,403)}}}async function d(l,i,f,o){if(!l.rules)return o;let h=l.rules?.filter;if(!h)return o;let y=[];for(let x of o)try{await h({user:i,doc:x,params:f})&&y.push(x);}catch{}return y}function a(l){return l.get("user")??l.get("docsUser")??null}function c(l,i){if(!l){let f=i.req.path.split("/");for(let o of f)if(e[o]){l=o;break}}return !l||!e[l]?null:e[l]??null}function p(l,i){if(!i)return;let f=l[i];if(typeof f!="string"||!f)return;let o=f.split("/").filter(Boolean),h=[];for(let y=1;y<o.length;y+=2)h.push(o[y]);return h.length>0?h:void 0}async function m(l,i){let f=`by${l.documentKey.charAt(0).toUpperCase()}${l.documentKey.slice(1)}`,o=l.repo.get[f];if(typeof o=="function")try{let y=await o(i);if(y)return y}catch{}return (await l.repo.query.by({where:[[l.documentKey,"==",i]],limit:1}))[0]??null}async function b(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);let h=a(i),y=await r(i,o,"list",{user:h,query:i.req.query(),params:f});if(!y.allowed)return y.errorResponse;let x=[],S;try{let u=i.req.query(),R=Math.min(Number(u.pageSize)||o.pageSize,100),O=u.cursor,q=u.direction?.toLowerCase()==="prev"?"prev":"next",T=u.orderBy,E=u.orderDir?.toLowerCase()==="desc"?"desc":"asc",M=u.select,B=M?M.split(",").map(Z=>Z.trim()):void 0,z=u.withTotal,A=z==="true"||z==="1"||z===!0,_;o.allowedIncludes&&u.includes&&(_=(typeof u.includes=="string"?u.includes.split(",").map(L=>L.trim()):Array.isArray(u.includes)?u.includes:[]).filter(L=>typeof L=="string"&&o.allowedIncludes.includes(L)),_?.length===0&&(_=void 0));let P=Pt(u,o.filterableFields);x=P.map(Z=>({field:Z.field,op:Z.op,value:String(Z.value??"")})),T&&(S={field:T,dir:E});let H={pageSize:R,direction:q,...A?{withTotal:!0}:{}};if(O)try{let Z=typeof O=="string"?JSON.parse(O):O;H.cursor=await Ne(o,Z);}catch{}if(T){if(o.orderableFields&&!o.orderableFields.includes(T))return w(i,`Field not orderable: ${T}`,400);H.orderBy=[{field:T,direction:E}];}if(P.length>0){H.where=[];for(let Z of P){let L=ae(o.schema,Z.field,Z.value,Z.op);if(!L.success)return w(i,`Invalid filter value for '${Z.field}': ${L.error}`,400);H.where.push([Z.field,Z.op,L.data]);}}B&&(H.select=B),_&&(H.include=_);let F=await o.repo.query.paginate(H),at={items:await d(o,a(i),f,F.data),hasNextPage:F.hasNextPage,hasPrevPage:F.hasPrevPage,nextCursor:ce(F.nextCursor),prevCursor:ce(F.prevCursor),...F.totalCount!==void 0?{totalCount:F.totalCount,totalCountIsExact:F.totalCountIsExact}:{}};return W(i,at,{pageSize:R,hasMore:F.hasNextPage,...F.totalCount!==void 0?{totalCount:F.totalCount,totalCountIsExact:F.totalCountIsExact}:{}})}catch(u){return await xe(i,u,{repoName:f.repoName||o.name,ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:x,sort:S},"Failed to fetch documents",n,s)}}async function g(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);let h=a(i),y=await r(i,o,"list",{user:h,query:l.input||{},params:f});if(!y.allowed)return y.errorResponse;let x=[],S;try{let u=l.input||{},R=Math.min(u.pageSize||o.pageSize,100),O=u.direction==="prev"?"prev":"next";u.where&&(x=u.where.map(z=>({field:String(z[0]),op:z[1],value:String(z[2]??"")}))),u.orderBy&&u.orderBy[0]&&(S={field:u.orderBy[0].field,dir:u.orderBy[0].direction==="desc"?"desc":"asc"});let q=u.withTotal===!0||String(u.withTotal)==="true",T={pageSize:R,direction:O,...q?{withTotal:!0}:{}};if(u.cursor)try{let z=typeof u.cursor=="string"?JSON.parse(u.cursor):u.cursor;T.cursor=await Ne(o,z);}catch{}if(o.allowedIncludes&&u.includes&&u.includes.length>0){let z=u.includes.filter(A=>typeof A=="string"?o.allowedIncludes.includes(A):typeof A=="object"&&A!==null&&"relation"in A&&typeof A.relation=="string"?o.allowedIncludes.includes(A.relation):!1);z.length>0&&(T.include=z);}if(u.where&&u.where.length>0){if(o.filterableFields){let A=new Set(o.filterableFields),_=u.where.filter(P=>!A.has(P[0]));if(_.length>0){w(i,`Fields not filterable: ${_.map(P=>P[0]).join(", ")}`,400);return}}let z=[];for(let A of u.where){let _=X(A[1]),P=ae(o.schema,A[0],A[2],_);if(!P.success){w(i,`Invalid filter value for '${A[0]}': ${P.error}`,400);return}z.push([A[0],_,P.data]);}T.where=z;}if(u.orWhere&&u.orWhere.length>0){if(o.filterableFields){let A=new Set(o.filterableFields),_=u.orWhere.filter(P=>!A.has(P[0]));if(_.length>0){w(i,`Fields not filterable: ${_.map(P=>P[0]).join(", ")}`,400);return}}let z=[];for(let A of u.orWhere){let _=X(A[1]),P=ae(o.schema,A[0],A[2],_);if(!P.success){w(i,`Invalid filter value for '${A[0]}': ${P.error}`,400);return}z.push([A[0],_,P.data]);}T.orWhere=z;}if(u.orWhereGroups&&u.orWhereGroups.length>0){if(o.filterableFields){let A=new Set(o.filterableFields);for(let _ of u.orWhereGroups){let P=_.filter(H=>!A.has(H[0]));if(P.length>0){w(i,`Fields not filterable: ${P.map(H=>H[0]).join(", ")}`,400);return}}}let z=[];for(let A of u.orWhereGroups){let _=[];for(let P of A){let H=X(P[1]),F=ae(o.schema,P[0],P[2],H);if(!F.success){w(i,`Invalid filter value for '${P[0]}': ${F.error}`,400);return}_.push([P[0],H,F.data]);}z.push(_);}T.orWhereGroups=z;}if(u.orderBy&&u.orderBy.length>0){if(o.orderableFields){let z=new Set(o.orderableFields),A=u.orderBy.filter(_=>!z.has(_.field));if(A.length>0){w(i,`Fields not orderable: ${A.map(_=>_.field).join(", ")}`,400);return}}T.orderBy=u.orderBy;}u.select&&u.select.length>0&&(T.select=u.select);let E=await o.repo.query.paginate(T),B={items:await d(o,a(i),f,E.data),hasNextPage:E.hasNextPage,hasPrevPage:E.hasPrevPage,nextCursor:ce(E.nextCursor),prevCursor:ce(E.prevCursor),...E.totalCount!==void 0?{totalCount:E.totalCount,totalCountIsExact:E.totalCountIsExact}:{}};return W(i,B,{pageSize:R,hasMore:E.hasNextPage,...E.totalCount!==void 0?{totalCount:E.totalCount,totalCountIsExact:E.totalCountIsExact}:{}})}catch(u){return await xe(i,u,{repoName:f.repoName||o.name,ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:x,sort:S},"Failed to query documents",n,s)}}async function C(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);let h=f.id;if(!h)return w(i,"Document ID required",400);try{let y=await m(o,h);if(!y)return w(i,"Document not found",404);let x=a(i),S=await r(i,o,"get",{user:x,doc:y,params:f});if(!S.allowed)return S.errorResponse;if(o.rules?.filter)try{if(!await o.rules.filter({user:x,doc:y,params:f}))return w(i,"Document not found",404)}catch{return w(i,"Document not found",404)}return W(i,y)}catch(y){return await xe(i,y,{repoName:f.repoName||o.name,ref:o.repo.ref,path:o.path,isGroup:!!o.isGroup,filters:[{field:o.documentKey,op:"==",value:h}]},"Failed to fetch document",n,s)}}async function I(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);try{let h=l.input||{},y=a(i),x=await r(i,o,"create",{user:y,body:h,params:f});if(!x.allowed)return x.errorResponse;let S=ie(o.schema,h,o.createFields,!1,o.systemKeys);if(!S.success)return w(i,S.error,400);if(o.validate){let R=await o.validate(S.data,"create");if(R)return w(i,R,400)}let u;if(o.isGroup&&o.parentKeys&&o.parentKeys.length>0){let R={...S.data};o.createdKey&&(R[o.createdKey]=new Date);let O=o.parentKeys.filter(E=>!R[E]);if(O.length>0){w(i,`Missing parent key(s) for subcollection create: ${O.join(", ")}`,400);return}let q=o.parentKeys.map(E=>R[E]),T=R[o.documentKey]||$e();u=await o.repo.set(...q,T,R);}else u=await o.repo.create(S.data);return W(i,u,void 0,201)}catch(h){let y=n&&h instanceof Error?h.message:"Failed to create document";return w(i,y,500)}}async function $(l,i){let f=l.c,o=f.req.param(),h=c(o.repoName,f);if(!h)return w(f,"Repository not found",404);let y=o.id;if(!y)return w(f,"Document ID required",400);try{let x=l.input||{},S=await m(h,y);if(!S)return w(f,"Document not found",404);let u=ie(h.schema,x,h.mutableFields,i,h.systemKeys);if(!u.success)return w(f,u.error,400);if(h.validate){let M=await h.validate(u.data,"update");if(M)return w(f,M,400)}let R=se(S,u.data),O=a(f),q=await r(f,h,"update",{user:O,doc:S,body:u.data,diff:R,params:o});if(!q.allowed)return q.errorResponse;let T=p(S,h.pathKey)??[y],E=await h.repo.update(...T,u.data);return W(f,E)}catch(x){let S=n&&x instanceof Error?x.message:"Failed to update document";return w(f,S,500)}}async function k(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);if(!o.allowDelete)return w(i,"Delete not allowed for this repository",403);let h=f.id;if(!h)return w(i,"Document ID required",400);try{let y=await m(o,h);if(!y)return w(i,"Document not found",404);let x=a(i),S=await r(i,o,"delete",{user:x,doc:y,params:f});if(!S.allowed)return S.errorResponse;let u=p(y,o.pathKey)??[h];return await o.repo.delete(...u),W(i,{deleted:!0})}catch(y){let x=n&&y instanceof Error?y.message:"Failed to delete document";return w(i,x,500)}}function v(l){return l.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 j(l){let i=l.c,f=i.req.param(),o=c(f.repoName,i);if(!o)return w(i,"Repository not found",404);try{let h=l.input||{};if(!Array.isArray(h.operations))return w(i,"operations array is required",400);let y=a(i),x=o.repo.batch.create(),S=[];for(let u of h.operations){if(!u.type||!["create","update","delete"].includes(u.type))return w(i,"Invalid operation type",400);if(u.type==="create"){let R=await r(i,o,"create",{user:y,body:u.data,params:f});if(!R.allowed)return R.errorResponse;let O=ie(o.schema,u.data,o.createFields,!1,o.systemKeys);if(!O.success)return w(i,O.error,400);let q=u.data[o.documentKey]||$e(),T={...O.data};if(o.createdKey&&(T[o.createdKey]=new Date),o.isGroup&&o.parentKeys){let E=o.parentKeys.map(M=>T[M]);x.set(...E,q,T);}else x.set(q,T);S.push({op:"create",id:q});}else if(u.type==="update"){if(!u.id)return w(i,"id required for update",400);let R=await m(o,u.id);if(!R)return w(i,`Document ${u.id} not found`,404);let O=ie(o.schema,u.data,o.mutableFields,!0,o.systemKeys);if(!O.success)return w(i,O.error,400);if(o.validate){let M=await o.validate(O.data,"update");if(M)return w(i,M,400)}let q=se(R,O.data),T=await r(i,o,"update",{user:y,doc:R,body:O.data,diff:q,params:f});if(!T.allowed)return T.errorResponse;let E=p(R,o.pathKey)??[u.id];x.update(...E,O.data),S.push({op:"update",id:u.id});}else if(u.type==="delete"){if(!o.allowDelete)return w(i,"Delete not allowed",403);if(!u.id)return w(i,"id required for delete",400);let R=await m(o,u.id);if(!R)return w(i,`Document ${u.id} not found`,404);let O=await r(i,o,"delete",{user:y,doc:R,params:f});if(!O.allowed)return O.errorResponse;let q=p(R,o.pathKey)??[u.id];x.delete(...q),S.push({op:"delete",id:u.id});}}return await x.commit(),W(i,{results:S})}catch(h){let y=n&&h instanceof Error?h.message:"Batch operation failed";return w(i,y,500)}}return {handleList:b,handleQuery:g,handleGet:C,handleCreate:I,handleUpdate:$,handleDelete:k,handleBatch:j,handleOptions:v}}function ue(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 N(e){return {$ref:`#/components/schemas/${e}`}}function D(e){return {description:e,content:{"application/json":{schema:N("ErrorResponse")}}}}function J(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function jt(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 Y(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 zt(e,t){let n=t.split("."),s=Y(e);for(let r=0;r<n.length;r++){let d=n[r];if(!d)continue;let a=s?.shape;if(!a||!a[d])return;let c=a[d];if(r===n.length-1)return c;s=Y(c);}return s}function Ae(e,t="",n=0){if(n>5)return [];let r=Y(e)?.shape;if(!r)return [];let d=[];for(let[a,c]of Object.entries(r)){let p=t?`${t}.${a}`:a,m=Y(c);m?.shape&&typeof m.shape=="object"?(d.push({path:p,zodSchema:c}),d.push(...Ae(m,p,n+1))):d.push({path:p,zodSchema:c});}return d}function _t(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:zt(e.schema,t)})):Ae(e.schema)}function Ue(e){if(!e)return {type:"string"};let t=ue(e);return delete t.$schema,delete t.title,t}function Le(){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 qt(e){let t=_t(e),n=e.orderableFields??t.map(a=>a.path),s=t.map(a=>a.path);if(t.length===0)return Le();let r=[];for(let{path:a,zodSchema:c}of t){let p=Ue(c),m=Y(c),g=m?._zod?.def?.type==="array"||m?._def?.typeName==="ZodArray"||m?._def?.type==="array"?Ue(m?._zod?.def?.element??m?._def?.type??m?._def?.element):p;r.push({type:"array",description:`Condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},p],minItems:3,maxItems:3}),r.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:p}],minItems:3,maxItems:3}),r.push({type:"array",description:`Array contains condition on '${a}'`,prefixItems:[{type:"string",enum:[a]},{type:"string",enum:["array-contains","contains"]},g],minItems:3,maxItems:3}),r.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:g}],minItems:3,maxItems:3});}let d={oneOf:r};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 $t(e,t,n,s,r,d="QueryRequestBody"){let a={},c=e.name,p=`${t}/${e.name}`,m=`${p}/{${e.documentKey}}`,b={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};a[p]={post:{operationId:`create${K(e.name)}`,summary:`Create a ${U(e.name)}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:N(s??n)}}},responses:{201:J("Document created",N(n)),400:D("Validation error"),403:D("Forbidden"),500:D("Internal server error")}}},a[`${p}/query`]={post:{operationId:`query${K(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:N(d)}}},responses:{200:jt(N(n)),400:D("Invalid query"),403:D("Forbidden"),424:D("Missing composite index (includes indexUrl in response)"),500:D("Internal server error")}}},a[`${p}/batch`]={post:{operationId:`batch${K(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[c],requestBody:{required:true,content:{"application/json":{schema:N(`${n}BatchRequest`)}}},responses:{200:J("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 g={};return g.get={operationId:`get${K(U(e.name))}`,summary:`Get a single ${U(e.name)}`,tags:[c],parameters:[b],responses:{200:J("Document found",N(n)),400:D("Document ID required"),403:D("Forbidden"),404:D("Document not found"),424:D("Missing composite index (includes indexUrl in response)"),500:D("Internal server error")}},g.put={operationId:`update${K(U(e.name))}`,summary:`Update a ${U(e.name)} (full replace)`,tags:[c],parameters:[b],requestBody:{required:true,content:{"application/json":{schema:N(r??n)}}},responses:{200:J("Document updated",N(n)),400:D("Validation error"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}},g.patch={operationId:`patch${K(U(e.name))}`,summary:`Partially update a ${U(e.name)}`,tags:[c],parameters:[b],requestBody:{required:true,content:{"application/json":{schema:{allOf:[N(r??n)],description:"All fields are optional for partial updates"}}}},responses:{200:J("Document patched",N(n)),400:D("Validation error"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}},e.allowDelete&&(g.delete={operationId:`delete${K(U(e.name))}`,summary:`Delete a ${U(e.name)}`,tags:[c],parameters:[b],responses:{200:J("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:D("Document ID required"),403:D("Forbidden"),404:D("Document not found"),500:D("Internal server error")}}),a[m]=g,a}function ke(e,t,n={}){let{title:s="CRUD API",version:r="1.0.0",description:d,servers:a,auth:c=false}=n,p=t==="/"?"":t.replace(/\/$/,""),m={},b={},g=[];m.ErrorResponse={type:"object",properties:{success:{type:"boolean",enum:[false]},error:{type:"string",description:"Human-readable error description"},errorType:{type:"string",enum:["index"],description:"Error category discriminator. Set to 'index' when a Firestore composite index is missing."},indexUrl:{type:"string",format:"uri",description:"Direct Firebase Console URL to create the required composite index (when errorType is 'index')."}},required:["success","error"]},m.QueryRequestBody=Le();for(let[k,v]of Object.entries(e)){let j=K(U(k)),l=`${j}Create`,i=`${j}Update`,f=`${j}QueryRequestBody`;m[j]=ue(v.schema),m[f]=qt(v);let o=T=>{let E={},M=Ae(v.schema);for(let{path:B,zodSchema:z}of M){let A=B.split(".")[0];v.systemKeys.includes(A)||v.systemKeys.includes(B)||T&&T.length>0&&!T.includes(B)&&!T.includes(A)||(B.includes(".")?E[B]=z.optional():E[B]=z);}return E},h=null,y=o(v.createFields);Object.keys(y).length>0&&(m[l]=ue(zod.z.object(y)),h=l);let x=null,S=o(v.mutableFields);Object.keys(S).length>0&&(m[i]=ue(zod.z.object(S)),x=i);let u=`${j}BatchCreateOperation`,R=`${j}BatchUpdateOperation`,O=`${j}BatchDeleteOperation`;m[u]={type:"object",title:`${j} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:N(h??j)},required:["type","data"]},m[R]={type:"object",title:`${j} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:{allOf:[N(x??j)],description:"Partial updates allowed"}},required:["type","id","data"]},v.allowDelete&&(m[O]={type:"object",title:`${j} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),m[`${j}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[N(u),N(R),...v.allowDelete?[N(O)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let q=$t(v,p,j,h,x,f);Object.assign(b,q),g.push({name:k,description:`Operations on ${k} (collection: ${v.path})`});}let C={},I;return c==="basic"?(C.basicAuth={type:"http",scheme:"basic"},I=[{basicAuth:[]}]):c==="bearer"&&(C.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},I=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:s,version:r,...d?{description:d}:{}},...a&&a.length>0?{servers:a}:{},paths:b,components:{schemas:m,...Object.keys(C).length>0?{securitySchemes:C}:{}},...I?{security:I}:{},tags:g}}function K(e){return e.charAt(0).toUpperCase()+e.slice(1)}function U(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 Q=class extends Error{constructor(n,s){super("Request validation failed");this.zodError=n;this.source=s;this.statusCode=400;this.name="ValidationError";}};var ee=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},te=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Ke(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function We(e,t){return t instanceof Q?e.json({success:false,error:"Validation failed",issues:Ke(t.zodError)},400):t instanceof ee?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof te?e.json({success:false,error:"Output validation failed",issues:Ke(t.zodError)},500):null}zodToOpenapi.extendZodWithOpenApi(zod.z);var Ge="Successful response",Ve="Error response";function Mt(e){return e==="get"?"query":"json"}function Bt(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function Ut(e){if(typeof e.safeParse=="function")return {description:Ve,schema:e};let t=e;return {description:t.description??Ve,schema:t.schema}}function Qe(e,t,n,s){let r=new zodToOpenapi.OpenAPIRegistry;if(n.securitySchemes)for(let[c,p]of Object.entries(n.securitySchemes))r.registerComponent("securitySchemes",c,p);for(let c of e){let p=c.method,m=c.source??Mt(p),b=Wt(t,c.path??"/"),g=c.status??200,C=Lt(p,m,c.input),I=Je(m,c.input,"query"),$=Je(m,c.input,"param"),k=Gt(p,b),v=Bt(c.output,s),j={[g]:v?{description:Ge,content:{"application/json":{schema:v}}}:{description:Ge}};if(s?.errors)for(let[l,i]of Object.entries(s.errors)){let{description:f,schema:o}=Ut(i);j[l]=o?{description:f,content:{"application/json":{schema:o}}}:{description:f};}r.registerPath({method:p,path:Kt(b),operationId:k,summary:c.summary,description:c.description,tags:c.tags,deprecated:c.deprecated,security:c.security,request:{...I?{query:I}:{},...$?{params:$}:{},...C?{body:C}:{}},responses:j});}return new zodToOpenapi.OpenApiGeneratorV31(r.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security})}function Lt(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 Je(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Kt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function Wt(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,r=`${n}${s}`;return r===""?"/":r}function Gt(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function Xe(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 Ye(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var ve=new async_hooks.AsyncLocalStorage;function et(){return async(e,t)=>{await ve.run({c:e},async()=>{await t();});}}var Xt=Object.freeze({}),le=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new hono.Hono,this.mountedRoutes=tn(t.routes,t.api),t.services&&this.app.use("*",et());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let s of n)this.app.use("*",s);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return nodeServer.getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let s=this.nodeHandler;return n?t(n,s):t(s)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=Qe(this.mountedRoutes,this.options.basePath??"",this.options.openapi,en(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,s=this.options.verbose??false;for(let r of this.mountedRoutes){if(!r.path)throw new Error(`[HonoServer] route "${r.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=pe(t,r.path),a=r.middlewares??[],c=r.source??(r.method==="get"?"query":"json"),p=on(r,c,n,Yt(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),m=r.method.toUpperCase();this.app.on(m,[d],...a,p),s&&console.log(`[HonoServer] ${r.method.toUpperCase().padEnd(6)} ${d}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",s=t.docsPath===void 0?"/docs":t.docsPath,r=pe(this.options.basePath??"",n),d=s===false?null:pe(this.options.basePath??"",s),a;if(Ye(t.docsAuth)){let c=t.docsAuth;a=[c.middleware];let p=nn(d??r);for(let m of c.routes)this.app.on(m.method,[pe(p,m.name)],m.handler);}else a=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[r],...a,c=>c.json(this.buildOpenApiSpec())),d){let c=rn(d,r);this.app.on("GET",[d],...a,p=>p.html(Xe(c,t.info.title)));}}};function tt(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function Yt(e){if(e)return tt(e)?e.handler:e}function en(e){return tt(e)?e:void 0}function tn(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function pe(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,s=t.startsWith("/")?t:`/${t}`,r=`${n}${s}`;return r===""?"/":r}function nn(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function rn(e,t){let n=e.split("/").filter(Boolean),s=t.split("/").filter(Boolean);n.pop();let r=0;for(;r<n.length&&r<s.length&&n[r]===s[r];)r++;let d=n.length-r;return [...Array(d).fill(".."),...s.slice(r)].join("/")||"./"}function on(e,t,n,s,r,d,a){let c=e.input,p=e.output,m=e.status??200,b=r??Xt;return async g=>{let C=async k=>{if(d){let v=await d.handle({error:k,c:g,route:e,services:b,logger:a});if(v)return v}return We(g,k)},I=async()=>{let k,v;try{v=await sn(g,t,e.method);}catch(l){throw new ee(l instanceof Error?l.message:String(l))}if(c){let l=c.safeParse(v);if(!l.success)throw new Q(l.error,t);k=l.data;}else k=v;let j=await e.handler({input:k,c:g,services:b,errorHandler:d,logger:a});if(n&&p&&!(j instanceof Response)){let l=p.safeParse(j);if(!l.success)throw new te(l.error);return l.data}return j},$;if(s)try{$=await s({next:I,route:e,c:g,services:b,errorHandler:d,logger:a});}catch(k){let v=await C(k);if(v)return v;throw k}else try{$=await I();}catch(k){let v=await C(k);if(v)return v;throw k}return $ instanceof Response?$:g.json($,m)}}async function sn(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(r){throw new Error(`Invalid JSON body: ${r instanceof Error?r.message:String(r)}`)}}case "query":return e.req.query();case "form":return await e.req.parseBody();case "param":return e.req.param();default:return {}}}function tr(e){let{basePath:t="/",repos:n,parseBody:s=true,securityHeaders:r,verbose:d=false,httpsOptions:a}=e,c=t==="/"?"":t.replace(/\/$/,""),p={};for(let[l,i]of Object.entries(n)){if(!i.repo)throw new Error(`[createCrudServer] Repository "${l}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let f=i.schema??i.repo.schema??null;if(!f)throw new Error(`[createCrudServer] Repository "${l}" has no Zod schema.`);let o,h,y,x;if(i.fieldsConfig){let R=i.fieldsConfig;o=[],h=[],y=[],x=[];for(let[O,q]of Object.entries(R))for(let T of q)T==="filterable"?o.push(O):T==="orderable"?h.push(O):T==="mutable"?y.push(O):T==="create"&&x.push(O);h.length===0&&(h=o),o.length===0&&(o=void 0),h&&h.length===0&&(h=void 0),y.length===0&&(y=void 0),x.length===0&&(x=void 0);}let S=(()=>{let R=i.repo._parentKeys;return R&&R.length>0?R:void 0})();if(S&&x)for(let R of S)x.includes(R)||x.push(R);let u={name:l,path:i.path,repo:i.repo,schema:f,systemKeys:i.repo._systemKeys??[i.documentKey??"docId"],documentKey:i.documentKey??"docId",pathKey:i.repo._pathKey??void 0,isGroup:!!i.repo._isGroup,parentKeys:S,createdKey:i.repo._createdKey??void 0,pageSize:i.pageSize??25,filterableFields:o,orderableFields:h,mutableFields:y,createFields:x,allowDelete:i.allowDelete??false,allowedIncludes:i.allowedIncludes,validate:i.validate,rules:i.rules};p[l]=u;}let m=e.indexesError??e.onIndexError,b=Be(p,c,d,m),g=e.openapi,C=g&&typeof g=="object"?g:{},I=null;function $(){return I||(I=ke(p,c,{...C,auth:C.auth??false})),I}let k=[];for(let l of Object.keys(p))k.push({api:"crud",method:"post",path:`/${l}/query`,source:"json",handler:b.handleQuery}),k.push({api:"crud",method:"get",path:`/${l}/:id`,source:"query",handler:b.handleGet}),k.push({api:"crud",method:"post",path:`/${l}`,source:"json",handler:b.handleCreate}),k.push({api:"crud",method:"put",path:`/${l}/:id`,source:"json",handler:i=>b.handleUpdate(i,false)}),k.push({api:"crud",method:"patch",path:`/${l}/:id`,source:"json",handler:i=>b.handleUpdate(i,true)}),k.push({api:"crud",method:"delete",path:`/${l}/:id`,source:"query",handler:b.handleDelete}),k.push({api:"crud",method:"post",path:`/${l}/batch`,source:"json",handler:b.handleBatch});let v=new le({...e,openapi:g!==false?{path:C.path??"/openapi.json",docsPath:C.docsPath??"/docs",info:{title:C.title??"CRUD API",version:C.version??"1.0.0"},docsAuth:C.docsAuth}:void 0,basePath:t,api:"crud",routes:k,middlewares:[async(l,i)=>{if(l.req.method==="OPTIONS")return l.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"});l.header("Access-Control-Allow-Origin","*"),l.header("Access-Control-Allow-Credentials","true"),await i();},...e.middlewares||[]]});if(g!==false&&(v.buildOpenApiSpec=$),r!==false){let{securityHeaders:l}=(it(),yt(st)),i=r===void 0?{csp:false}:r;v.hono.use("*",async(f,o)=>{let h=l(i);await new Promise(y=>{let x=f.req.raw;h(x,{setHeader:(u,R)=>f.header(u,R),removeHeader:u=>f.res.headers.delete(u)},()=>y());}),await o();});}let j=v.nodeHandler;return j.spec=$,a&&(j.httpsOptions=a),j}exports.applyRules=qe;exports.computeDeepDiff=se;exports.createBeforeRules=Ot;exports.createCrudServer=tr;exports.createRules=vt;exports.generateOpenAPISpec=ke;//# sourceMappingURL=index.cjs.map
|
|
13
13
|
//# sourceMappingURL=index.cjs.map
|