@lpdjs/firestore-repo-service 3.0.13 → 3.0.15
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/actor-context-DQZgWqj3.d.cts +117 -0
- package/dist/actor-context-DQZgWqj3.d.ts +117 -0
- package/dist/{create-servers-LyRLAOh3.d.cts → create-servers-B5Z5v2SP.d.cts} +11 -5
- package/dist/{create-servers-Db1xUY2N.d.ts → create-servers-p1-jJNTG.d.ts} +11 -5
- package/dist/history/index.cjs +1 -1
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.d.cts +67 -7
- package/dist/history/index.d.ts +67 -7
- package/dist/history/index.js +1 -1
- package/dist/history/index.js.map +1 -1
- package/dist/index.cjs +81 -81
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +20 -14
- package/dist/index.d.ts +20 -14
- package/dist/index.js +81 -81
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +1 -1
- package/dist/llms.txt +1 -1
- package/dist/{openapi-QVpqnnes.d.cts → openapi-B9utXiEH.d.cts} +1 -1
- package/dist/{openapi-CNIA7QRw.d.ts → openapi-Bsqq2zgh.d.ts} +1 -1
- package/dist/{queue-BEB-ujA3.d.ts → queue-NFod6hTT.d.ts} +1 -1
- package/dist/{queue-CpHe6M5j.d.cts → queue-zw2B7GPx.d.cts} +1 -1
- package/dist/{read-15-TcgCz.d.ts → read-BPov7lws.d.ts} +30 -7
- package/dist/{read-B15YaPyR.d.cts → read-Dfah1PPl.d.cts} +30 -7
- package/dist/{rules-Cafrkb9v.d.ts → rules-18wH7Uak.d.ts} +1 -1
- package/dist/{rules-Bu2NB7Eb.d.cts → rules-oSXoV4Js.d.cts} +1 -1
- package/dist/servers/admin/index.cjs +5 -5
- package/dist/servers/admin/index.cjs.map +1 -1
- package/dist/servers/admin/index.d.cts +5 -4
- package/dist/servers/admin/index.d.ts +5 -4
- package/dist/servers/admin/index.js +5 -5
- package/dist/servers/admin/index.js.map +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 +10 -9
- package/dist/servers/crud/index.d.ts +10 -9
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/hono/index.cjs +14 -14
- package/dist/servers/hono/index.cjs.map +1 -1
- package/dist/servers/hono/index.d.cts +11 -3
- package/dist/servers/hono/index.d.ts +11 -3
- package/dist/servers/hono/index.js +14 -14
- package/dist/servers/hono/index.js.map +1 -1
- package/dist/servers/index.cjs +94 -94
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +13 -12
- package/dist/servers/index.d.ts +13 -12
- package/dist/servers/index.js +94 -94
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/bigquery.d.cts +2 -2
- package/dist/sync/bigquery.d.ts +2 -2
- package/dist/sync/index.cjs +55 -55
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.d.cts +6 -6
- package/dist/sync/index.d.ts +6 -6
- package/dist/sync/index.js +55 -55
- package/dist/sync/index.js.map +1 -1
- package/dist/sync/meilisearch.cjs +2 -2
- package/dist/sync/meilisearch.cjs.map +1 -1
- package/dist/sync/meilisearch.d.cts +2 -2
- package/dist/sync/meilisearch.d.ts +2 -2
- package/dist/sync/meilisearch.js +2 -2
- package/dist/sync/meilisearch.js.map +1 -1
- package/dist/{types-o-9qoExc.d.cts → types-BDTx8VPg.d.cts} +8 -0
- package/dist/{types-CNseHqF7.d.cts → types-BGh5_2fl.d.cts} +4 -4
- package/dist/{types-DGQURFSq.d.ts → types-B_FrzmO4.d.ts} +1 -1
- package/dist/{types-DmXW_fVz.d.ts → types-Cc6lelk1.d.ts} +4 -4
- package/dist/{types--RamYGF1.d.cts → types-D6zvWzRt.d.cts} +96 -2
- package/dist/{types--RamYGF1.d.ts → types-D6zvWzRt.d.ts} +96 -2
- package/dist/{types-VVuLlmfc.d.cts → types-D78FPJeF.d.cts} +1 -1
- package/dist/{types-B51LYvQZ.d.cts → types-Dc3lX99O.d.cts} +20 -19
- package/dist/{types-Ci0dGbuW.d.ts → types-DgFJLwAu.d.ts} +20 -19
- package/dist/{types-D3W_RaDA.d.ts → types-w1rEqs0Z.d.ts} +8 -0
- package/package.json +1 -1
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
2
|
-
import { a as CrudServerOptions } from '../../types-
|
|
2
|
+
import { a as CrudServerOptions } from '../../types-BGh5_2fl.cjs';
|
|
3
3
|
import { ConfiguredRepository } from '../../index.cjs';
|
|
4
|
-
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, e as CrudRules, f as CrudUpdateRuleContext, D as DeepDiffReturn, F as FieldRole, I as IndexErrorCallback, g as IndexErrorContext, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, h as RepoRelationKeys, i as Rule, j as RuleResult, k as RulesMap, U as UserFieldPath } from '../../types-
|
|
5
|
-
import { O as OpenAPIDocument } from '../../openapi-
|
|
6
|
-
export { g as generateOpenAPISpec } from '../../openapi-
|
|
7
|
-
export { a as applyRules, c as computeDeepDiff, b as createBeforeRules, d as createRules } from '../../rules-
|
|
4
|
+
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, e as CrudRules, f as CrudUpdateRuleContext, D as DeepDiffReturn, F as FieldRole, I as IndexErrorCallback, g as IndexErrorContext, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, h as RepoRelationKeys, i as Rule, j as RuleResult, k as RulesMap, U as UserFieldPath } from '../../types-BGh5_2fl.cjs';
|
|
5
|
+
import { O as OpenAPIDocument } from '../../openapi-B9utXiEH.cjs';
|
|
6
|
+
export { g as generateOpenAPISpec } from '../../openapi-B9utXiEH.cjs';
|
|
7
|
+
export { a as applyRules, c as computeDeepDiff, b as createBeforeRules, d as createRules } from '../../rules-oSXoV4Js.cjs';
|
|
8
8
|
import '../../firebase-auth-nG3prKoj.cjs';
|
|
9
|
-
import '../../types-
|
|
9
|
+
import '../../types-BDTx8VPg.cjs';
|
|
10
10
|
import 'zod';
|
|
11
11
|
import 'hono';
|
|
12
|
-
import '../../
|
|
12
|
+
import '../../actor-context-DQZgWqj3.cjs';
|
|
13
|
+
import '../../read-Dfah1PPl.cjs';
|
|
13
14
|
import 'firebase-admin/firestore';
|
|
14
|
-
import '../../types
|
|
15
|
+
import '../../types-D6zvWzRt.cjs';
|
|
15
16
|
import 'firebase-functions/v2/firestore';
|
|
16
|
-
import '../../types-
|
|
17
|
+
import '../../types-Dc3lX99O.cjs';
|
|
17
18
|
|
|
18
19
|
/**
|
|
19
20
|
* @module servers/crud
|
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
import { HttpsOptions } from 'firebase-functions/v2/https';
|
|
2
|
-
import { a as CrudServerOptions } from '../../types-
|
|
2
|
+
import { a as CrudServerOptions } from '../../types-Cc6lelk1.js';
|
|
3
3
|
import { ConfiguredRepository } from '../../index.js';
|
|
4
|
-
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, e as CrudRules, f as CrudUpdateRuleContext, D as DeepDiffReturn, F as FieldRole, I as IndexErrorCallback, g as IndexErrorContext, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, h as RepoRelationKeys, i as Rule, j as RuleResult, k as RulesMap, U as UserFieldPath } from '../../types-
|
|
5
|
-
import { O as OpenAPIDocument } from '../../openapi-
|
|
6
|
-
export { g as generateOpenAPISpec } from '../../openapi-
|
|
7
|
-
export { a as applyRules, c as computeDeepDiff, b as createBeforeRules, d as createRules } from '../../rules-
|
|
4
|
+
export { A as ApiResponse, b as CrudRepoConfig, c as CrudRepoEntry, d as CrudRepoRegistry, e as CrudRules, f as CrudUpdateRuleContext, D as DeepDiffReturn, F as FieldRole, I as IndexErrorCallback, g as IndexErrorContext, L as ListResponseData, O as OpenAPISpecOptions, Q as QueryRequestBody, R as RepoFieldPath, h as RepoRelationKeys, i as Rule, j as RuleResult, k as RulesMap, U as UserFieldPath } from '../../types-Cc6lelk1.js';
|
|
5
|
+
import { O as OpenAPIDocument } from '../../openapi-Bsqq2zgh.js';
|
|
6
|
+
export { g as generateOpenAPISpec } from '../../openapi-Bsqq2zgh.js';
|
|
7
|
+
export { a as applyRules, c as computeDeepDiff, b as createBeforeRules, d as createRules } from '../../rules-18wH7Uak.js';
|
|
8
8
|
import '../../firebase-auth-nG3prKoj.js';
|
|
9
|
-
import '../../types-
|
|
9
|
+
import '../../types-w1rEqs0Z.js';
|
|
10
10
|
import 'zod';
|
|
11
11
|
import 'hono';
|
|
12
|
-
import '../../
|
|
12
|
+
import '../../actor-context-DQZgWqj3.js';
|
|
13
|
+
import '../../read-BPov7lws.js';
|
|
13
14
|
import 'firebase-admin/firestore';
|
|
14
|
-
import '../../types
|
|
15
|
+
import '../../types-D6zvWzRt.js';
|
|
15
16
|
import 'firebase-functions/v2/firestore';
|
|
16
|
-
import '../../types-
|
|
17
|
+
import '../../types-DgFJLwAu.js';
|
|
17
18
|
|
|
18
19
|
/**
|
|
19
20
|
* @module servers/crud
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {z}from'zod';import {Timestamp}from'firebase-admin/firestore';import {randomBytes}from'crypto';import {extendZodWithOpenApi,getOpenApiMetadata,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {AsyncLocalStorage}from'async_hooks';var he=Object.defineProperty;var ht=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var wt=Object.prototype.hasOwnProperty;var bt=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};var xt=(e,t)=>{for(var n in t)he(e,n,{get:t[n],enumerable:true});},St=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of gt(t))!wt.call(e,r)&&r!==n&&he(e,r,{get:()=>t[r],enumerable:!(o=ht(t,r))||o.enumerable});return e};var Rt=e=>St(he({},"__esModule",{value:true}),e);var ft={};xt(ft,{DEFAULT_HTML_CSP:()=>lt,securityHeaders:()=>yn});function yn(e={}){let t=e.csp===void 0?lt:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,o=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,r=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(a,c,d)=>{typeof c?.setHeader=="function"&&(c.setHeader("X-Content-Type-Options","nosniff"),n&&c.setHeader("X-Frame-Options",n),o&&c.setHeader("Referrer-Policy",o),r&&c.setHeader("Cache-Control",r),t&&c.setHeader("Content-Security-Policy",t)),await d();}}var ut,pt,lt,yt=bt(()=>{"use strict";ut="https://cdn.jsdelivr.net",pt="https://www.gstatic.com",lt=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${ut} ${pt}`,`style-src 'self' 'unsafe-inline' ${ut}`,`connect-src 'self' ${pt} 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 je="preserve";function we(){return je}function Tt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function ze(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(Tt(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 _e(e){return e}var be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function xe(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let o=t[n];o>=be.length*4||(e+=be.charAt(o%be.length));}}return e}function qe(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function $e(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let o=e.split("/").map(y=>y.trim()).filter(Boolean);if(o.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(o.length===1){let y=o[0];return {rawPath:e,collectionId:y,collectionPath:y,parentKeys:[],documentPathTemplate:n?null:`${y}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let r=o.length%2===0,a=r?o.slice(0,-1):o,c=a[a.length-1],d=a.join("/"),l=a.slice(0,-1).map(qe).filter(y=>y!==null),g=r?o.join("/"):`${d}/{${t}}`;return {rawPath:e,collectionId:c,collectionPath:d,parentKeys:l,documentPathTemplate:g,hasTemplate:true}}function Fe(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:o="docId",parentKeys:r,documentPathTemplate:a,isGroup:c}=t,d=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(d&&a){let u=d.split("/").filter(Boolean),l=a.split("/").filter(Boolean);if(u.length===l.length){let g=[];for(let y=0;y<l.length;y++)qe(l[y])!==null&&g.push(u[y]);if(g.length>0)return g}}if(r&&r.length>0){let u=r.length+1;if(d){let g=d.split("/").filter(Boolean),y=[];for(let S=1;S<g.length;S+=2)y.push(g[S]);if(y.length>=u)return y.slice(y.length-u)}let l=o?e[o]:void 0;if(typeof l=="string"&&l.trim()!==""){let g=[],y=true;for(let S of r){let E=e[S];if(typeof E=="string"&&E.trim()!=="")g.push(E);else {y=false;break}}if(y)return [...g,l]}}if(d){let u=d.split("/").filter(Boolean),l=[];for(let g=1;g<u.length;g+=2)l.push(u[g]);if(l.length>0)return !c&&(!r||r.length===0)?[l[l.length-1]]:l}}function Ne(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var Ot=new Set(["<","<=",">",">=","!="]),vt=new Set(["array-contains","array-contains-any"]);function Se(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Ct(e){return $e(e).collectionId||e}function Et(e,t,n,o,r){let a=[],c=new Set;for(let u of o)if(u.op==="=="||u.op==="in"||u.op==="not-in"){if(c.has(u.field))continue;c.add(u.field),a.push({fieldPath:u.field,order:"ASCENDING"});}for(let u of o)if(vt.has(u.op)){if(c.has(u.field))continue;c.add(u.field),a.push({fieldPath:u.field,arrayConfig:"CONTAINS"});}for(let u of o)if(Ot.has(u.op)){if(c.has(u.field))continue;c.add(u.field);let l=r?.field===u.field?Se(r.dir):"ASCENDING";a.push({fieldPath:u.field,order:l});}if(r&&!c.has(r.field)&&a.push({fieldPath:r.field,order:Se(r.dir)}),a.length===1&&n)return Dt(e,t,a[0]);let d=r&&a.some(u=>u.fieldPath===r.field)?Se(r.dir):"ASCENDING";return a.push({fieldPath:"__name__",order:d}),It(e,t,n,a)}function It(e,t,n,o,r="(default)"){let a=`projects/${e}/databases/${r}/collectionGroups/${t}/indexes/_`,c=[...Ae(1,a),...ae(2,n?2:1)];for(let l of o)c.push(...Ze(3,He(l)));let d=r==="(default)"?"-default-":r,u=encodeURIComponent(Me(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${d}/indexes?create_composite=${u}`}function Pt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Re(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Te(e,t){return e<<3|t}function Ae(e,t){let n=Array.from(new TextEncoder().encode(t));return [Te(e,2),...Re(n.length),...n]}function ae(e,t){return [Te(e,0),...Re(t)]}function Ze(e,t){return [Te(e,2),...Re(t.length),...t]}function He(e){let t=[...Ae(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ae(3,1)):t.push(...ae(2,e.order==="DESCENDING"?2:1)),t}function Me(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 Dt(e,t,n,o="(default)"){let r=`projects/${e}/databases/${o}/collectionGroups/${t}/fields/${n.fieldPath}`,a=[...Ae(1,r),...ae(2,2),...Ze(3,He(n))],c=o==="(default)"?"-default-":o,d=encodeURIComponent(Me(a));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes/automatic?create_exemption=${d}`}function jt(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 zt(e){let t=e;return t?t.code===9?true:typeof t.message=="string"?t.message.includes("requires an index"):false:false}function Be(e,t){let n=e??{},o=zt(e),r;if(o&&(r=n.message?Pt(n.message):void 0,!r)){let a=jt(t.ref);if(a){let c=Ct(t.path);r=Et(a,c,t.isGroup,t.filters,t.sort);}}return {type:o?"index":"error",message:o?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:r}}function de(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 Timestamp&&t instanceof 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 o=0;o<e.length;o++)if(!de(e[o],t[o],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof Timestamp||t instanceof Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let o=Object.keys(e),r=Object.keys(t);if(o.length!==r.length)return false;for(let a of o)if(!Object.prototype.hasOwnProperty.call(t,a)||!de(e[a],t[a],n))return false;return true}return false}function ue(e,t){let n=e||{},o={},r={...n};for(let[a,c]of Object.entries(t||{})){let d=n[a];de(d,c)||(o[a]=c,r[a]=c);}return {before:n,after:r,changes:o}}function _t(e){return e}async function Ue(e,t,n){let o=e.changes||{};for(let r of Object.keys(o)){let a=t[r];if(a&&a.length>0){for(let c of a)if(await c.rule({diff:e,key:r,user:n,authenticatedUser:n})===false)return {allowed:false,reason:c.description}}}return {allowed:true}}function qt(e){return async t=>Ue(t.diff,e,t.user)}function ve(e,t,n=200){let o=_e(t);return e.json(o,n)}function W(e,t,n,o=200){return ve(e,{success:true,data:t,meta:n},o)}function b(e,t,n=400){return ve(e,{success:false,error:t},n)}async function ke(e,t,n,o,r,a){let c=Be(t,n),d=c.type==="index",u=d?424:500,g={success:false,error:d?c.message:r&&t instanceof Error?t.message:o};if(d&&(g.errorType="index",c.indexUrl&&(g.indexUrl=c.indexUrl,a)))try{let y=a({indexUrl:c.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});y instanceof Promise&&await y;}catch(y){r&&console.error("[crudServer] Error in indexesError callback:",y);}return ve(e,g,u)}function V(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z.preprocess(o=>ze(o)??o,e);if(n==="ZodObject"||n==="object"){let o=e.shape,r={};for(let[a,c]of Object.entries(o))r[a]=V(c);return z.object(r)}if(n==="ZodArray"||n==="array"){let o=t.element??t.type;if(o)return z.array(V(o))}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(o)return V(o).optional()}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(o)return V(o).nullable()}if(n==="ZodDefault"||n==="default"){let o=t.innerType,r=t.defaultValue;if(o){let a=V(o);return typeof r=="function"?a.default(r()):a.default(r)}}return e}function $t(e,t,n=[]){let o=e.shape,r={},a=t&&t.length>0?t:Object.keys(o);for(let c of a){if(n.includes(c))continue;let d=c.split(".")[0];d&&o[d]&&(r[d]=o[d]);}return z.object(r)}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 Ge(e,t){let n=t.split("."),o=Oe(e);for(let r=0;r<n.length;r++){let a=n[r];if(!a)continue;let c=o?.shape;if(!c||!c[a])return;let d=c[a];if(r===n.length-1)return d;o=Oe(d);}return o}function J(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let o=e.shape,r={};for(let[a,c]of Object.entries(o))r[a]=J(c);return z.object(r).partial()}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let r=J(o);return r===o?e:r.optional()}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let r=J(o);return r===o?e:r.nullable()}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?J(o).optional():e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let r=o.map(c=>J(c));return r.some((c,d)=>c!==o[d])?z.union(r):e}return e}function pe(e,t,n,o=false,r=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let a=t,c={},d={};for(let[u,l]of Object.entries(a))if(u.includes(".")){let g=u.split(".")[0];if(r.includes(u)||r.includes(g))continue;if(n&&n.length>0&&!n.includes(u)&&!n.includes(g))return {success:!1,error:`Field '${u}' is not allowed for this operation`};let y=Ge(e,u);if(!y)return {success:!1,error:`Field '${u}' does not exist in schema`};let S=o?J(y):y,F=(we()==="normalize"?V(S):S).parse(l);c[u]=F;}else d[u]=l;if(Object.keys(d).length>0||Object.keys(c).length===0){let u=$t(e,n,r),l=o?J(u):u,y=(we()==="normalize"?V(l):l).parse(d);Object.assign(c,y);}return {success:!0,data:c}}catch(a){return a instanceof z.ZodError?{success:false,error:`Validation failed: ${a.issues.map(d=>`${d.path.join(".")}: ${d.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var We={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 ne(e){return We[e]??e}function Ft(e){return e in We}function le(e,t,n,o){let r=Ge(e,t);if(!r||typeof r.safeParse!="function")return {success:true,data:n};let a=o?ne(o):void 0,c=Oe(r),d=Ne(c);if(a==="array-contains"){let g=d??r;if(typeof g.safeParse=="function"){let y=g.safeParse(n);return y.success?{success:true,data:y.data}:{success:false,error:y.error.issues.map(E=>E.message).join(", ")}}return {success:true,data:n}}if(a==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let g=d??r,y=[];for(let S of n)if(typeof g.safeParse=="function"){let E=g.safeParse(S);if(E.success)y.push(E.data);else return {success:false,error:E.error.issues.map(v=>v.message).join(", ")}}else y.push(S);return {success:true,data:y}}let u=r.safeParse(n);if(u.success)return {success:true,data:u.data};if(Array.isArray(n)){let g=d??r,y=[];for(let S of n)if(typeof g.safeParse=="function"){let E=g.safeParse(S);if(E.success)y.push(E.data);else return {success:false,error:E.error.issues.map(v=>v.message).join(", ")}}else y.push(S);return {success:true,data:y}}return {success:false,error:u.error.issues.map(g=>g.message).join(", ")}}function Nt(e,t){let n=[],o=t?new Set(t):null;for(let[r,a]of Object.entries(e)){if(a===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(r))continue;let c=Array.isArray(a)?a[0]:a;if(c===void 0||c==="")continue;let d=r.lastIndexOf("__"),u,l="==";if(d!==-1){let y=r.slice(0,d),S=r.slice(d+2);Ft(S)?(u=y,l=ne(S)):(u=r,l="==");}else u=r;if(o&&!o.has(u))continue;let g=c;l==="in"||l==="not-in"||l==="array-contains-any"?g=c.split(",").map(y=>Ke(y.trim())):g=Ke(c),n.push({field:u,op:l,value:g});}return n}function Ke(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 fe(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Le(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 o=typeof n.docPath=="string"?n.docPath:void 0,r=typeof n.docId=="string"?n.docId:void 0;try{let a=e.repo.ref,c=a?.firestore;if(o&&c&&typeof c.doc=="function"){let d=await c.doc(o).get();if(d.exists)return d}if(r&&r.includes("/")&&c&&typeof c.doc=="function"){let d=await c.doc(r).get();if(d.exists)return d}if(r&&typeof a.doc=="function"){let d=await a.doc(r).get();if(d.exists)return d}return}catch{return}}function Ve(e,t,n,o){async function r(f,i,m,s){if(!i.rules)return {allowed:true};let w=i.rules?.[m];if(!w)return {allowed:false,errorResponse:b(f,`Operation "${m}" is not allowed for this repository`,403)};try{let h=await w(s);return h===!1?{allowed:!1,errorResponse:b(f,"Forbidden",403)}:typeof h=="string"?{allowed:!1,errorResponse:b(f,h,403)}:typeof h=="object"&&h!==null&&!h.allowed?{allowed:!1,errorResponse:b(f,h.reason||"Forbidden",403)}:{allowed:!0}}catch(h){let x=n&&h instanceof Error?h.message:"Forbidden";return {allowed:false,errorResponse:b(f,x,403)}}}async function a(f,i,m,s){if(!f.rules)return s;let w=f.rules?.filter;if(!w)return s;let h=[];for(let x of s)try{await w({user:i,doc:x,params:m})&&h.push(x);}catch{}return h}function c(f){return f.get("user")??f.get("docsUser")??null}function d(f,i){if(!f){let m=i.req.path.split("/");for(let s of m)if(e[s]){f=s;break}}return !f||!e[f]?null:e[f]??null}function u(f,i){return Fe(f,{pathKey:i.pathKey,documentKey:i.documentKey,parentKeys:i.parentKeys,documentPathTemplate:i.documentPathTemplate,isGroup:i.isGroup})}async function l(f,i){let m=`by${f.documentKey.charAt(0).toUpperCase()}${f.documentKey.slice(1)}`,s=f.repo.get[m];if(typeof s=="function")try{let h=await s(i);if(h)return h}catch{}return (await f.repo.query.by({where:[[f.documentKey,"==",i]],limit:1}))[0]??null}async function g(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);let w=c(i),h=await r(i,s,"list",{user:w,query:i.req.query(),params:m});if(!h.allowed)return h.errorResponse;let x=[],k;try{let p=i.req.query(),T=Math.min(Number(p.pageSize)||s.pageSize,100),C=p.cursor,q=p.direction?.toLowerCase()==="prev"?"prev":"next",O=p.orderBy,$=p.orderDir?.toLowerCase()==="desc"?"desc":"asc",j=p.select,N=j?j.split(",").map(M=>M.trim()):void 0,z=p.withTotal,A=z==="true"||z==="1"||z===!0,P;s.allowedIncludes&&p.includes&&(P=(typeof p.includes=="string"?p.includes.split(",").map(L=>L.trim()):Array.isArray(p.includes)?p.includes:[]).filter(L=>typeof L=="string"&&s.allowedIncludes.includes(L)),P?.length===0&&(P=void 0));let I=Nt(p,s.filterableFields);x=I.map(M=>({field:M.field,op:M.op,value:String(M.value??"")})),O&&(k={field:O,dir:$});let U={pageSize:T,direction:q,...A?{withTotal:!0}:{}};if(C)try{let M=typeof C=="string"?JSON.parse(C):C;U.cursor=await Le(s,M);}catch{}if(O){if(s.orderableFields&&!s.orderableFields.includes(O))return b(i,`Field not orderable: ${O}`,400);U.orderBy=[{field:O,direction:$}];}if(I.length>0){U.where=[];for(let M of I){let L=le(s.schema,M.field,M.value,M.op);if(!L.success)return b(i,`Invalid filter value for '${M.field}': ${L.error}`,400);U.where.push([M.field,M.op,L.data]);}}N&&(U.select=N),P&&(U.include=P);let Z=await s.repo.query.paginate(U),mt={items:await a(s,c(i),m,Z.data),hasNextPage:Z.hasNextPage,hasPrevPage:Z.hasPrevPage,nextCursor:fe(Z.nextCursor),prevCursor:fe(Z.prevCursor),...Z.totalCount!==void 0?{totalCount:Z.totalCount,totalCountIsExact:Z.totalCountIsExact}:{}};return W(i,mt,{pageSize:T,hasMore:Z.hasNextPage,...Z.totalCount!==void 0?{totalCount:Z.totalCount,totalCountIsExact:Z.totalCountIsExact}:{}})}catch(p){return await ke(i,p,{repoName:m.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:x,sort:k},"Failed to fetch documents",n,o)}}async function y(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);let w=c(i),h=await r(i,s,"list",{user:w,query:f.input||{},params:m});if(!h.allowed)return h.errorResponse;let x=[],k;try{let p=f.input||{},T=Math.min(p.pageSize||s.pageSize,100),C=p.direction==="prev"?"prev":"next";p.where&&(x=p.where.map(z=>({field:String(z[0]),op:z[1],value:String(z[2]??"")}))),p.orderBy&&p.orderBy[0]&&(k={field:p.orderBy[0].field,dir:p.orderBy[0].direction==="desc"?"desc":"asc"});let q=p.withTotal===!0||String(p.withTotal)==="true",O={pageSize:T,direction:C,...q?{withTotal:!0}:{}};if(p.cursor)try{let z=typeof p.cursor=="string"?JSON.parse(p.cursor):p.cursor;O.cursor=await Le(s,z);}catch{}if(s.allowedIncludes&&p.includes&&p.includes.length>0){let z=p.includes.filter(A=>typeof A=="string"?s.allowedIncludes.includes(A):typeof A=="object"&&A!==null&&"relation"in A&&typeof A.relation=="string"?s.allowedIncludes.includes(A.relation):!1);z.length>0&&(O.include=z);}if(p.where&&p.where.length>0){if(s.filterableFields){let A=new Set(s.filterableFields),P=p.where.filter(I=>!A.has(I[0]));if(P.length>0){b(i,`Fields not filterable: ${P.map(I=>I[0]).join(", ")}`,400);return}}let z=[];for(let A of p.where){let P=ne(A[1]),I=le(s.schema,A[0],A[2],P);if(!I.success){b(i,`Invalid filter value for '${A[0]}': ${I.error}`,400);return}z.push([A[0],P,I.data]);}O.where=z;}if(p.orWhere&&p.orWhere.length>0){if(s.filterableFields){let A=new Set(s.filterableFields),P=p.orWhere.filter(I=>!A.has(I[0]));if(P.length>0){b(i,`Fields not filterable: ${P.map(I=>I[0]).join(", ")}`,400);return}}let z=[];for(let A of p.orWhere){let P=ne(A[1]),I=le(s.schema,A[0],A[2],P);if(!I.success){b(i,`Invalid filter value for '${A[0]}': ${I.error}`,400);return}z.push([A[0],P,I.data]);}O.orWhere=z;}if(p.orWhereGroups&&p.orWhereGroups.length>0){if(s.filterableFields){let A=new Set(s.filterableFields);for(let P of p.orWhereGroups){let I=P.filter(U=>!A.has(U[0]));if(I.length>0){b(i,`Fields not filterable: ${I.map(U=>U[0]).join(", ")}`,400);return}}}let z=[];for(let A of p.orWhereGroups){let P=[];for(let I of A){let U=ne(I[1]),Z=le(s.schema,I[0],I[2],U);if(!Z.success){b(i,`Invalid filter value for '${I[0]}': ${Z.error}`,400);return}P.push([I[0],U,Z.data]);}z.push(P);}O.orWhereGroups=z;}if(p.orderBy&&p.orderBy.length>0){if(s.orderableFields){let z=new Set(s.orderableFields),A=p.orderBy.filter(P=>!z.has(P.field));if(A.length>0){b(i,`Fields not orderable: ${A.map(P=>P.field).join(", ")}`,400);return}}O.orderBy=p.orderBy;}p.select&&p.select.length>0&&(O.select=p.select);let $=await s.repo.query.paginate(O),N={items:await a(s,c(i),m,$.data),hasNextPage:$.hasNextPage,hasPrevPage:$.hasPrevPage,nextCursor:fe($.nextCursor),prevCursor:fe($.prevCursor),...$.totalCount!==void 0?{totalCount:$.totalCount,totalCountIsExact:$.totalCountIsExact}:{}};return W(i,N,{pageSize:T,hasMore:$.hasNextPage,...$.totalCount!==void 0?{totalCount:$.totalCount,totalCountIsExact:$.totalCountIsExact}:{}})}catch(p){return await ke(i,p,{repoName:m.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:x,sort:k},"Failed to query documents",n,o)}}async function S(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);let w=m.id;if(!w)return b(i,"Document ID required",400);try{let h=await l(s,w);if(!h)return b(i,"Document not found",404);let x=c(i),k=await r(i,s,"get",{user:x,doc:h,params:m});if(!k.allowed)return k.errorResponse;if(s.rules?.filter)try{if(!await s.rules.filter({user:x,doc:h,params:m}))return b(i,"Document not found",404)}catch{return b(i,"Document not found",404)}return W(i,h)}catch(h){return await ke(i,h,{repoName:m.repoName||s.name,ref:s.repo.ref,path:s.path,isGroup:!!s.isGroup,filters:[{field:s.documentKey,op:"==",value:w}]},"Failed to fetch document",n,o)}}async function E(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);try{let w=f.input||{},h=c(i),x=await r(i,s,"create",{user:h,body:w,params:m});if(!x.allowed)return x.errorResponse;let k=pe(s.schema,w,s.createFields,!1,s.systemKeys);if(!k.success)return b(i,k.error,400);if(s.validate){let T=await s.validate(k.data,"create");if(T)return b(i,T,400)}let p;if(s.isGroup&&s.parentKeys&&s.parentKeys.length>0){let T={...k.data},C=s.parentKeys.filter(q=>T[q]===void 0||T[q]===null||typeof T[q]=="string"&&T[q].trim()==="");if(C.length>0){b(i,`Missing parent key(s) for subcollection create: ${C.join(", ")}`,400);return}if(typeof s.repo.create=="function")p=await s.repo.create(T);else {let q=s.parentKeys.map($=>String(T[$])),O=T[s.documentKey]||xe();p=await s.repo.set(...q,O,T);}}else p=await s.repo.create(k.data);return W(i,p,void 0,201)}catch(w){let h=n&&w instanceof Error?w.message:"Failed to create document";return b(i,h,500)}}async function F(f,i){let m=f.c,s=m.req.param(),w=d(s.repoName,m);if(!w)return b(m,"Repository not found",404);let h=s.id;if(!h)return b(m,"Document ID required",400);try{let x=f.input||{},k=await l(w,h);if(!k)return b(m,"Document not found",404);let p=pe(w.schema,x,w.mutableFields,i,w.systemKeys);if(!p.success)return b(m,p.error,400);if(w.validate){let j=await w.validate(p.data,"update");if(j)return b(m,j,400)}let T=ue(k,p.data),C=c(m),q=await r(m,w,"update",{user:C,doc:k,body:p.data,diff:T,params:s});if(!q.allowed)return q.errorResponse;let O=u(k,w)??[h],$=await w.repo.update(...O,p.data);return W(m,$)}catch(x){let k=n&&x instanceof Error?x.message:"Failed to update document";return b(m,k,500)}}async function v(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);if(!s.allowDelete)return b(i,"Delete not allowed for this repository",403);let w=m.id;if(!w)return b(i,"Document ID required",400);try{let h=await l(s,w);if(!h)return b(i,"Document not found",404);let x=c(i),k=await r(i,s,"delete",{user:x,doc:h,params:m});if(!k.allowed)return k.errorResponse;let p=u(h,s)??[w];return await s.repo.delete(...p),W(i,{deleted:!0})}catch(h){let x=n&&h instanceof Error?h.message:"Failed to delete document";return b(i,x,500)}}function R(f){return f.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 D(f){let i=f.c,m=i.req.param(),s=d(m.repoName,i);if(!s)return b(i,"Repository not found",404);try{let w=f.input||{};if(!Array.isArray(w.operations))return b(i,"operations array is required",400);let h=c(i),x=s.repo.batch.create(),k=[];for(let p of w.operations){if(!p.type||!["create","update","delete"].includes(p.type))return b(i,"Invalid operation type",400);if(p.type==="create"){let T=await r(i,s,"create",{user:h,body:p.data,params:m});if(!T.allowed)return T.errorResponse;let C=pe(s.schema,p.data,s.createFields,!1,s.systemKeys);if(!C.success)return b(i,C.error,400);let q=p.data[s.documentKey]||xe(),O={...C.data};if(s.createdKey&&O[s.createdKey]===void 0&&(O[s.createdKey]=new Date),s.isGroup&&s.parentKeys){let $=s.parentKeys.map(j=>O[j]);x.set(...$,q,O);}else x.set(q,O);k.push({op:"create",id:q});}else if(p.type==="update"){if(!p.id)return b(i,"id required for update",400);let T=await l(s,p.id);if(!T)return b(i,`Document ${p.id} not found`,404);let C=pe(s.schema,p.data,s.mutableFields,!0,s.systemKeys);if(!C.success)return b(i,C.error,400);if(s.validate){let j=await s.validate(C.data,"update");if(j)return b(i,j,400)}let q=ue(T,C.data),O=await r(i,s,"update",{user:h,doc:T,body:C.data,diff:q,params:m});if(!O.allowed)return O.errorResponse;let $=u(T,s)??[p.id];x.update(...$,C.data),k.push({op:"update",id:p.id});}else if(p.type==="delete"){if(!s.allowDelete)return b(i,"Delete not allowed",403);if(!p.id)return b(i,"id required for delete",400);let T=await l(s,p.id);if(!T)return b(i,`Document ${p.id} not found`,404);let C=await r(i,s,"delete",{user:h,doc:T,params:m});if(!C.allowed)return C.errorResponse;let q=u(T,s)??[p.id];x.delete(...q),k.push({op:"delete",id:p.id});}}return await x.commit(),W(i,{results:k})}catch(w){let h=n&&w instanceof Error?w.message:"Batch operation failed";return b(i,h,500)}}return {handleList:g,handleQuery:y,handleGet:S,handleCreate:E,handleUpdate:F,handleDelete:v,handleBatch:D,handleOptions:R}}function ee(e){try{return z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let o=t.zodSchema?._zod?.def;o&&(o.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):o.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 H(e){return {$ref:`#/components/schemas/${e}`}}function _(e){return {description:e,content:{"application/json":{schema:H("ErrorResponse")}}}}function Y(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Zt(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 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 Ht(e,t){let n=t.split("."),o=oe(e);for(let r=0;r<n.length;r++){let a=n[r];if(!a)continue;let c=o?.shape;if(!c||!c[a])return;let d=c[a];if(r===n.length-1)return d;o=oe(d);}return o}function X(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,o=r=>{let a=getOpenApiMetadata(e);return a&&typeof r.openapi=="function"?r.openapi(a):r};if(n==="ZodObject"||n==="object"){let r=e.shape,a={};for(let[c,d]of Object.entries(r))a[c]=X(d);return o(z.object(a).partial())}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let a=X(r);return a===r?e:o(a.optional())}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let a=X(r);return a===r?e:o(a.nullable())}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?o(X(r).optional()):e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let a=r.map(d=>X(d));return a.some((d,u)=>d!==r[u])?o(z.union(a)):e}return e}function Ce(e,t="",n=0){if(n>5)return [];let r=oe(e)?.shape;if(!r)return [];let a=[];for(let[c,d]of Object.entries(r)){let u=t?`${t}.${c}`:c,l=oe(d);l?.shape&&typeof l.shape=="object"?(a.push({path:u,zodSchema:d}),a.push(...Ce(l,u,n+1))):a.push({path:u,zodSchema:d});}return a}function Mt(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Ht(e.schema,t)})):Ce(e.schema)}function Je(e){if(!e)return {type:"string"};let t=ee(e);return delete t.$schema,delete t.title,t}function Xe(){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 Bt(e){let t=Mt(e),n=e.orderableFields??t.map(c=>c.path),o=t.map(c=>c.path);if(t.length===0)return Xe();let r=[];for(let{path:c,zodSchema:d}of t){let u=Je(d),l=oe(d),y=l?._zod?.def?.type==="array"||l?._def?.typeName==="ZodArray"||l?._def?.type==="array"?Je(l?._zod?.def?.element??l?._def?.type??l?._def?.element):u;r.push({type:"array",description:`Condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},u],minItems:3,maxItems:3}),r.push({type:"array",description:`List condition on '${c}' (in, not-in)`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:u}],minItems:3,maxItems:3}),r.push({type:"array",description:`Array contains condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains","contains"]},y],minItems:3,maxItems:3}),r.push({type:"array",description:`Array contains-any condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:y}],minItems:3,maxItems:3});}let a={oneOf:r};return {type:"object",properties:{where:{type:"array",items:a,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:a,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:a},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:o},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 Ut(e,t,n,o,r,a=null,c="QueryRequestBody"){let d={},u=e.name,l=`${t}/${e.name}`,g=`${l}/{${e.documentKey}}`,y={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};d[l]={post:{operationId:`create${G(e.name)}`,summary:`Create a ${K(e.name)}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:H(o??n)}}},responses:{201:Y("Document created",H(n)),400:_("Validation error"),403:_("Forbidden"),500:_("Internal server error")}}},d[`${l}/query`]={post:{operationId:`query${G(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:H(c)}}},responses:{200:Zt(H(n)),400:_("Invalid query"),403:_("Forbidden"),424:_("Missing composite index (includes indexUrl in response)"),500:_("Internal server error")}}},d[`${l}/batch`]={post:{operationId:`batch${G(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[u],requestBody:{required:true,content:{"application/json":{schema:H(`${n}BatchRequest`)}}},responses:{200:Y("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 S={};return S.get={operationId:`get${G(K(e.name))}`,summary:`Get a single ${K(e.name)}`,tags:[u],parameters:[y],responses:{200:Y("Document found",H(n)),400:_("Document ID required"),403:_("Forbidden"),404:_("Document not found"),424:_("Missing composite index (includes indexUrl in response)"),500:_("Internal server error")}},S.put={operationId:`update${G(K(e.name))}`,summary:`Update a ${K(e.name)} (full replace)`,tags:[u],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:H(r??n)}}},responses:{200:Y("Document updated",H(n)),400:_("Validation error"),403:_("Forbidden"),404:_("Document not found"),500:_("Internal server error")}},S.patch={operationId:`patch${G(K(e.name))}`,summary:`Partially update a ${K(e.name)}`,tags:[u],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:H(a??r??n)}}},responses:{200:Y("Document patched",H(n)),400:_("Validation error"),403:_("Forbidden"),404:_("Document not found"),500:_("Internal server error")}},e.allowDelete&&(S.delete={operationId:`delete${G(K(e.name))}`,summary:`Delete a ${K(e.name)}`,tags:[u],parameters:[y],responses:{200:Y("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:_("Document ID required"),403:_("Forbidden"),404:_("Document not found"),500:_("Internal server error")}}),d[g]=S,d}function Ee(e,t,n={}){let{title:o="CRUD API",version:r="1.0.0",description:a,servers:c,auth:d=false}=n,u=t==="/"?"":t.replace(/\/$/,""),l={},g={},y=[];l.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"]},l.QueryRequestBody=Xe();for(let[v,R]of Object.entries(e)){let D=G(K(v)),f=`${D}Create`,i=`${D}Update`,m=`${D}Patch`,s=`${D}QueryRequestBody`;l[D]=ee(R.schema),l[s]=Bt(R);let w=j=>{let N={},z=Ce(R.schema);for(let{path:A,zodSchema:P}of z){let I=A.split(".")[0];R.systemKeys.includes(I)||R.systemKeys.includes(A)||j&&j.length>0&&!j.includes(A)&&!j.includes(I)||(A.includes(".")?N[A]=P.optional():N[A]=P);}return N},h=null,x=w(R.createFields);if(R.isGroup&&R.parentKeys&&R.parentKeys.length>0){let j=R.schema?.shape??{};for(let N of R.parentKeys)!x[N]&&j[N]&&(x[N]=j[N]);}if(Object.keys(x).length>0){let j=ee(z.object(x));if(R.isGroup&&R.parentKeys&&R.parentKeys.length>0){let N=new Set(Array.isArray(j.required)?j.required:[]);for(let z of R.parentKeys)j.properties?.[z]&&N.add(z);N.size>0&&(j.required=Array.from(N));}l[f]=j,h=f;}let k=null,p=null,T=w(R.mutableFields);if(Object.keys(T).length>0){let j=z.object(T);l[i]=ee(j),k=i,l[m]=ee(X(j)),p=m;}else l[m]=ee(X(R.schema)),p=m;let C=`${D}BatchCreateOperation`,q=`${D}BatchUpdateOperation`,O=`${D}BatchDeleteOperation`;l[C]={type:"object",title:`${D} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:H(h??D)},required:["type","data"]},l[q]={type:"object",title:`${D} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:H(p??k??D)},required:["type","id","data"]},R.allowDelete&&(l[O]={type:"object",title:`${D} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),l[`${D}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[H(C),H(q),...R.allowDelete?[H(O)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let $=Ut(R,u,D,h,k,p,s);Object.assign(g,$),y.push({name:v,description:`Operations on ${v} (collection: ${R.path})`});}let S={},E;return d==="basic"?(S.basicAuth={type:"http",scheme:"basic"},E=[{basicAuth:[]}]):d==="bearer"&&(S.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},E=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:o,version:r,...a?{description:a}:{}},...c&&c.length>0?{servers:c}:{},paths:g,components:{schemas:l,...Object.keys(S).length>0?{securitySchemes:S}:{}},...E?{security:E}:{},tags:y}}function G(e){return e.charAt(0).toUpperCase()+e.slice(1)}function K(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 te=class extends Error{constructor(n,o){super("Request validation failed");this.zodError=n;this.source=o;this.statusCode=400;this.name="ValidationError";}};var se=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},ie=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function Ye(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function et(e,t){return t instanceof te?e.json({success:false,error:"Validation failed",issues:Ye(t.zodError)},400):t instanceof se?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof ie?e.json({success:false,error:"Output validation failed",issues:Ye(t.zodError)},500):null}extendZodWithOpenApi(z);var tt="Successful response",nt="Error response";function B(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,o=n._zod?.def??n.def;if(!o)return;if(o.type==="custom"){let a=getOpenApiMetadata(n);a?.type||z.globalRegistry.add(n,{...a??{},type:"object"});return}if(o.innerType&&B(o.innerType,t),o.element&&B(o.element,t),o.valueType&&B(o.valueType,t),o.keyType&&B(o.keyType,t),o.left&&B(o.left,t),o.right&&B(o.right,t),o.in&&B(o.in,t),o.out&&B(o.out,t),typeof o.getter=="function")try{B(o.getter(),t);}catch{}if(Array.isArray(o.options))for(let a of o.options)B(a,t);if(Array.isArray(o.items))for(let a of o.items)B(a,t);let r=typeof o.shape=="function"?o.shape():o.shape;if(r&&typeof r=="object")for(let a of Object.values(r))B(a,t);}function Ie(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)Ie(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))Ie(n);}function Vt(e){return e==="get"?"query":"json"}function Jt(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:nt,schema:e};let t=e;return {description:t.description??nt,schema:t.schema}}function st(e,t,n,o){let r=new OpenAPIRegistry;if(n.securitySchemes)for(let[d,u]of Object.entries(n.securitySchemes))r.registerComponent("securitySchemes",d,u);for(let d of e){let u=d.method,l=d.source??Vt(u),g=en(t,d.path??"/"),y=d.status??200;d.input&&B(d.input);let S=Xt(u,l,d.input),E=rt(l,d.input,"query"),F=rt(l,d.input,"param"),v=tn(u,g),R=Jt(d.output,o);R&&B(R);let D={[y]:R?{description:tt,content:{"application/json":{schema:R}}}:{description:tt}};if(o?.errors)for(let[f,i]of Object.entries(o.errors)){let{description:m,schema:s}=Qt(i);s&&B(s),D[f]=s?{description:m,content:{"application/json":{schema:s}}}:{description:m};}r.registerPath({method:u,path:Yt(g),operationId:v,summary:d.summary,description:d.description,tags:d.tags,deprecated:d.deprecated,security:d.security,request:{...E?{query:E}:{},...F?{params:F}:{},...S?{body:S}:{}},responses:D});}let c=new OpenApiGeneratorV31(r.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return Ie(c),c}function Xt(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 rt(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function Yt(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function en(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,o=t.startsWith("/")?t:`/${t}`,r=`${n}${o}`;return r===""?"/":r}function tn(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function it(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
1
|
+
import {z}from'zod';import {Timestamp}from'firebase-admin/firestore';import {randomBytes}from'crypto';import {extendZodWithOpenApi,getOpenApiMetadata,OpenAPIRegistry,OpenApiGeneratorV31}from'@asteasolutions/zod-to-openapi';import {Hono}from'hono';import {getRequestListener}from'@hono/node-server';import {AsyncLocalStorage}from'async_hooks';var he=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var Ot=Object.prototype.hasOwnProperty;var Ct=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Et=(e,t)=>{for(var n in t)he(e,n,{get:t[n],enumerable:true});},It=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of kt(t))!Ot.call(e,o)&&o!==n&&he(e,o,{get:()=>t[o],enumerable:!(r=vt(t,o))||r.enumerable});return e};var Pt=e=>It(he({},"__esModule",{value:true}),e);var St={};Et(St,{DEFAULT_HTML_CSP:()=>Rt,securityHeaders:()=>On});function On(e={}){let t=e.csp===void 0?Rt:e.csp,n=e.frameOptions===void 0?"DENY":e.frameOptions,r=e.referrerPolicy===void 0?"no-referrer":e.referrerPolicy,o=e.cacheControl===void 0?"private, no-store":e.cacheControl;return async(i,c,u)=>{typeof c?.setHeader=="function"&&(c.setHeader("X-Content-Type-Options","nosniff"),n&&c.setHeader("X-Frame-Options",n),r&&c.setHeader("Referrer-Policy",r),o&&c.setHeader("Cache-Control",o),t&&c.setHeader("Content-Security-Policy",t)),await u();}}var bt,xt,Rt,At=Ct(()=>{"use strict";bt="https://cdn.jsdelivr.net",xt="https://www.gstatic.com",Rt=["default-src 'self'",`script-src 'self' 'unsafe-inline' 'unsafe-eval' ${bt} ${xt}`,`style-src 'self' 'unsafe-inline' ${bt}`,`connect-src 'self' ${xt} 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 Fe="preserve";function be(){return Fe}function Dt(e){return typeof e=="object"&&e!==null&&typeof e._seconds=="number"&&typeof e._nanoseconds=="number"}function Ne(e){if(e==null)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e instanceof Timestamp)return e.toDate();if(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 $e(e){return e}var xe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Re(){let e="";for(;e.length<20;){let t=randomBytes(20);for(let n=0;n<t.length&&e.length<20;n++){let r=t[n];r>=xe.length*4||(e+=xe.charAt(r%xe.length));}}return e}function Ze(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function He(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(y=>y.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let y=r[0];return {rawPath:e,collectionId:y,collectionPath:y,parentKeys:[],documentPathTemplate:n?null:`${y}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let o=r.length%2===0,i=o?r.slice(0,-1):r,c=i[i.length-1],u=i.join("/"),p=i.slice(0,-1).map(Ze).filter(y=>y!==null),m=o?r.join("/"):`${u}/{${t}}`;return {rawPath:e,collectionId:c,collectionPath:u,parentKeys:p,documentPathTemplate:m,hasTemplate:true}}function Me(e,t={}){if(!e||typeof e!="object")return;let{pathKey:n,documentKey:r="docId",parentKeys:o,documentPathTemplate:i,isGroup:c}=t,u=n&&typeof e[n]=="string"&&e[n]?e[n]:void 0;if(u&&i){let d=u.split("/").filter(Boolean),p=i.split("/").filter(Boolean);if(d.length===p.length){let m=[];for(let y=0;y<p.length;y++)Ze(p[y])!==null&&m.push(d[y]);if(m.length>0)return m}}if(o&&o.length>0){let d=o.length+1;if(u){let m=u.split("/").filter(Boolean),y=[];for(let b=1;b<m.length;b+=2)y.push(m[b]);if(y.length>=d)return y.slice(y.length-d)}let p=r?e[r]:void 0;if(typeof p=="string"&&p.trim()!==""){let m=[],y=true;for(let b of o){let O=e[b];if(typeof O=="string"&&O.trim()!=="")m.push(O);else {y=false;break}}if(y)return [...m,p]}}if(u){let d=u.split("/").filter(Boolean),p=[];for(let m=1;m<d.length;m+=2)p.push(d[m]);if(p.length>0)return !c&&(!o||o.length===0)?[p[p.length-1]]:p}}function Be(e){let t=e;if(t._zod?.def?.element)return t._zod.def.element;if(t._def?.type)return t._def.type}var _t=new Set(["<","<=",">",">=","!="]),qt=new Set(["array-contains","array-contains-any"]);function Se(e){return e==="desc"?"DESCENDING":"ASCENDING"}function Ft(e){return He(e).collectionId||e}function Nt(e,t,n,r,o){let i=[],c=new Set;for(let d of r)if(d.op==="=="||d.op==="in"||d.op==="not-in"){if(c.has(d.field))continue;c.add(d.field),i.push({fieldPath:d.field,order:"ASCENDING"});}for(let d of r)if(qt.has(d.op)){if(c.has(d.field))continue;c.add(d.field),i.push({fieldPath:d.field,arrayConfig:"CONTAINS"});}for(let d of r)if(_t.has(d.op)){if(c.has(d.field))continue;c.add(d.field);let p=o?.field===d.field?Se(o.dir):"ASCENDING";i.push({fieldPath:d.field,order:p});}if(o&&!c.has(o.field)&&i.push({fieldPath:o.field,order:Se(o.dir)}),i.length===1&&n)return Ht(e,t,i[0]);let u=o&&i.some(d=>d.fieldPath===o.field)?Se(o.dir):"ASCENDING";return i.push({fieldPath:"__name__",order:u}),$t(e,t,n,i)}function $t(e,t,n,r,o="(default)"){let i=`projects/${e}/databases/${o}/collectionGroups/${t}/indexes/_`,c=[...ve(1,i),...ce(2,n?2:1)];for(let p of r)c.push(...Ue(3,Ke(p)));let u=o==="(default)"?"-default-":o,d=encodeURIComponent(Le(c));return `https://console.firebase.google.com/project/${e}/firestore/databases/${u}/indexes?create_composite=${d}`}function Zt(e){return e.match(/https:\/\/console\.firebase\.google\.com[^\s)"]*/)?.[0]}function Ae(e){let t=[],n=e>>>0;for(;n>=128;)t.push(n&127|128),n>>>=7;return t.push(n&127),t}function Te(e,t){return e<<3|t}function ve(e,t){let n=Array.from(new TextEncoder().encode(t));return [Te(e,2),...Ae(n.length),...n]}function ce(e,t){return [Te(e,0),...Ae(t)]}function Ue(e,t){return [Te(e,2),...Ae(t.length),...t]}function Ke(e){let t=[...ve(1,e.fieldPath)];return e.arrayConfig==="CONTAINS"?t.push(...ce(3,1)):t.push(...ce(2,e.order==="DESCENDING"?2:1)),t}function Le(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 Ht(e,t,n,r="(default)"){let o=`projects/${e}/databases/${r}/collectionGroups/${t}/fields/${n.fieldPath}`,i=[...ve(1,o),...ce(2,2),...Ue(3,Ke(n))],c=r==="(default)"?"-default-":r,u=encodeURIComponent(Le(i));return `https://console.firebase.google.com/project/${e}/firestore/databases/${c}/indexes/automatic?create_exemption=${u}`}function Mt(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 Ge(e,t){let n=e??{},r=Bt(e),o;if(r&&(o=n.message?Zt(n.message):void 0,!o)){let i=Mt(t.ref);if(i){let c=Ft(t.path);o=Nt(i,c,t.isGroup,t.filters,t.sort);}}return {type:r?"index":"error",message:r?"This query requires a composite index that does not exist yet.":n.message??"Query failed",indexUrl:o}}function de(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 Timestamp&&t instanceof 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 r=0;r<e.length;r++)if(!de(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof Timestamp||t instanceof Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return false;for(let i of r)if(!Object.prototype.hasOwnProperty.call(t,i)||!de(e[i],t[i],n))return false;return true}return false}function le(e,t){let n=e||{},r={},o={...n};for(let[i,c]of Object.entries(t||{})){let u=n[i];de(u,c)||(r[i]=c,o[i]=c);}return {before:n,after:o,changes:r}}function Ut(e){return e}async function We(e,t,n){let r=e.changes||{};for(let o of Object.keys(r)){let i=t[o];if(i&&i.length>0){for(let c of i)if(await c.rule({diff:e,key:o,user:n,authenticatedUser:n})===false)return {allowed:false,reason:c.description}}}return {allowed:true}}function Kt(e){return async t=>We(t.diff,e,t.user)}var ke=1e3;function Ve(e,t){if(e===void 0)return {success:true,value:Math.min(Math.max(1,t),ke)};let n=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return !Number.isInteger(n)||n<=0||n>ke?{success:false,error:`Invalid pageSize: must be an integer between 1 and ${ke}`}:{success:true,value:n}}function Ee(e,t,n=200){let r=$e(t);return e.json(r,n)}function V(e,t,n,r=200){return Ee(e,{success:true,data:t,meta:n},r)}function x(e,t,n=400){return Ee(e,{success:false,error:t},n)}async function Oe(e,t,n,r,o,i){let c=Ge(t,n),u=c.type==="index",d=u?424:500,m={success:false,error:u?c.message:o&&t instanceof Error?t.message:r};if(u&&(m.errorType="index",c.indexUrl&&(m.indexUrl=c.indexUrl,i)))try{let y=i({indexUrl:c.indexUrl,repoName:n.repoName??"",path:n.path,isGroup:n.isGroup,filters:n.filters,sort:n.sort,error:t,c:e});y instanceof Promise&&await y;}catch(y){o&&console.error("[crudServer] Error in indexesError callback:",y);}return Ee(e,m,d)}function J(e){let t=e._def??e.def;if(!t)return e;let n=t.typeName??t.type;if(n==="ZodDate"||n==="date")return z.preprocess(r=>Ne(r)??r,e);if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[i,c]of Object.entries(r))o[i]=J(c);return z.object(o)}if(n==="ZodArray"||n==="array"){let r=t.element??t.type;if(r)return z.array(J(r))}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(r)return J(r).optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(r)return J(r).nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType,o=t.defaultValue;if(r){let i=J(r);return typeof o=="function"?i.default(o()):i.default(o)}}return e}function Lt(e,t,n=[]){let r=e.shape,o={},i=t&&t.length>0?t:Object.keys(r);for(let c of i){if(n.includes(c))continue;let u=c.split(".")[0];u&&r[u]&&(o[u]=r[u]);}return z.object(o)}function Ce(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 Xe(e,t){let n=t.split("."),r=Ce(e);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let c=r?.shape;if(!c||!c[i])return;let u=c[i];if(o===n.length-1)return u;r=Ce(u);}return r}function Q(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type;if(n==="ZodObject"||n==="object"){let r=e.shape,o={};for(let[i,c]of Object.entries(r))o[i]=Q(c);return z.object(o).partial()}if(n==="ZodOptional"||n==="optional"){let r=t.innerType;if(!r)return e;let o=Q(r);return o===r?e:o.optional()}if(n==="ZodNullable"||n==="nullable"){let r=t.innerType;if(!r)return e;let o=Q(r);return o===r?e:o.nullable()}if(n==="ZodDefault"||n==="default"){let r=t.innerType;return r?Q(r).optional():e}if(n==="ZodUnion"||n==="union"){let r=t.options;if(!r||r.length<2)return e;let o=r.map(c=>Q(c));return o.some((c,u)=>c!==r[u])?z.union(o):e}return e}function pe(e,t,n,r=false,o=[]){if(typeof t!="object"||t===null||Array.isArray(t))return {success:false,error:"Data payload must be an object"};try{let i=t,c={},u={};for(let[d,p]of Object.entries(i))if(d.includes(".")){let m=d.split(".")[0];if(o.includes(d)||o.includes(m))continue;if(n&&n.length>0&&!n.includes(d)&&!n.includes(m))return {success:!1,error:`Field '${d}' is not allowed for this operation`};let y=Xe(e,d);if(!y)return {success:!1,error:`Field '${d}' does not exist in schema`};let b=r?Q(y):y,N=(be()==="normalize"?J(b):b).parse(p);c[d]=N;}else u[d]=p;if(Object.keys(u).length>0||Object.keys(c).length===0){let d=Lt(e,n,o),p=r?Q(d):d,y=(be()==="normalize"?J(p):p).parse(u);Object.assign(c,y);}return {success:!0,data:c}}catch(i){return i instanceof z.ZodError?{success:false,error:`Validation failed: ${i.issues.map(u=>`${u.path.join(".")}: ${u.message}`).join(", ")}`}:{success:false,error:"Validation failed"}}}var Ye={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 re(e){return Ye[e]??e}function Gt(e){return e in Ye}function fe(e,t,n,r){let o=Xe(e,t);if(!o||typeof o.safeParse!="function")return {success:true,data:n};let i=r?re(r):void 0,c=Ce(o),u=Be(c);if(i==="array-contains"){let m=u??o;if(typeof m.safeParse=="function"){let y=m.safeParse(n);return y.success?{success:true,data:y.data}:{success:false,error:y.error.issues.map(O=>O.message).join(", ")}}return {success:true,data:n}}if(i==="array-contains-any"){if(!Array.isArray(n))return {success:false,error:"Expected array value for array-contains-any"};let m=u??o,y=[];for(let b of n)if(typeof m.safeParse=="function"){let O=m.safeParse(b);if(O.success)y.push(O.data);else return {success:false,error:O.error.issues.map(C=>C.message).join(", ")}}else y.push(b);return {success:true,data:y}}let d=o.safeParse(n);if(d.success)return {success:true,data:d.data};if(Array.isArray(n)){let m=u??o,y=[];for(let b of n)if(typeof m.safeParse=="function"){let O=m.safeParse(b);if(O.success)y.push(O.data);else return {success:false,error:O.error.issues.map(C=>C.message).join(", ")}}else y.push(b);return {success:true,data:y}}return {success:false,error:d.error.issues.map(m=>m.message).join(", ")}}function Wt(e,t){let n=[],r=t?new Set(t):null;for(let[o,i]of Object.entries(e)){if(i===void 0||["cursor","direction","limit","pageSize","orderBy","orderDir","select","includes","withTotal"].includes(o))continue;let c=Array.isArray(i)?i[0]:i;if(c===void 0||c==="")continue;let u=o.lastIndexOf("__"),d,p="==";if(u!==-1){let y=o.slice(0,u),b=o.slice(u+2);Gt(b)?(d=y,p=re(b)):(d=o,p="==");}else d=o;if(r&&!r.has(d))continue;let m=c;p==="in"||p==="not-in"||p==="array-contains-any"?m=c.split(",").map(y=>Je(y.trim())):m=Je(c),n.push({field:d,op:p,value:m});}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 ye(e){return e?{docId:e.id,docPath:e.ref?.path??void 0}:null}async function Qe(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 r=typeof n.docPath=="string"?n.docPath:void 0,o=typeof n.docId=="string"?n.docId:void 0;try{let i=e.repo.ref,c=i?.firestore;if(r&&c&&typeof c.doc=="function"){let u=await c.doc(r).get();if(u.exists)return u}if(o&&o.includes("/")&&c&&typeof c.doc=="function"){let u=await c.doc(o).get();if(u.exists)return u}if(o&&typeof i.doc=="function"){let u=await i.doc(o).get();if(u.exists)return u}return}catch{return}}function et(e,t,n,r){async function o(f,s,g,a){if(!s.rules)return {allowed:true};let w=s.rules?.[g];if(!w)return {allowed:false,errorResponse:x(f,`Operation "${g}" is not allowed for this repository`,403)};try{let h=await w(a);return h===!1?{allowed:!1,errorResponse:x(f,"Forbidden",403)}:typeof h=="string"?{allowed:!1,errorResponse:x(f,h,403)}:typeof h=="object"&&h!==null&&!h.allowed?{allowed:!1,errorResponse:x(f,h.reason||"Forbidden",403)}:{allowed:!0}}catch(h){let R=n&&h instanceof Error?h.message:"Forbidden";return {allowed:false,errorResponse:x(f,R,403)}}}async function i(f,s,g,a){if(!f.rules)return a;let w=f.rules?.filter;if(!w)return a;let h=[];for(let R of a)try{await w({user:s,doc:R,params:g})&&h.push(R);}catch{}return h}function c(f){return f.get("user")??f.get("docsUser")??null}function u(f,s){if(!f){let g=s.req.path.split("/");for(let a of g)if(e[a]){f=a;break}}return !f||!e[f]?null:e[f]??null}function d(f,s){return Me(f,{pathKey:s.pathKey,documentKey:s.documentKey,parentKeys:s.parentKeys,documentPathTemplate:s.documentPathTemplate,isGroup:s.isGroup})}async function p(f,s){let g=`by${f.documentKey.charAt(0).toUpperCase()}${f.documentKey.slice(1)}`,a=f.repo.get[g];if(typeof a=="function")try{let h=await a(s);if(h)return h}catch{}return (await f.repo.query.by({where:[[f.documentKey,"==",s]],limit:1}))[0]??null}async function m(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);let w=c(s),h=await o(s,a,"list",{user:w,query:s.req.query(),params:g});if(!h.allowed)return h.errorResponse;let R=[],v;try{let l=s.req.query(),T=Ve(l.pageSize,a.pageSize);if(!T.success)return x(s,T.error,400);let P=T.value,D=l.cursor,_=l.direction?.toLowerCase()==="prev"?"prev":"next",E=l.orderBy,A=l.orderDir?.toLowerCase()==="desc"?"desc":"asc",$=l.select,L=$?$.split(",").map(M=>M.trim()):void 0,I=l.withTotal,k=I==="true"||I==="1"||I===!0,j;a.allowedIncludes&&l.includes&&(j=(typeof l.includes=="string"?l.includes.split(",").map(G=>G.trim()):Array.isArray(l.includes)?l.includes:[]).filter(G=>typeof G=="string"&&a.allowedIncludes.includes(G)),j?.length===0&&(j=void 0));let q=Wt(l,a.filterableFields);R=q.map(M=>({field:M.field,op:M.op,value:String(M.value??"")})),E&&(v={field:E,dir:A});let U={pageSize:P,direction:_,...k?{withTotal:!0}:{}};if(D)try{let M=typeof D=="string"?JSON.parse(D):D;U.cursor=await Qe(a,M);}catch{}if(E){if(a.orderableFields&&!a.orderableFields.includes(E))return x(s,`Field not orderable: ${E}`,400);U.orderBy=[{field:E,direction:A}];}if(q.length>0){U.where=[];for(let M of q){let G=fe(a.schema,M.field,M.value,M.op);if(!G.success)return x(s,`Invalid filter value for '${M.field}': ${G.error}`,400);U.where.push([M.field,M.op,G.data]);}}L&&(U.select=L),j&&(U.include=j);let Z=await a.repo.query.paginate(U),Tt={items:await i(a,c(s),g,Z.data),hasNextPage:Z.hasNextPage,hasPrevPage:Z.hasPrevPage,nextCursor:ye(Z.nextCursor),prevCursor:ye(Z.prevCursor),...Z.totalCount!==void 0?{totalCount:Z.totalCount,totalCountIsExact:Z.totalCountIsExact}:{}};return V(s,Tt,{pageSize:P,hasMore:Z.hasNextPage,...Z.totalCount!==void 0?{totalCount:Z.totalCount,totalCountIsExact:Z.totalCountIsExact}:{}})}catch(l){return await Oe(s,l,{repoName:g.repoName||a.name,ref:a.repo.ref,path:a.path,isGroup:!!a.isGroup,filters:R,sort:v},"Failed to fetch documents",n,r)}}async function y(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);let w=c(s),h=await o(s,a,"list",{user:w,query:f.input||{},params:g});if(!h.allowed)return h.errorResponse;let R=[],v;try{let l=f.input||{},T=Ve(l.pageSize,a.pageSize);if(!T.success)return x(s,T.error,400);let P=T.value,D=l.direction==="prev"?"prev":"next";l.where&&(R=l.where.map(I=>({field:String(I[0]),op:I[1],value:String(I[2]??"")}))),l.orderBy&&l.orderBy[0]&&(v={field:l.orderBy[0].field,dir:l.orderBy[0].direction==="desc"?"desc":"asc"});let _=l.withTotal===!0||String(l.withTotal)==="true",E={pageSize:P,direction:D,..._?{withTotal:!0}:{}};if(l.cursor)try{let I=typeof l.cursor=="string"?JSON.parse(l.cursor):l.cursor;E.cursor=await Qe(a,I);}catch{}if(a.allowedIncludes&&l.includes&&l.includes.length>0){let I=l.includes.filter(k=>typeof k=="string"?a.allowedIncludes.includes(k):typeof k=="object"&&k!==null&&"relation"in k&&typeof k.relation=="string"?a.allowedIncludes.includes(k.relation):!1);I.length>0&&(E.include=I);}if(l.where&&l.where.length>0){if(a.filterableFields){let k=new Set(a.filterableFields),j=l.where.filter(q=>!k.has(q[0]));if(j.length>0){x(s,`Fields not filterable: ${j.map(q=>q[0]).join(", ")}`,400);return}}let I=[];for(let k of l.where){let j=re(k[1]),q=fe(a.schema,k[0],k[2],j);if(!q.success){x(s,`Invalid filter value for '${k[0]}': ${q.error}`,400);return}I.push([k[0],j,q.data]);}E.where=I;}if(l.orWhere&&l.orWhere.length>0){if(a.filterableFields){let k=new Set(a.filterableFields),j=l.orWhere.filter(q=>!k.has(q[0]));if(j.length>0){x(s,`Fields not filterable: ${j.map(q=>q[0]).join(", ")}`,400);return}}let I=[];for(let k of l.orWhere){let j=re(k[1]),q=fe(a.schema,k[0],k[2],j);if(!q.success){x(s,`Invalid filter value for '${k[0]}': ${q.error}`,400);return}I.push([k[0],j,q.data]);}E.orWhere=I;}if(l.orWhereGroups&&l.orWhereGroups.length>0){if(a.filterableFields){let k=new Set(a.filterableFields);for(let j of l.orWhereGroups){let q=j.filter(U=>!k.has(U[0]));if(q.length>0){x(s,`Fields not filterable: ${q.map(U=>U[0]).join(", ")}`,400);return}}}let I=[];for(let k of l.orWhereGroups){let j=[];for(let q of k){let U=re(q[1]),Z=fe(a.schema,q[0],q[2],U);if(!Z.success){x(s,`Invalid filter value for '${q[0]}': ${Z.error}`,400);return}j.push([q[0],U,Z.data]);}I.push(j);}E.orWhereGroups=I;}if(l.orderBy&&l.orderBy.length>0){if(a.orderableFields){let I=new Set(a.orderableFields),k=l.orderBy.filter(j=>!I.has(j.field));if(k.length>0){x(s,`Fields not orderable: ${k.map(j=>j.field).join(", ")}`,400);return}}E.orderBy=l.orderBy;}l.select&&l.select.length>0&&(E.select=l.select);let A=await a.repo.query.paginate(E),L={items:await i(a,c(s),g,A.data),hasNextPage:A.hasNextPage,hasPrevPage:A.hasPrevPage,nextCursor:ye(A.nextCursor),prevCursor:ye(A.prevCursor),...A.totalCount!==void 0?{totalCount:A.totalCount,totalCountIsExact:A.totalCountIsExact}:{}};return V(s,L,{pageSize:P,hasMore:A.hasNextPage,...A.totalCount!==void 0?{totalCount:A.totalCount,totalCountIsExact:A.totalCountIsExact}:{}})}catch(l){return await Oe(s,l,{repoName:g.repoName||a.name,ref:a.repo.ref,path:a.path,isGroup:!!a.isGroup,filters:R,sort:v},"Failed to query documents",n,r)}}async function b(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);let w=g.id;if(!w)return x(s,"Document ID required",400);try{let h=await p(a,w);if(!h)return x(s,"Document not found",404);let R=c(s),v=await o(s,a,"get",{user:R,doc:h,params:g});if(!v.allowed)return v.errorResponse;if(a.rules?.filter)try{if(!await a.rules.filter({user:R,doc:h,params:g}))return x(s,"Document not found",404)}catch{return x(s,"Document not found",404)}return V(s,h)}catch(h){return await Oe(s,h,{repoName:g.repoName||a.name,ref:a.repo.ref,path:a.path,isGroup:!!a.isGroup,filters:[{field:a.documentKey,op:"==",value:w}]},"Failed to fetch document",n,r)}}async function O(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);try{let w=f.input||{},h=c(s),R=await o(s,a,"create",{user:h,body:w,params:g});if(!R.allowed)return R.errorResponse;let v=pe(a.schema,w,a.createFields,!1,a.systemKeys);if(!v.success)return x(s,v.error,400);if(a.validate){let T=await a.validate(v.data,"create");if(T)return x(s,T,400)}let l;if(a.isGroup&&a.parentKeys&&a.parentKeys.length>0){let T={...v.data},P=a.parentKeys.filter(D=>T[D]===void 0||T[D]===null||typeof T[D]=="string"&&T[D].trim()==="");if(P.length>0){x(s,`Missing parent key(s) for subcollection create: ${P.join(", ")}`,400);return}if(typeof a.repo.create=="function")l=await a.repo.create(T);else {let D=a.parentKeys.map(E=>String(T[E])),_=T[a.documentKey]||Re();l=await a.repo.set(...D,_,T);}}else l=await a.repo.create(v.data);return V(s,l,void 0,201)}catch(w){let h=n&&w instanceof Error?w.message:"Failed to create document";return x(s,h,500)}}async function N(f,s){let g=f.c,a=g.req.param(),w=u(a.repoName,g);if(!w)return x(g,"Repository not found",404);let h=a.id;if(!h)return x(g,"Document ID required",400);try{let R=f.input||{},v=await p(w,h);if(!v)return x(g,"Document not found",404);let l=pe(w.schema,R,w.mutableFields,s,w.systemKeys);if(!l.success)return x(g,l.error,400);if(w.validate){let A=await w.validate(l.data,"update");if(A)return x(g,A,400)}let T=le(v,l.data),P=c(g),D=await o(g,w,"update",{user:P,doc:v,body:l.data,diff:T,params:a});if(!D.allowed)return D.errorResponse;let _=d(v,w)??[h],E=await w.repo.update(..._,l.data);return V(g,E)}catch(R){let v=n&&R instanceof Error?R.message:"Failed to update document";return x(g,v,500)}}async function C(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);if(!a.allowDelete)return x(s,"Delete not allowed for this repository",403);let w=g.id;if(!w)return x(s,"Document ID required",400);try{let h=await p(a,w);if(!h)return x(s,"Document not found",404);let R=c(s),v=await o(s,a,"delete",{user:R,doc:h,params:g});if(!v.allowed)return v.errorResponse;let l=d(h,a)??[w];return await a.repo.delete(...l),V(s,{deleted:!0})}catch(h){let R=n&&h instanceof Error?h.message:"Failed to delete document";return x(s,R,500)}}function S(f){return f.c.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400"})}async function z(f){let s=f.c,g=s.req.param(),a=u(g.repoName,s);if(!a)return x(s,"Repository not found",404);try{let w=f.input||{};if(!Array.isArray(w.operations))return x(s,"operations array is required",400);let h=c(s),R=a.repo.batch.create(),v=[];for(let l of w.operations){if(!l.type||!["create","update","delete"].includes(l.type))return x(s,"Invalid operation type",400);if(l.type==="create"){let T=await o(s,a,"create",{user:h,body:l.data,params:g});if(!T.allowed)return T.errorResponse;let P=pe(a.schema,l.data,a.createFields,!1,a.systemKeys);if(!P.success)return x(s,P.error,400);let D=l.data[a.documentKey]||Re(),_={...P.data};if(a.createdKey&&_[a.createdKey]===void 0&&(_[a.createdKey]=new Date),a.isGroup&&a.parentKeys){let E=a.parentKeys.map(A=>_[A]);R.set(...E,D,_);}else R.set(D,_);v.push({op:"create",id:D});}else if(l.type==="update"){if(!l.id)return x(s,"id required for update",400);let T=await p(a,l.id);if(!T)return x(s,`Document ${l.id} not found`,404);let P=pe(a.schema,l.data,a.mutableFields,!0,a.systemKeys);if(!P.success)return x(s,P.error,400);if(a.validate){let A=await a.validate(P.data,"update");if(A)return x(s,A,400)}let D=le(T,P.data),_=await o(s,a,"update",{user:h,doc:T,body:P.data,diff:D,params:g});if(!_.allowed)return _.errorResponse;let E=d(T,a)??[l.id];R.update(...E,P.data),v.push({op:"update",id:l.id});}else if(l.type==="delete"){if(!a.allowDelete)return x(s,"Delete not allowed",403);if(!l.id)return x(s,"id required for delete",400);let T=await p(a,l.id);if(!T)return x(s,`Document ${l.id} not found`,404);let P=await o(s,a,"delete",{user:h,doc:T,params:g});if(!P.allowed)return P.errorResponse;let D=d(T,a)??[l.id];R.delete(...D),v.push({op:"delete",id:l.id});}}return await R.commit(),V(s,{results:v})}catch(w){let h=n&&w instanceof Error?w.message:"Batch operation failed";return x(s,h,500)}}return {handleList:m,handleQuery:y,handleGet:b,handleCreate:O,handleUpdate:N,handleDelete:C,handleBatch:z,handleOptions:S}}function te(e){try{return z.toJSONSchema(e,{target:"openapi-3.1",unrepresentable:"any",override:t=>{let n=getOpenApiMetadata(t.zodSchema);n&&(Object.assign(t.jsonSchema,n),(t.jsonSchema.anyOf||t.jsonSchema.oneOf)&&delete t.jsonSchema.type);let r=t.zodSchema?._zod?.def;r&&(r.type==="date"&&!t.jsonSchema.type&&!t.jsonSchema.anyOf?(t.jsonSchema.type="string",t.jsonSchema.format="date-time"):r.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 H(e){return {$ref:`#/components/schemas/${e}`}}function F(e){return {description:e,content:{"application/json":{schema:H("ErrorResponse")}}}}function ee(e,t){return {description:e,content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",enum:[true]},data:t},required:["success","data"]}}}}}function Vt(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 se(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 Jt(e,t){let n=t.split("."),r=se(e);for(let o=0;o<n.length;o++){let i=n[o];if(!i)continue;let c=r?.shape;if(!c||!c[i])return;let u=c[i];if(o===n.length-1)return u;r=se(u);}return r}function Y(e){let t=e?._zod?.def??e?._def,n=t?.typeName??t?.type,r=o=>{let i=getOpenApiMetadata(e);return i&&typeof o.openapi=="function"?o.openapi(i):o};if(n==="ZodObject"||n==="object"){let o=e.shape,i={};for(let[c,u]of Object.entries(o))i[c]=Y(u);return r(z.object(i).partial())}if(n==="ZodOptional"||n==="optional"){let o=t.innerType;if(!o)return e;let i=Y(o);return i===o?e:r(i.optional())}if(n==="ZodNullable"||n==="nullable"){let o=t.innerType;if(!o)return e;let i=Y(o);return i===o?e:r(i.nullable())}if(n==="ZodDefault"||n==="default"){let o=t.innerType;return o?r(Y(o).optional()):e}if(n==="ZodUnion"||n==="union"){let o=t.options;if(!o||o.length<2)return e;let i=o.map(u=>Y(u));return i.some((u,d)=>u!==o[d])?r(z.union(i)):e}return e}function Ie(e,t="",n=0){if(n>5)return [];let o=se(e)?.shape;if(!o)return [];let i=[];for(let[c,u]of Object.entries(o)){let d=t?`${t}.${c}`:c,p=se(u);p?.shape&&typeof p.shape=="object"?(i.push({path:d,zodSchema:u}),i.push(...Ie(p,d,n+1))):i.push({path:d,zodSchema:u});}return i}function Qt(e){return e.filterableFields&&e.filterableFields.length>0?e.filterableFields.map(t=>({path:t,zodSchema:Jt(e.schema,t)})):Ie(e.schema)}function tt(e){if(!e)return {type:"string"};let t=te(e);return delete t.$schema,delete t.title,t}function rt(){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",minimum:1,maximum:1e3,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 Xt(e){let t=Qt(e),n=e.orderableFields??t.map(c=>c.path),r=t.map(c=>c.path);if(t.length===0)return rt();let o=[];for(let{path:c,zodSchema:u}of t){let d=tt(u),p=se(u),y=p?._zod?.def?.type==="array"||p?._def?.typeName==="ZodArray"||p?._def?.type==="array"?tt(p?._zod?.def?.element??p?._def?.type??p?._def?.element):d;o.push({type:"array",description:`Condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["==","!=","<","<=",">",">=","eq","ne","lt","lte","gt","gte"]},d],minItems:3,maxItems:3}),o.push({type:"array",description:`List condition on '${c}' (in, not-in)`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["in","not-in","nin"]},{type:"array",items:d}],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains","contains"]},y],minItems:3,maxItems:3}),o.push({type:"array",description:`Array contains-any condition on '${c}'`,prefixItems:[{type:"string",enum:[c]},{type:"string",enum:["array-contains-any","containsAny"]},{type:"array",items:y}],minItems:3,maxItems:3});}let i={oneOf:o};return {type:"object",properties:{where:{type:"array",items:i,description:"AND conditions: [field, operator, value][]"},orWhere:{type:"array",items:i,description:"Simple OR conditions (each independently OR'd)"},orWhereGroups:{type:"array",items:{type:"array",items:i},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:r},description:"Fields to select (projection)"},pageSize:{type:"integer",minimum:1,maximum:1e3,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 Yt(e,t,n,r,o,i=null,c="QueryRequestBody"){let u={},d=e.name,p=`${t}/${e.name}`,m=`${p}/{${e.documentKey}}`,y={name:e.documentKey,in:"path",required:true,schema:{type:"string"},description:"Unique document identifier"};u[p]={post:{operationId:`create${W(e.name)}`,summary:`Create a ${K(e.name)}`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:H(r??n)}}},responses:{201:ee("Document created",H(n)),400:F("Validation error"),403:F("Forbidden"),500:F("Internal server error")}}},u[`${p}/query`]={post:{operationId:`query${W(e.name)}`,summary:`Query ${e.name} with advanced filters`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:H(c)}}},responses:{200:Vt(H(n)),400:F("Invalid query"),403:F("Forbidden"),424:F("Missing composite index (includes indexUrl in response)"),500:F("Internal server error")}}},u[`${p}/batch`]={post:{operationId:`batch${W(e.name)}`,summary:`Execute batch operations on ${e.name}`,tags:[d],requestBody:{required:true,content:{"application/json":{schema:H(`${n}BatchRequest`)}}},responses:{200:ee("Batch operations completed",{type:"object",properties:{results:{type:"array",items:{type:"object",properties:{op:{type:"string"},id:{type:"string"}}}}}}),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}}};let b={};return b.get={operationId:`get${W(K(e.name))}`,summary:`Get a single ${K(e.name)}`,tags:[d],parameters:[y],responses:{200:ee("Document found",H(n)),400:F("Document ID required"),403:F("Forbidden"),404:F("Document not found"),424:F("Missing composite index (includes indexUrl in response)"),500:F("Internal server error")}},b.put={operationId:`update${W(K(e.name))}`,summary:`Update a ${K(e.name)} (full replace)`,tags:[d],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:H(o??n)}}},responses:{200:ee("Document updated",H(n)),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}},b.patch={operationId:`patch${W(K(e.name))}`,summary:`Partially update a ${K(e.name)}`,tags:[d],parameters:[y],requestBody:{required:true,content:{"application/json":{schema:H(i??o??n)}}},responses:{200:ee("Document patched",H(n)),400:F("Validation error"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}},e.allowDelete&&(b.delete={operationId:`delete${W(K(e.name))}`,summary:`Delete a ${K(e.name)}`,tags:[d],parameters:[y],responses:{200:ee("Document deleted",{type:"object",properties:{id:{type:"string"}}}),400:F("Document ID required"),403:F("Forbidden"),404:F("Document not found"),500:F("Internal server error")}}),u[m]=b,u}function Pe(e,t,n={}){let{title:r="CRUD API",version:o="1.0.0",description:i,servers:c,auth:u=false}=n,d=t==="/"?"":t.replace(/\/$/,""),p={},m={},y=[];p.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"]},p.QueryRequestBody=rt();for(let[C,S]of Object.entries(e)){let z$1=W(K(C)),f=`${z$1}Create`,s=`${z$1}Update`,g=`${z$1}Patch`,a=`${z$1}QueryRequestBody`;p[z$1]=te(S.schema),p[a]=Xt(S);let w=A=>{let $={},L=Ie(S.schema);for(let{path:I,zodSchema:k}of L){let j=I.split(".")[0];S.systemKeys.includes(j)||S.systemKeys.includes(I)||A&&A.length>0&&!A.includes(I)&&!A.includes(j)||(I.includes(".")?$[I]=k.optional():$[I]=k);}return $},h=null,R=w(S.createFields);if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let A=S.schema?.shape??{};for(let $ of S.parentKeys)!R[$]&&A[$]&&(R[$]=A[$]);}if(Object.keys(R).length>0){let A=te(z.object(R));if(S.isGroup&&S.parentKeys&&S.parentKeys.length>0){let $=new Set(Array.isArray(A.required)?A.required:[]);for(let L of S.parentKeys)A.properties?.[L]&&$.add(L);$.size>0&&(A.required=Array.from($));}p[f]=A,h=f;}let v=null,l=null,T=w(S.mutableFields);if(Object.keys(T).length>0){let A=z.object(T);p[s]=te(A),v=s,p[g]=te(Y(A)),l=g;}else p[g]=te(Y(S.schema)),l=g;let P=`${z$1}BatchCreateOperation`,D=`${z$1}BatchUpdateOperation`,_=`${z$1}BatchDeleteOperation`;p[P]={type:"object",title:`${z$1} Create Operation`,properties:{type:{type:"string",enum:["create"],const:"create"},data:H(h??z$1)},required:["type","data"]},p[D]={type:"object",title:`${z$1} Update Operation`,properties:{type:{type:"string",enum:["update"],const:"update"},id:{type:"string"},data:H(l??v??z$1)},required:["type","id","data"]},S.allowDelete&&(p[_]={type:"object",title:`${z$1} Delete Operation`,properties:{type:{type:"string",enum:["delete"],const:"delete"},id:{type:"string"}},required:["type","id"]}),p[`${z$1}BatchRequest`]={type:"object",properties:{operations:{type:"array",items:{oneOf:[H(P),H(D),...S.allowDelete?[H(_)]:[]],discriminator:{propertyName:"type"}}}},required:["operations"]};let E=Yt(S,d,z$1,h,v,l,a);Object.assign(m,E),y.push({name:C,description:`Operations on ${C} (collection: ${S.path})`});}let b={},O;return u==="basic"?(b.basicAuth={type:"http",scheme:"basic"},O=[{basicAuth:[]}]):u==="bearer"&&(b.bearerAuth={type:"http",scheme:"bearer",bearerFormat:"JWT"},O=[{bearerAuth:[]}]),{openapi:"3.1.0",info:{title:r,version:o,...i?{description:i}:{}},...c&&c.length>0?{servers:c}:{},paths:m,components:{schemas:p,...Object.keys(b).length>0?{securitySchemes:b}:{}},...O?{security:O}:{},tags:y}}function W(e){return e.charAt(0).toUpperCase()+e.slice(1)}function K(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 ne=class extends Error{constructor(n,r){super("Request validation failed");this.zodError=n;this.source=r;this.statusCode=400;this.name="ValidationError";}};var ie=class extends Error{constructor(n){super(n);this.statusCode=400;this.name="BadRequestError";}},ae=class extends Error{constructor(n){super("Output validation failed");this.zodError=n;this.statusCode=500;this.name="OutputValidationError";}};function ot(e){return e.issues.map(t=>({path:t.path.join("."),code:t.code,message:t.message}))}function st(e,t){return t instanceof ne?e.json({success:false,error:"Validation failed",issues:ot(t.zodError)},400):t instanceof ie?e.json({success:false,error:"Bad Request",message:t.message},400):t instanceof ae?e.json({success:false,error:"Output validation failed",issues:ot(t.zodError)},500):null}extendZodWithOpenApi(z);var it="Successful response",at="Error response";function B(e,t=new Set){if(!e||typeof e!="object"||t.has(e))return;t.add(e);let n=e,r=n._zod?.def??n.def;if(!r)return;if(r.type==="custom"){let i=getOpenApiMetadata(n);i?.type||z.globalRegistry.add(n,{...i??{},type:"object"});return}if(r.innerType&&B(r.innerType,t),r.element&&B(r.element,t),r.valueType&&B(r.valueType,t),r.keyType&&B(r.keyType,t),r.left&&B(r.left,t),r.right&&B(r.right,t),r.in&&B(r.in,t),r.out&&B(r.out,t),typeof r.getter=="function")try{B(r.getter(),t);}catch{}if(Array.isArray(r.options))for(let i of r.options)B(i,t);if(Array.isArray(r.items))for(let i of r.items)B(i,t);let o=typeof r.shape=="function"?r.shape():r.shape;if(o&&typeof o=="object")for(let i of Object.values(o))B(i,t);}function De(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let n of e)De(n);return}let t=e;(Array.isArray(t.anyOf)||Array.isArray(t.oneOf))&&"type"in t&&delete t.type;for(let n of Object.values(t))De(n);}function on(e){return e==="get"?"query":"json"}function sn(e,t){let n=t?.output;return n?typeof n=="function"?n(e):n:e}function an(e){if(typeof e.safeParse=="function")return {description:at,schema:e};let t=e;return {description:t.description??at,schema:t.schema}}function dt(e,t,n,r){let o=new OpenAPIRegistry;if(n.securitySchemes)for(let[u,d]of Object.entries(n.securitySchemes))o.registerComponent("securitySchemes",u,d);for(let u of e){let d=u.method,p=u.source??on(d),m=dn(t,u.path??"/"),y=u.status??200;u.input&&B(u.input);let b=cn(d,p,u.input),O=ct(p,u.input,"query"),N=ct(p,u.input,"param"),C=ln(d,m),S=sn(u.output,r);S&&B(S);let z={[y]:S?{description:it,content:{"application/json":{schema:S}}}:{description:it}};if(r?.errors)for(let[f,s]of Object.entries(r.errors)){let{description:g,schema:a}=an(s);a&&B(a),z[f]=a?{description:g,content:{"application/json":{schema:a}}}:{description:g};}o.registerPath({method:d,path:un(m),operationId:C,summary:u.summary,description:u.description,tags:u.tags,deprecated:u.deprecated,security:u.security,request:{...O?{query:O}:{},...N?{params:N}:{},...b?{body:b}:{}},responses:z});}let c=new OpenApiGeneratorV31(o.definitions).generateDocument({openapi:"3.1.0",info:n.info,servers:n.servers,security:n.security});return De(c),c}function cn(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 ct(e,t,n){if(t&&(n==="query"&&e==="query"||n==="param"&&e==="param"))return t}function un(e){return e.replace(/:([A-Za-z0-9_]+)/g,"{$1}")}function dn(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function ln(e,t){let n=t.replace(/[{}]/g,"").replace(/\/+/g,"_").replace(/[^A-Za-z0-9_]/g,"").replace(/^_+|_+$/g,"");return `${e}_${n||"root"}`}function lt(e,t){let n=e.replace(/"/g,""");return `<!doctype html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8" />
|
|
@@ -9,5 +9,5 @@ import {z}from'zod';import {Timestamp}from'firebase-admin/firestore';import {ran
|
|
|
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 pt(e){return typeof e=="object"&&e!==null&&e.__docsAuthExtension===true}var je=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),ze=globalThis,fn=ze[je]??(ze[je]=new AsyncLocalStorage);function yn(e,t){if(!t.includes("."))return e[t];let n=e;for(let r of t.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function ft(e,t){for(let n of t){let r=yn(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function yt(e,t){if(t===false)return;let n=e?.req?.header;if(typeof n!="function")return;let r=n.call(e.req,t);return typeof r=="string"&&r.length>0?r:void 0}function mt(e={}){let t=e.contextKeys??["user","docsUser"],n=e.userIdFields??["uid","id","sub"],r=e.userEmailFields??["email"],o=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,i=e.commentHeader===void 0?"x-history-comment":e.commentHeader,c=e.extras;return u=>{let d=null,p=u?.get;if(typeof p=="function")for(let O of t){let N=p.call(u,O);if(N&&typeof N=="object"){d=N;break}}let m=yt(u,o),y=yt(u,i),b=c?c(u,d):void 0;return d?{userId:ft(d,n),userEmail:ft(d,r),...m!==void 0?{reason:m}:{},...y!==void 0?{comment:y}:{},...b?{extras:b}:{}}:m===void 0&&y===void 0&&!b?null:{...m!==void 0?{reason:m}:{},...y!==void 0?{comment:y}:{},...b?{extras:b}:{}}}}mt();function mn(e){if(e)return typeof e=="function"?e:mt(e)}function gt(e){let t=mn(e);return async(n,r)=>{await fn.run({c:n,resolver:t},async()=>{await r();});}}var _e=new AsyncLocalStorage;function ht(){return async(e,t)=>{await _e.run({c:e},async()=>{await t();});}}var bn=Object.freeze({}),ge=class{constructor(t){this.cachedSpec=null;this.options=t,this.app=new Hono,this.mountedRoutes=Sn(t.routes,t.api),this.app.use("*",gt(t.actorResolver)),t.services&&this.app.use("*",ht());let n=[...t.middlewares??[],...t.globalMiddlewares??[]];for(let r of n)this.app.use("*",r);this.mountRoutes(),this.mountOpenApi(),t.notFound&&this.app.notFound(t.notFound),t.onError&&this.app.onError(t.onError);}get hono(){return this.app}get nodeHandler(){return getRequestListener(this.app.fetch,{overrideGlobalObjects:false})}toFunction(t,n){let r=this.nodeHandler;return n?t(n,r):t(r)}buildOpenApiSpec(){if(this.cachedSpec)return this.cachedSpec;if(!this.options.openapi)throw new Error("[HonoServer] openapi config not set");return this.cachedSpec=dt(this.mountedRoutes,this.options.basePath??"",this.options.openapi,Rn(this.options.interceptor)),this.cachedSpec}mountRoutes(){let t=this.options.basePath??"",n=this.options.validateOutput??false,r=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 i=me(t,o.path),c=o.middlewares??[],u=o.source??(o.method==="get"?"query":"json"),d=vn(o,u,n,xn(this.options.interceptor),this.options.services,this.options.errorHandler,this.options.logger),p=o.method.toUpperCase();this.app.on(p,[i],...c,d),r&&console.log(`[HonoServer] ${o.method.toUpperCase().padEnd(6)} ${i}`);}}mountOpenApi(){let t=this.options.openapi;if(!t)return;let n=t.path??"/openapi.json",r=t.docsPath===void 0?"/docs":t.docsPath,o=me(this.options.basePath??"",n),i=r===false?null:me(this.options.basePath??"",r),c;if(pt(t.docsAuth)){let u=t.docsAuth;c=[u.middleware];let d=An(i??o);for(let p of u.routes)this.app.on(p.method,[me(d,p.name)],p.handler);}else c=t.docsAuth?Array.isArray(t.docsAuth)?t.docsAuth:[t.docsAuth]:[];if(this.app.on("GET",[o],...c,u=>u.json(this.buildOpenApiSpec())),i){let u=Tn(i,o);this.app.on("GET",[i],...c,d=>d.html(lt(u,t.info.title)));}}};function wt(e){return typeof e=="object"&&e!==null&&typeof e.handler=="function"}function xn(e){if(e)return wt(e)?e.handler:e}function Rn(e){return wt(e)?e:void 0}function Sn(e,t){return t?e.filter(n=>Array.isArray(n.api)?n.api.includes(t):n.api===t):e.slice()}function me(e,t){let n=e.endsWith("/")?e.slice(0,-1):e,r=t.startsWith("/")?t:`/${t}`,o=`${n}${r}`;return o===""?"/":o}function An(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function Tn(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean);n.pop();let o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let i=n.length-o;return [...Array(i).fill(".."),...r.slice(o)].join("/")||"./"}function vn(e,t,n,r,o,i,c){let u=e.input,d=e.output,p=e.status??200,m=o??bn;return async y=>{let b=async C=>{if(i){let S=await i.handle({error:C,c:y,route:e,services:m,logger:c});if(S)return S}return st(y,C)},O=async()=>{let C,S;try{S=await kn(y,t,e.method);}catch(f){throw new ie(f instanceof Error?f.message:String(f))}if(u){let f=u.safeParse(S);if(!f.success)throw new ne(f.error,t);C=f.data;}else C=S;let z=await e.handler({input:C,c:y,services:m,errorHandler:i,logger:c});if(n&&d&&!(z instanceof Response)){let f=d.safeParse(z);if(!f.success)throw new ae(f.error);return f.data}return z},N;if(r)try{N=await r({next:O,route:e,c:y,services:m,errorHandler:i,logger:c});}catch(C){let S=await b(C);if(S)return S;throw C}else try{N=await O();}catch(C){let S=await b(C);if(S)return S;throw C}return N instanceof Response?N:y.json(N,p)}}async function kn(e,t,n){switch(t){case "json":{if(n==="get")return e.req.query();let r=await e.req.text();if(!r)return {};try{return JSON.parse(r)}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 Cr(e){let{basePath:t="/",repos:n,parseBody:r=true,securityHeaders:o,verbose:i=false,httpsOptions:c}=e,u=t==="/"?"":t.replace(/\/$/,""),d={};for(let[f,s]of Object.entries(n)){if(!s.repo)throw new Error(`[createCrudServer] Repository "${f}" has no 'repo' defined. Did you forget to pass it or is there a circular import?`);let g=s.schema??s.repo.schema??null;if(!g)throw new Error(`[createCrudServer] Repository "${f}" has no Zod schema.`);let a,w,h,R;if(s.fieldsConfig){let _=s.fieldsConfig;a=[],w=[],h=[],R=[];for(let[E,A]of Object.entries(_))for(let $ of A)$==="filterable"?a.push(E):$==="orderable"?w.push(E):$==="mutable"?h.push(E):$==="create"&&R.push(E);w.length===0&&(w=a),a.length===0&&(a=void 0),w&&w.length===0&&(w=void 0),h.length===0&&(h=void 0),R.length===0&&(R=void 0);}let v=(()=>{let _=s.repo._parentKeys;return _&&_.length>0?_:void 0})();if(v&&R)for(let _ of v)R.includes(_)||R.push(_);let l=s.repo._systemKeys??[s.documentKey??"docId"],T=s.repo._historyIdentityKeys??[],P=Array.from(new Set([...l,...T])),D={name:f,path:s.path,repo:s.repo,schema:g,systemKeys:P,documentKey:s.documentKey??"docId",pathKey:s.repo._pathKey??void 0,isGroup:!!s.repo._isGroup,parentKeys:v,documentPathTemplate:s.repo._documentPathTemplate??void 0,createdKey:s.repo._createdKey??void 0,pageSize:s.pageSize??25,filterableFields:a,orderableFields:w,mutableFields:h,createFields:R,allowDelete:s.allowDelete??false,allowedIncludes:s.allowedIncludes,validate:s.validate,rules:s.rules};d[f]=D;}let p=e.indexesError??e.onIndexError,m=et(d,u,i,p),y=e.openapi,b=y&&typeof y=="object"?y:{},O=null;function N(){return O||(O=Pe(d,u,{...b,auth:b.auth??false})),O}let C=[];for(let f of Object.keys(d))C.push({api:"crud",method:"post",path:`/${f}/query`,source:"json",handler:m.handleQuery}),C.push({api:"crud",method:"get",path:`/${f}/:id`,source:"query",handler:m.handleGet}),C.push({api:"crud",method:"post",path:`/${f}`,source:"json",handler:m.handleCreate}),C.push({api:"crud",method:"put",path:`/${f}/:id`,source:"json",handler:s=>m.handleUpdate(s,false)}),C.push({api:"crud",method:"patch",path:`/${f}/:id`,source:"json",handler:s=>m.handleUpdate(s,true)}),C.push({api:"crud",method:"delete",path:`/${f}/:id`,source:"query",handler:m.handleDelete}),C.push({api:"crud",method:"post",path:`/${f}/batch`,source:"json",handler:m.handleBatch});let S=new ge({...e,openapi:y!==false?{path:b.path??"/openapi.json",docsPath:b.docsPath??"/docs",info:{title:b.title??"CRUD API",version:b.version??"1.0.0"},docsAuth:b.docsAuth}:void 0,basePath:t,api:"crud",routes:C,middlewares:[async(f,s)=>{if(f.req.method==="OPTIONS")return f.text("",204,{"Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization, X-History-Reason, X-History-Comment","Access-Control-Max-Age":"86400","Access-Control-Allow-Origin":"*","Access-Control-Allow-Credentials":"true"});f.header("Access-Control-Allow-Origin","*"),f.header("Access-Control-Allow-Credentials","true"),await s();},...e.middlewares||[]]});if(y!==false&&(S.buildOpenApiSpec=N),o!==false){let{securityHeaders:f}=(At(),Pt(St)),s=o===void 0?{csp:false}:o;S.hono.use("*",async(g,a)=>{let w=f(s);await new Promise(h=>{let R=g.req.raw;w(R,{setHeader:(l,T)=>g.header(l,T),removeHeader:l=>g.res.headers.delete(l)},()=>h());}),await a();});}let z=S.nodeHandler;return z.spec=N,c&&(z.httpsOptions=c),z}export{We as applyRules,le as computeDeepDiff,Kt as createBeforeRules,Cr as createCrudServer,Ut as createRules,Pe as generateOpenAPISpec};//# sourceMappingURL=index.js.map
|
|
13
13
|
//# sourceMappingURL=index.js.map
|