@lpdjs/firestore-repo-service 2.6.47 → 2.6.49

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.
Files changed (34) hide show
  1. package/README.md +4 -1
  2. package/dist/{create-servers-BjhepKI6.d.ts → create-servers-CwNxQQQ1.d.ts} +3 -3
  3. package/dist/{create-servers-DSLJF9cm.d.cts → create-servers-rVXsgSQE.d.cts} +3 -3
  4. package/dist/{index-BwN1OK3P.d.cts → index-CsuESJ5D.d.cts} +1 -1
  5. package/dist/{index-Df6FAq2n.d.ts → index-D0clYX8B.d.ts} +1 -1
  6. package/dist/index.cjs +82 -82
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +16 -6
  9. package/dist/index.d.ts +16 -6
  10. package/dist/index.js +82 -82
  11. package/dist/index.js.map +1 -1
  12. package/dist/llms-full.txt +178 -9
  13. package/dist/llms.txt +2 -1
  14. package/dist/{openapi-CC8PXZ3R.d.cts → openapi-BEBoB0y3.d.cts} +1 -1
  15. package/dist/{openapi-DuBKOatd.d.ts → openapi-ltqn60oy.d.ts} +1 -1
  16. package/dist/servers/admin/index.d.cts +2 -2
  17. package/dist/servers/admin/index.d.ts +2 -2
  18. package/dist/servers/crud/index.cjs +2 -2
  19. package/dist/servers/crud/index.cjs.map +1 -1
  20. package/dist/servers/crud/index.d.cts +4 -4
  21. package/dist/servers/crud/index.d.ts +4 -4
  22. package/dist/servers/crud/index.js +2 -2
  23. package/dist/servers/crud/index.js.map +1 -1
  24. package/dist/servers/index.cjs +55 -55
  25. package/dist/servers/index.cjs.map +1 -1
  26. package/dist/servers/index.d.cts +5 -5
  27. package/dist/servers/index.d.ts +5 -5
  28. package/dist/servers/index.js +55 -55
  29. package/dist/servers/index.js.map +1 -1
  30. package/dist/sync/index.cjs +3 -3
  31. package/dist/sync/index.js +3 -3
  32. package/dist/{types-BEel_BJZ.d.ts → types-DG5Ys5AM.d.ts} +16 -0
  33. package/dist/{types-BQKFWe40.d.cts → types-DQwhnE4-.d.cts} +16 -0
  34. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- 'use strict';require('firebase-admin/firestore'),require('crypto');function ue(t){let e=[],n=t.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,i)=>(e.push(i),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:e}}function le(t){let e=t.path??t.url??"/",n=e.indexOf("?");return n===-1?e:e.slice(0,n)}var L=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(e,n)=>{n.status(404).send("Not Found");};this.errorHandler=(e,n,r)=>{console.error("[MiniRouter]",e),r.status(500).send("Internal Server Error");};}use(e){return this.middlewares.push(e),this}get(e,n){return this.addRoute("GET",e,n)}post(e,n){return this.addRoute("POST",e,n)}put(e,n){return this.addRoute("PUT",e,n)}patch(e,n){return this.addRoute("PATCH",e,n)}delete(e,n){return this.addRoute("DELETE",e,n)}onNotFound(e){return this.notFoundHandler=e,this}onError(e){return this.errorHandler=e,this}addRoute(e,n,r){let{pattern:i,paramNames:u}=ue(n);return this.routes.push({method:e.toUpperCase(),pattern:i,paramNames:u,handler:r}),this}async handle(e,n){let r=(e.method??"GET").toUpperCase(),i=le(e),u=null,a={};for(let T of this.routes){if(T.method!==r)continue;let k=i.match(T.pattern);if(k){u=T,a={},T.paramNames.forEach((w,A)=>{a[w]=decodeURIComponent(k[A+1]??"");});break}}let b=Object.assign(e,{params:a}),f=u?u.handler:this.notFoundHandler;try{await this.runMiddlewareChain(b,n,f);}catch(T){this.errorHandler(T,e,n);}}async runMiddlewareChain(e,n,r){let i=0,u=async()=>{if(i<this.middlewares.length){let a=this.middlewares[i++];await a(e,n,u);}else await r(e,n);};await u();}};function I(t,e,n){let r=e==="/"?"":e.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",b=process.env.FUNCTION_REGION??"us-central1",f=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${b}/${f}${r}`}let i=process.env.K_SERVICE,u=t?.hostname??t?.headers?.host??"";return i&&typeof u=="string"&&u.includes("cloudfunctions.net")?`/${i.toLowerCase()}${r}`:r}function K(t){return !!t&&typeof t=="object"&&t.__authExtension===true}function ye(t){if(typeof t!="function")return [];let n=t.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(i=>i.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function me(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(r=>typeof r=="string"),n=t?.history&&typeof t.history=="object"?t.history:void 0;return {schema:t?.schema,_systemKeys:e,_pathKey:t?.pathKey??null,_isGroup:!!t?.isGroup,_createdKey:t?.createdKey??null,_parentKeys:t?.isGroup?ye(t?.refCb):[],relationalKeys:t?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof t?.path=="string"?t.path:null}}function Y(t,e){let n=me(t),r,i=()=>{let u=r??(r=e());if(!u){let a=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${a}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return u};return new Proxy(n,{get(u,a){return typeof a=="string"&&a in n?n[a]:i()[a]},has(u,a){return typeof a=="string"&&a in n?true:a in i()}})}var ge={string:"ZodString",number:"ZodNumber",bigint:"ZodBigInt",boolean:"ZodBoolean",date:"ZodDate",enum:"ZodEnum",nativeEnum:"ZodNativeEnum",literal:"ZodLiteral",object:"ZodObject",array:"ZodArray",optional:"ZodOptional",nullable:"ZodNullable",default:"ZodDefault",coerce:"ZodCoerce",union:"ZodUnion",undefined:"ZodUndefined",unknown:"ZodUnknown",any:"ZodAny",record:"ZodRecord"};function Q(t){let e=t,n=e._zod?.def?.type;if(n)return ge[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=e._def?.typeName;return r||""}function X(t){let e=t;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function W(t){let e=t;return e.shape&&typeof e.shape=="object"?e.shape:e._zod?.def?.shape&&typeof e._zod.def.shape=="object"?e._zod.def.shape:e._def?.shape?typeof e._def.shape=="function"?e._def.shape():e._def.shape:{}}var H="__sync_version";var he=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function ee(t){let e=t,n=false;for(;;){let r=Q(e);if(!he.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let i=X(e);if(!i)break;e=i;}return {inner:e,nullable:n}}var te={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function be(t){let{inner:e}=ee(t);return te[Q(e)]??"json"}function ne(t,e,n,r,i,u,a,b){for(let[f,T]of Object.entries(t)){let k=n?`${n}__${f}`:f;if(i.has(f)||i.has(k))continue;let{inner:w,nullable:A}=ee(T),s=Q(w),l=r||A;if(s==="ZodObject"){let S=W(w);ne(S,e,k,l,i,u,a,b);continue}let c=te[s]??"json",o=k===a||f===a,p=u[k]??u[f]??k;b.push({name:p,sqlType:e.mapType(c),nullable:o?false:l,isPrimaryKey:o});}}function $(t,e,n={}){let{primaryKey:r,exclude:i=[],columnMap:u={}}=n,a=new Set(i),b=W(t),f=[];return ne(b,e,"",false,a,u,r,f),f.some(T=>T.name===H)||f.push({name:H,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),f}function q(t){if(t==null)return null;if(typeof t=="object"&&typeof t.toDate=="function")return t.toDate().toISOString();if(t instanceof Date)return t.toISOString();if(Buffer.isBuffer(t))return t.toString("base64");if(t instanceof Uint8Array)return Buffer.from(t).toString("base64");if(typeof t=="object"&&"latitude"in t&&"longitude"in t){let e=t;return JSON.stringify({lat:e.latitude,lng:e.longitude})}return Array.isArray(t)?JSON.stringify(t.map(q)):t}var we=32,Te=5e3;function re(t,e,n,r=new WeakSet,i=0){if(i>we){n[e||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(t)){n[e||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(t);for(let[u,a]of Object.entries(t)){if(Object.keys(n).length>=Te)break;let b=e?`${e}__${u}`:u;a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!Buffer.isBuffer(a)&&!(a instanceof Uint8Array)&&typeof a.toDate!="function"&&!("latitude"in a&&"longitude"in a)?re(a,b,n,r,i+1):n[b]=q(a);}r.delete(t);}function N(t,e){let n=new Set(e?.exclude),r=e?.columnMap??{},i={};re(t,"",i);let u={};for(let[a,b]of Object.entries(i)){if(n.has(a))continue;let f=a.split("__")[0];if(f!==a&&n.has(f))continue;let T=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;u[T]=b;}return u}function _(t,e,n){return `<!DOCTYPE html>
1
+ 'use strict';require('firebase-admin/firestore'),require('crypto');function ue(t){let e=[],n=t.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,i)=>(e.push(i),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:e}}function le(t){let e=t.path??t.url??"/",n=e.indexOf("?");return n===-1?e:e.slice(0,n)}var L=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(e,n)=>{n.status(404).send("Not Found");};this.errorHandler=(e,n,r)=>{console.error("[MiniRouter]",e),r.status(500).send("Internal Server Error");};}use(e){return this.middlewares.push(e),this}get(e,n){return this.addRoute("GET",e,n)}post(e,n){return this.addRoute("POST",e,n)}put(e,n){return this.addRoute("PUT",e,n)}patch(e,n){return this.addRoute("PATCH",e,n)}delete(e,n){return this.addRoute("DELETE",e,n)}onNotFound(e){return this.notFoundHandler=e,this}onError(e){return this.errorHandler=e,this}addRoute(e,n,r){let{pattern:i,paramNames:u}=ue(n);return this.routes.push({method:e.toUpperCase(),pattern:i,paramNames:u,handler:r}),this}async handle(e,n){let r=(e.method??"GET").toUpperCase(),i=le(e),u=null,a={};for(let T of this.routes){if(T.method!==r)continue;let k=i.match(T.pattern);if(k){u=T,a={},T.paramNames.forEach((w,A)=>{a[w]=decodeURIComponent(k[A+1]??"");});break}}let b=Object.assign(e,{params:a}),f=u?u.handler:this.notFoundHandler;try{await this.runMiddlewareChain(b,n,f);}catch(T){this.errorHandler(T,e,n);}}async runMiddlewareChain(e,n,r){let i=0,u=async()=>{if(i<this.middlewares.length){let a=this.middlewares[i++];await a(e,n,u);}else await r(e,n);};await u();}};function I(t,e,n){let r=e==="/"?"":e.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",b=process.env.FUNCTION_REGION??"us-central1",f=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${b}/${f}${r}`}let i=process.env.K_SERVICE,u=t?.hostname??t?.headers?.host??"";return i&&typeof u=="string"&&u.includes("cloudfunctions.net")?`/${i.toLowerCase()}${r}`:r}function W(t){return !!t&&typeof t=="object"&&t.__authExtension===true}function ye(t){if(typeof t!="function")return [];let n=t.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(i=>i.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function me(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(r=>typeof r=="string"),n=t?.history&&typeof t.history=="object"?t.history:void 0;return {schema:t?.schema,_systemKeys:e,_pathKey:t?.pathKey??null,_isGroup:!!t?.isGroup,_createdKey:t?.createdKey??null,_parentKeys:t?.isGroup?ye(t?.refCb):[],relationalKeys:t?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof t?.path=="string"?t.path:null}}function Y(t,e){let n=me(t),r,i=()=>{let u=r??(r=e());if(!u){let a=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${a}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return u};return new Proxy(n,{get(u,a){return typeof a=="string"&&a in n?n[a]:i()[a]},has(u,a){return typeof a=="string"&&a in n?true:a in i()}})}var ge={string:"ZodString",number:"ZodNumber",bigint:"ZodBigInt",boolean:"ZodBoolean",date:"ZodDate",enum:"ZodEnum",nativeEnum:"ZodNativeEnum",literal:"ZodLiteral",object:"ZodObject",array:"ZodArray",optional:"ZodOptional",nullable:"ZodNullable",default:"ZodDefault",coerce:"ZodCoerce",union:"ZodUnion",undefined:"ZodUndefined",unknown:"ZodUnknown",any:"ZodAny",record:"ZodRecord"};function Q(t){let e=t,n=e._zod?.def?.type;if(n)return ge[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=e._def?.typeName;return r||""}function X(t){let e=t;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function K(t){let e=t;return e.shape&&typeof e.shape=="object"?e.shape:e._zod?.def?.shape&&typeof e._zod.def.shape=="object"?e._zod.def.shape:e._def?.shape?typeof e._def.shape=="function"?e._def.shape():e._def.shape:{}}var H="__sync_version";var he=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function ee(t){let e=t,n=false;for(;;){let r=Q(e);if(!he.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let i=X(e);if(!i)break;e=i;}return {inner:e,nullable:n}}var te={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function be(t){let{inner:e}=ee(t);return te[Q(e)]??"json"}function ne(t,e,n,r,i,u,a,b){for(let[f,T]of Object.entries(t)){let k=n?`${n}__${f}`:f;if(i.has(f)||i.has(k))continue;let{inner:w,nullable:A}=ee(T),s=Q(w),l=r||A;if(s==="ZodObject"){let S=K(w);ne(S,e,k,l,i,u,a,b);continue}let c=te[s]??"json",o=k===a||f===a,p=u[k]??u[f]??k;b.push({name:p,sqlType:e.mapType(c),nullable:o?false:l,isPrimaryKey:o});}}function $(t,e,n={}){let{primaryKey:r,exclude:i=[],columnMap:u={}}=n,a=new Set(i),b=K(t),f=[];return ne(b,e,"",false,a,u,r,f),f.some(T=>T.name===H)||f.push({name:H,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),f}function q(t){if(t==null)return null;if(typeof t=="object"&&typeof t.toDate=="function")return t.toDate().toISOString();if(t instanceof Date)return t.toISOString();if(Buffer.isBuffer(t))return t.toString("base64");if(t instanceof Uint8Array)return Buffer.from(t).toString("base64");if(typeof t=="object"&&"latitude"in t&&"longitude"in t){let e=t;return JSON.stringify({lat:e.latitude,lng:e.longitude})}return Array.isArray(t)?JSON.stringify(t.map(q)):t}var we=32,Te=5e3;function re(t,e,n,r=new WeakSet,i=0){if(i>we){n[e||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(t)){n[e||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(t);for(let[u,a]of Object.entries(t)){if(Object.keys(n).length>=Te)break;let b=e?`${e}__${u}`:u;a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!Buffer.isBuffer(a)&&!(a instanceof Uint8Array)&&typeof a.toDate!="function"&&!("latitude"in a&&"longitude"in a)?re(a,b,n,r,i+1):n[b]=q(a);}r.delete(t);}function N(t,e){let n=new Set(e?.exclude),r=e?.columnMap??{},i={};re(t,"",i);let u={};for(let[a,b]of Object.entries(i)){if(n.has(a))continue;let f=a.split("__")[0];if(f!==a&&n.has(f))continue;let T=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;u[T]=b;}return u}function _(t,e,n){return `<!DOCTYPE html>
2
2
  <html lang="en"><head>
3
3
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4
4
  <title>${t} \u2014 Sync Admin</title>
@@ -28,7 +28,7 @@
28
28
  <nav><a href="${e}/">\u2190 Dashboard</a></nav>
29
29
  <h1>${t}</h1>
30
30
  ${n}
31
- </body></html>`}function M(t,e,n=200){t.status(n).set("Content-Type","text/html; charset=utf-8").send(e);}function j(t,e,n=200){t.status(n).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function Z(t){return (t.headers?.accept??"").includes("application/json")}function Se(t,e,n,r,i,u,a,b){let f=(i.basePath??"/").replace(/\/$/,"")||"",T=i.featuresFlag??{},k=t?.rawMapping,w=[];for(let s of Object.keys(t)){let l=u[s],c=k?Y(k[s],()=>t[s]):t[s];w.push({name:s,schema:c.schema??null,documentKey:c._systemKeys?.[0]??c.documentKey??"docId",tableName:l?.tableName??s,isGroup:!!c._isGroup,repoCfg:l,repo:c});}let A=new L;if(i.auth)if(K(i.auth)){let s=i.auth;for(let l of s.routes){let c=`${f}${l.path}`;l.method==="GET"?A.get(c,l.handler):A.post(c,l.handler);}A.use(s.middleware);}else if(typeof i.auth=="function")A.use(i.auth);else {let s=i.auth.realm??"Sync Admin",l="Basic "+Buffer.from(`${i.auth.username}:${i.auth.password}`).toString("base64");A.use((c,o,p)=>{if((c.headers?.authorization??"")!==l){o.status(401).set("WWW-Authenticate",`Basic realm="${s}"`).set("Content-Type","text/plain").send("Unauthorized");return}p();});}return A.get(`${f}/`,(s,l)=>{let c=I(s,f),o=w.map(d=>{let h=[];return T.healthCheck&&h.push(`<a class="btn" href="${c}/${d.name}/health">Health</a>`),T.manualSync&&h.push(`<a class="btn btn-primary" href="${c}/${d.name}/force-sync">Force Sync</a>`),`<tr>
31
+ </body></html>`}function M(t,e,n=200){t.status(n).set("Content-Type","text/html; charset=utf-8").send(e);}function j(t,e,n=200){t.status(n).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function Z(t){return (t.headers?.accept??"").includes("application/json")}function Se(t,e,n,r,i,u,a,b){let f=(i.basePath??"/").replace(/\/$/,"")||"",T=i.featuresFlag??{},k=t?.rawMapping,w=[];for(let s of Object.keys(t)){let l=u[s],c=k?Y(k[s],()=>t[s]):t[s];w.push({name:s,schema:c.schema??null,documentKey:c._systemKeys?.[0]??c.documentKey??"docId",tableName:l?.tableName??s,isGroup:!!c._isGroup,repoCfg:l,repo:c});}let A=new L;if(i.auth)if(W(i.auth)){let s=i.auth;for(let l of s.routes){let c=`${f}${l.path}`;l.method==="GET"?A.get(c,l.handler):A.post(c,l.handler);}A.use(s.middleware);}else if(typeof i.auth=="function")A.use(i.auth);else {let s=i.auth.realm??"Sync Admin",l="Basic "+Buffer.from(`${i.auth.username}:${i.auth.password}`).toString("base64");A.use((c,o,p)=>{if((c.headers?.authorization??"")!==l){o.status(401).set("WWW-Authenticate",`Basic realm="${s}"`).set("Content-Type","text/plain").send("Unauthorized");return}p();});}return A.get(`${f}/`,(s,l)=>{let c=I(s,f),o=w.map(d=>{let h=[];return T.healthCheck&&h.push(`<a class="btn" href="${c}/${d.name}/health">Health</a>`),T.manualSync&&h.push(`<a class="btn btn-primary" href="${c}/${d.name}/force-sync">Force Sync</a>`),`<tr>
32
32
  <td><strong>${d.name}</strong></td>
33
33
  <td>${d.tableName}</td>
34
34
  <td>${d.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
@@ -87,5 +87,5 @@ ${n}
87
87
  );`}function ke(t,e,n){return n.map(r=>`ALTER TABLE ${t.quoteIdentifier(e)} ADD COLUMN ${t.quoteIdentifier(r.name)} ${r.sqlType};`).join(`
88
88
  `)}function xe(t,e,n){let r=[];for(let[i,u]of Object.entries(t)){let a=u.schema??u._schema??void 0;if(!a)continue;let b=n?.repos?.[i],f=b?.tableName??i,T=u._systemKeys?.[0]??u.documentKey??"docId",k=$(a,e,{primaryKey:T,exclude:b?.exclude,columnMap:b?.columnMap}),w={tableName:f,columns:k};r.push(oe(e,w));}return r.join(`
89
89
 
90
- `)}async function Re(t,e,n){let r={created:[],altered:[],upToDate:[],skipped:[]};for(let[i,u]of Object.entries(t)){let a=u.schema??void 0;if(!a){r.skipped.push(i);continue}let b=n?.repos?.[i],f=b?.tableName??i,T=u._systemKeys?.[0]??u.documentKey??"docId",k=$(a,e.dialect,{primaryKey:T,exclude:b?.exclude,columnMap:b?.columnMap}),w={tableName:f,columns:k};if(!await e.tableExists(f))await e.createTable(w),r.created.push(f);else {let s=new Set(await e.getTableColumns(f)),l=k.filter(c=>!s.has(c.name));l.length>0?(await e.addColumns(f,l),r.altered.push(f)):r.upToDate.push(f);}}return r}var F=class{constructor(e){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;this.adapter=e.adapter,this.tableName=e.tableName,this.primaryKey=e.primaryKey,this.batchSize=e.batchSize??100,this.onFlushError=e.onFlushError;let n=e.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...e){this.buffer.push(...e),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let e=this.buffer.splice(0,this.batchSize);try{let n=new Map,r=[];for(let u of e)if(u.operation==="DELETE")r.push(u.docId),n.delete(u.docId);else if(u.data){let a=n.get(u.docId);if(!a)n.set(u.docId,u.data);else {let b=Number(a[H]??0);Number(u.data[H]??0)>=b&&n.set(u.docId,u.data);}}let i=Array.from(n.values());i.length>0&&await this.adapter.upsertRows(this.tableName,i,this.primaryKey),r.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r);}catch(n){if(this.onFlushError)await this.onFlushError(e,n);else return this.buffer.unshift(...e),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var Ae="firestore-sync";function Ce(t,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${t}". Skipping.`),null)}function Ee(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(n=>typeof n=="string");return {isGroup:!!t?.isGroup,documentKey:e[0]??"docId",collectionPath:typeof t?.path=="string"?t.path:null}}function Oe(t){return {isGroup:!!t?._isGroup,documentKey:t?._systemKeys?.[0]??"docId",collectionPath:t?.ref?.path??null}}function Pe(t,e){let{onDocumentCreated:n,onDocumentUpdated:r,onDocumentDeleted:i}=e.deps.firestoreTriggers,u=e.deps.pubsub,a=e?.topicPrefix??Ae,b={},f=new Map;function T(s){let l=f.get(s);return l||(l=u.topic(s),f.set(s,l),l)}async function k(s,l){await T(s).publishMessage({json:l});}let w=t?.rawMapping,A=w?Object.entries(w).map(([s,l])=>[s,Ee(l)]):Object.entries(t).map(([s,l])=>[s,Oe(l)]);for(let[s,l]of A){let c=e?.repos?.[s],o;if(l.isGroup){if(!c?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${s}". Provide a triggerPath in the sync repos config for group collections.`);continue}o=c.triggerPath;}else o=c?.triggerPath??Ce(s,l.collectionPath);if(!o)continue;let p=l.documentKey,S=`${a}-${s}`;b[`${s}_onCreate`]=n(o,async d=>{let h=d.data;if(!h)return;let C=h.data();if(!C)return;let E=String(C[p]??h.id),O=N(C,{exclude:c?.exclude,columnMap:c?.columnMap}),P={operation:"INSERT",repoName:s,docId:E,data:O,timestamp:new Date().toISOString(),version:Date.now()};await k(S,P);}),b[`${s}_onUpdate`]=r(o,async d=>{let h=d.data?.after;if(!h)return;let C=h.data();if(!C)return;let E=String(C[p]??h.id),O=N(C,{exclude:c?.exclude,columnMap:c?.columnMap}),P={operation:"UPSERT",repoName:s,docId:E,data:O,timestamp:new Date().toISOString(),version:Date.now()};await k(S,P);}),b[`${s}_onDelete`]=i(o,async d=>{let h=d.data;if(!h)return;let C=h.data(),E=String(C?.[p]??h.id),O={operation:"DELETE",repoName:s,docId:E,data:null,timestamp:new Date().toISOString(),version:Date.now()};await k(S,O);});}return b}function se(t){let e=t.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function ie(t,e){let n=se(t),r=se(e);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var ae=new Set,V=class extends Error{constructor(n,r,i,u){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${i} in BigQuery but the current Zod schema maps it to ${u}. BigQuery cannot safely convert between these types \u2014 to resolve, either (a) keep the BigQuery type and add a transform in your repo to coerce values, (b) rename the field in your Zod schema (creates a new column), or (c) drop & recreate the table.`);this.tableName=n;this.column=r;this.existingType=i;this.desiredType=u;this.name="SchemaTypeMismatchError";}};async function De(t,e,n,r,i,u,a){if(ae.has(t))return;let b=$(n,e.dialect,{primaryKey:i,exclude:u,columnMap:a});if(!await e.tableExists(r))await e.createTable({tableName:r,columns:b});else if(e.getTableColumnsWithTypes){let T=await e.getTableColumnsWithTypes(r),k=[];for(let w of b){let A=T.get(w.name);if(A===void 0){k.push(w);continue}if(e.dialect.name==="bigquery"&&!ie(A,w.sqlType))throw new V(r,w.name,A,w.sqlType)}k.length>0&&(await e.addColumns(r,k),await e.onSchemaChange?.(r));}else {let T=new Set(await e.getTableColumns(r)),k=b.filter(w=>!T.has(w.name));k.length>0&&(await e.addColumns(r,k),await e.onSchemaChange?.(r));}ae.add(t);}function ve(t,e){let{deps:n,adapter:r,batchSize:i=100,flushIntervalMs:u=5e3,autoMigrate:a=false,topicPrefix:b="firestore-sync",maxDlqAttempts:f=5,workerOptions:T,repos:k={}}=e,w=new Map;function A(c,o){let p=w.get(c);if(p)return p;let d=k[c]?.tableName??c,h=`${b}-${c}-dlq`,C=n.pubsub.topic(h),E=false,O=async()=>{if(!E){try{await C.create(),console.info(`[SyncWorker] Created DLQ topic "${h}"`);}catch(v){if(v?.code!==6)throw v}E=true;}},P=async(v,y)=>{console.error(`[SyncWorker] Flush failed for "${c}" (${v.length} events):`,y),await O(),await Promise.all(v.map(g=>{let x=(g.attempts??0)+1;if(f>0&&x>f)return console.error(`[SyncWorker] Dropping event for "${c}" after ${x-1} DLQ attempts:`,{docId:g.docId,operation:g.operation}),Promise.resolve();let R={...g,attempts:x,firstFailedAt:g.firstFailedAt??Date.now()};return C.publishMessage({json:R})}));};return p=new F({adapter:r,tableName:d,primaryKey:o,batchSize:i,flushIntervalMs:u,onFlushError:P}),w.set(c,p),p}async function s(c){let{repoName:o}=c,p=t[o];if(!p){console.warn(`[SyncWorker] Unknown repo "${o}", skipping event`);return}let S=p._systemKeys?.[0]??p.documentKey??"docId",d=k[o],h=d?.columnMap,C=h?.[S]??S;if(a){let O=p.schema??void 0;if(O){let P=d?.tableName??o;await De(o,r,O,P,S,d?.exclude,h);}}let E=A(o,C);c.data&&(c.data[H]=c.version??Date.now()),E.enqueue(c);}function l(c){let o=async p=>{let S=p.data?.message?.json??p.data?.json;if(!S){console.warn("[SyncWorker] Received empty PubSub message");return}await s(S);let d=w.get(S.repoName);d&&await d.flush();};return T?n.pubsubHandler.onMessagePublished({topic:c,...T},o):n.pubsubHandler.onMessagePublished(c,o)}return {handleMessage:s,createHandler:l,queues:w,async shutdown(){let c=[];for(let o of w.values())c.push(o.shutdown());await Promise.all(c);}}}exports.SyncQueue=F;exports.addColumnsDDL=ke;exports.autoMigrate=Re;exports.createSyncTriggers=Pe;exports.createSyncWorker=ve;exports.createTableDDL=oe;exports.createadminsyncServer=Se;exports.generateDDL=xe;exports.serializeDocument=N;exports.serializeValue=q;exports.zodSchemaToColumns=$;exports.zodTypeToLogical=be;//# sourceMappingURL=index.cjs.map
90
+ `)}async function Re(t,e,n){let r={created:[],altered:[],upToDate:[],skipped:[]};for(let[i,u]of Object.entries(t)){let a=u.schema??void 0;if(!a){r.skipped.push(i);continue}let b=n?.repos?.[i],f=b?.tableName??i,T=u._systemKeys?.[0]??u.documentKey??"docId",k=$(a,e.dialect,{primaryKey:T,exclude:b?.exclude,columnMap:b?.columnMap}),w={tableName:f,columns:k};if(!await e.tableExists(f))await e.createTable(w),r.created.push(f);else {let s=new Set(await e.getTableColumns(f)),l=k.filter(c=>!s.has(c.name));l.length>0?(await e.addColumns(f,l),r.altered.push(f)):r.upToDate.push(f);}}return r}var F=class{constructor(e){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;this.adapter=e.adapter,this.tableName=e.tableName,this.primaryKey=e.primaryKey,this.batchSize=e.batchSize??100,this.onFlushError=e.onFlushError;let n=e.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...e){this.buffer.push(...e),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let e=this.buffer.splice(0,this.batchSize);try{let n=new Map,r=[];for(let u of e)if(u.operation==="DELETE")r.push(u.docId),n.delete(u.docId);else if(u.data){let a=n.get(u.docId);if(!a)n.set(u.docId,u.data);else {let b=Number(a[H]??0);Number(u.data[H]??0)>=b&&n.set(u.docId,u.data);}}let i=Array.from(n.values());i.length>0&&await this.adapter.upsertRows(this.tableName,i,this.primaryKey),r.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r);}catch(n){if(this.onFlushError)await this.onFlushError(e,n);else return this.buffer.unshift(...e),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var Ae="firestore-sync";function Ce(t,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${t}". Skipping.`),null)}function Ee(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(n=>typeof n=="string");return {isGroup:!!t?.isGroup,documentKey:e[0]??"docId",collectionPath:typeof t?.path=="string"?t.path:null}}function Oe(t){return {isGroup:!!t?._isGroup,documentKey:t?._systemKeys?.[0]??"docId",collectionPath:t?.ref?.path??null}}function Pe(t,e){let{onDocumentCreated:n,onDocumentUpdated:r,onDocumentDeleted:i}=e.deps.firestoreTriggers,u=e.deps.pubsub,a=e?.topicPrefix??Ae,b={},f=new Map;function T(s){let l=f.get(s);return l||(l=u.topic(s),f.set(s,l),l)}async function k(s,l){await T(s).publishMessage({json:l});}let w=t?.rawMapping,A=w?Object.entries(w).map(([s,l])=>[s,Ee(l)]):Object.entries(t).map(([s,l])=>[s,Oe(l)]);for(let[s,l]of A){let c=e?.repos?.[s],o;if(l.isGroup){if(!c?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${s}". Provide a triggerPath in the sync repos config for group collections.`);continue}o=c.triggerPath;}else o=c?.triggerPath??Ce(s,l.collectionPath);if(!o)continue;let p=l.documentKey,S=`${a}-${s}`;b[`${s}_onCreate`]=n(o,async d=>{let h=d.data;if(!h)return;let C=h.data();if(!C)return;let E=String(C[p]??h.id),O=N(C,{exclude:c?.exclude,columnMap:c?.columnMap}),P={operation:"INSERT",repoName:s,docId:E,data:O,timestamp:new Date().toISOString(),version:Date.now()};await k(S,P);}),b[`${s}_onUpdate`]=r(o,async d=>{let h=d.data?.after;if(!h)return;let C=h.data();if(!C)return;let E=String(C[p]??h.id),O=N(C,{exclude:c?.exclude,columnMap:c?.columnMap}),P={operation:"UPSERT",repoName:s,docId:E,data:O,timestamp:new Date().toISOString(),version:Date.now()};await k(S,P);}),b[`${s}_onDelete`]=i(o,async d=>{let h=d.data;if(!h)return;let C=h.data(),E=String(C?.[p]??h.id),O={operation:"DELETE",repoName:s,docId:E,data:null,timestamp:new Date().toISOString(),version:Date.now()};await k(S,O);});}return b}function se(t){let e=t.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function ie(t,e){let n=se(t),r=se(e);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var ae=new Set,G=class extends Error{constructor(n,r,i,u){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${i} in BigQuery but the current Zod schema maps it to ${u}. BigQuery cannot safely convert between these types \u2014 to resolve, either (a) keep the BigQuery type and add a transform in your repo to coerce values, (b) rename the field in your Zod schema (creates a new column), or (c) drop & recreate the table.`);this.tableName=n;this.column=r;this.existingType=i;this.desiredType=u;this.name="SchemaTypeMismatchError";}};async function De(t,e,n,r,i,u,a){if(ae.has(t))return;let b=$(n,e.dialect,{primaryKey:i,exclude:u,columnMap:a});if(!await e.tableExists(r))await e.createTable({tableName:r,columns:b});else if(e.getTableColumnsWithTypes){let T=await e.getTableColumnsWithTypes(r),k=[];for(let w of b){let A=T.get(w.name);if(A===void 0){k.push(w);continue}if(e.dialect.name==="bigquery"&&!ie(A,w.sqlType))throw new G(r,w.name,A,w.sqlType)}k.length>0&&(await e.addColumns(r,k),await e.onSchemaChange?.(r));}else {let T=new Set(await e.getTableColumns(r)),k=b.filter(w=>!T.has(w.name));k.length>0&&(await e.addColumns(r,k),await e.onSchemaChange?.(r));}ae.add(t);}function ve(t,e){let{deps:n,adapter:r,batchSize:i=100,flushIntervalMs:u=5e3,autoMigrate:a=false,topicPrefix:b="firestore-sync",maxDlqAttempts:f=5,workerOptions:T,repos:k={}}=e,w=new Map;function A(c,o){let p=w.get(c);if(p)return p;let d=k[c]?.tableName??c,h=`${b}-${c}-dlq`,C=n.pubsub.topic(h),E=false,O=async()=>{if(!E){try{await C.create(),console.info(`[SyncWorker] Created DLQ topic "${h}"`);}catch(v){if(v?.code!==6)throw v}E=true;}},P=async(v,y)=>{console.error(`[SyncWorker] Flush failed for "${c}" (${v.length} events):`,y),await O(),await Promise.all(v.map(g=>{let x=(g.attempts??0)+1;if(f>0&&x>f)return console.error(`[SyncWorker] Dropping event for "${c}" after ${x-1} DLQ attempts:`,{docId:g.docId,operation:g.operation}),Promise.resolve();let R={...g,attempts:x,firstFailedAt:g.firstFailedAt??Date.now()};return C.publishMessage({json:R})}));};return p=new F({adapter:r,tableName:d,primaryKey:o,batchSize:i,flushIntervalMs:u,onFlushError:P}),w.set(c,p),p}async function s(c){let{repoName:o}=c,p=t[o];if(!p){console.warn(`[SyncWorker] Unknown repo "${o}", skipping event`);return}let S=p._systemKeys?.[0]??p.documentKey??"docId",d=k[o],h=d?.columnMap,C=h?.[S]??S;if(a){let O=p.schema??void 0;if(O){let P=d?.tableName??o;await De(o,r,O,P,S,d?.exclude,h);}}let E=A(o,C);c.data&&(c.data[H]=c.version??Date.now()),E.enqueue(c);}function l(c){let o=async p=>{let S=p.data?.message?.json??p.data?.json;if(!S){console.warn("[SyncWorker] Received empty PubSub message");return}await s(S);let d=w.get(S.repoName);d&&await d.flush();};return T?n.pubsubHandler.onMessagePublished({topic:c,...T},o):n.pubsubHandler.onMessagePublished(c,o)}return {handleMessage:s,createHandler:l,queues:w,async shutdown(){let c=[];for(let o of w.values())c.push(o.shutdown());await Promise.all(c);}}}exports.SyncQueue=F;exports.addColumnsDDL=ke;exports.autoMigrate=Re;exports.createSyncTriggers=Pe;exports.createSyncWorker=ve;exports.createTableDDL=oe;exports.createadminsyncServer=Se;exports.generateDDL=xe;exports.serializeDocument=N;exports.serializeValue=q;exports.zodSchemaToColumns=$;exports.zodTypeToLogical=be;//# sourceMappingURL=index.cjs.map
91
91
  //# sourceMappingURL=index.cjs.map
@@ -1,4 +1,4 @@
1
- import'firebase-admin/firestore';import'crypto';function ue(t){let e=[],n=t.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,i)=>(e.push(i),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:e}}function le(t){let e=t.path??t.url??"/",n=e.indexOf("?");return n===-1?e:e.slice(0,n)}var L=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(e,n)=>{n.status(404).send("Not Found");};this.errorHandler=(e,n,r)=>{console.error("[MiniRouter]",e),r.status(500).send("Internal Server Error");};}use(e){return this.middlewares.push(e),this}get(e,n){return this.addRoute("GET",e,n)}post(e,n){return this.addRoute("POST",e,n)}put(e,n){return this.addRoute("PUT",e,n)}patch(e,n){return this.addRoute("PATCH",e,n)}delete(e,n){return this.addRoute("DELETE",e,n)}onNotFound(e){return this.notFoundHandler=e,this}onError(e){return this.errorHandler=e,this}addRoute(e,n,r){let{pattern:i,paramNames:u}=ue(n);return this.routes.push({method:e.toUpperCase(),pattern:i,paramNames:u,handler:r}),this}async handle(e,n){let r=(e.method??"GET").toUpperCase(),i=le(e),u=null,a={};for(let T of this.routes){if(T.method!==r)continue;let k=i.match(T.pattern);if(k){u=T,a={},T.paramNames.forEach((w,A)=>{a[w]=decodeURIComponent(k[A+1]??"");});break}}let b=Object.assign(e,{params:a}),f=u?u.handler:this.notFoundHandler;try{await this.runMiddlewareChain(b,n,f);}catch(T){this.errorHandler(T,e,n);}}async runMiddlewareChain(e,n,r){let i=0,u=async()=>{if(i<this.middlewares.length){let a=this.middlewares[i++];await a(e,n,u);}else await r(e,n);};await u();}};function I(t,e,n){let r=e==="/"?"":e.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",b=process.env.FUNCTION_REGION??"us-central1",f=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${b}/${f}${r}`}let i=process.env.K_SERVICE,u=t?.hostname??t?.headers?.host??"";return i&&typeof u=="string"&&u.includes("cloudfunctions.net")?`/${i.toLowerCase()}${r}`:r}function K(t){return !!t&&typeof t=="object"&&t.__authExtension===true}function ye(t){if(typeof t!="function")return [];let n=t.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(i=>i.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function me(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(r=>typeof r=="string"),n=t?.history&&typeof t.history=="object"?t.history:void 0;return {schema:t?.schema,_systemKeys:e,_pathKey:t?.pathKey??null,_isGroup:!!t?.isGroup,_createdKey:t?.createdKey??null,_parentKeys:t?.isGroup?ye(t?.refCb):[],relationalKeys:t?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof t?.path=="string"?t.path:null}}function Y(t,e){let n=me(t),r,i=()=>{let u=r??(r=e());if(!u){let a=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${a}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return u};return new Proxy(n,{get(u,a){return typeof a=="string"&&a in n?n[a]:i()[a]},has(u,a){return typeof a=="string"&&a in n?true:a in i()}})}var ge={string:"ZodString",number:"ZodNumber",bigint:"ZodBigInt",boolean:"ZodBoolean",date:"ZodDate",enum:"ZodEnum",nativeEnum:"ZodNativeEnum",literal:"ZodLiteral",object:"ZodObject",array:"ZodArray",optional:"ZodOptional",nullable:"ZodNullable",default:"ZodDefault",coerce:"ZodCoerce",union:"ZodUnion",undefined:"ZodUndefined",unknown:"ZodUnknown",any:"ZodAny",record:"ZodRecord"};function Q(t){let e=t,n=e._zod?.def?.type;if(n)return ge[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=e._def?.typeName;return r||""}function X(t){let e=t;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function W(t){let e=t;return e.shape&&typeof e.shape=="object"?e.shape:e._zod?.def?.shape&&typeof e._zod.def.shape=="object"?e._zod.def.shape:e._def?.shape?typeof e._def.shape=="function"?e._def.shape():e._def.shape:{}}var H="__sync_version";var he=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function ee(t){let e=t,n=false;for(;;){let r=Q(e);if(!he.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let i=X(e);if(!i)break;e=i;}return {inner:e,nullable:n}}var te={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function be(t){let{inner:e}=ee(t);return te[Q(e)]??"json"}function ne(t,e,n,r,i,u,a,b){for(let[f,T]of Object.entries(t)){let k=n?`${n}__${f}`:f;if(i.has(f)||i.has(k))continue;let{inner:w,nullable:A}=ee(T),s=Q(w),l=r||A;if(s==="ZodObject"){let S=W(w);ne(S,e,k,l,i,u,a,b);continue}let c=te[s]??"json",o=k===a||f===a,p=u[k]??u[f]??k;b.push({name:p,sqlType:e.mapType(c),nullable:o?false:l,isPrimaryKey:o});}}function $(t,e,n={}){let{primaryKey:r,exclude:i=[],columnMap:u={}}=n,a=new Set(i),b=W(t),f=[];return ne(b,e,"",false,a,u,r,f),f.some(T=>T.name===H)||f.push({name:H,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),f}function q(t){if(t==null)return null;if(typeof t=="object"&&typeof t.toDate=="function")return t.toDate().toISOString();if(t instanceof Date)return t.toISOString();if(Buffer.isBuffer(t))return t.toString("base64");if(t instanceof Uint8Array)return Buffer.from(t).toString("base64");if(typeof t=="object"&&"latitude"in t&&"longitude"in t){let e=t;return JSON.stringify({lat:e.latitude,lng:e.longitude})}return Array.isArray(t)?JSON.stringify(t.map(q)):t}var we=32,Te=5e3;function re(t,e,n,r=new WeakSet,i=0){if(i>we){n[e||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(t)){n[e||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(t);for(let[u,a]of Object.entries(t)){if(Object.keys(n).length>=Te)break;let b=e?`${e}__${u}`:u;a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!Buffer.isBuffer(a)&&!(a instanceof Uint8Array)&&typeof a.toDate!="function"&&!("latitude"in a&&"longitude"in a)?re(a,b,n,r,i+1):n[b]=q(a);}r.delete(t);}function N(t,e){let n=new Set(e?.exclude),r=e?.columnMap??{},i={};re(t,"",i);let u={};for(let[a,b]of Object.entries(i)){if(n.has(a))continue;let f=a.split("__")[0];if(f!==a&&n.has(f))continue;let T=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;u[T]=b;}return u}function _(t,e,n){return `<!DOCTYPE html>
1
+ import'firebase-admin/firestore';import'crypto';function ue(t){let e=[],n=t.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,i)=>(e.push(i),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:e}}function le(t){let e=t.path??t.url??"/",n=e.indexOf("?");return n===-1?e:e.slice(0,n)}var L=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(e,n)=>{n.status(404).send("Not Found");};this.errorHandler=(e,n,r)=>{console.error("[MiniRouter]",e),r.status(500).send("Internal Server Error");};}use(e){return this.middlewares.push(e),this}get(e,n){return this.addRoute("GET",e,n)}post(e,n){return this.addRoute("POST",e,n)}put(e,n){return this.addRoute("PUT",e,n)}patch(e,n){return this.addRoute("PATCH",e,n)}delete(e,n){return this.addRoute("DELETE",e,n)}onNotFound(e){return this.notFoundHandler=e,this}onError(e){return this.errorHandler=e,this}addRoute(e,n,r){let{pattern:i,paramNames:u}=ue(n);return this.routes.push({method:e.toUpperCase(),pattern:i,paramNames:u,handler:r}),this}async handle(e,n){let r=(e.method??"GET").toUpperCase(),i=le(e),u=null,a={};for(let T of this.routes){if(T.method!==r)continue;let k=i.match(T.pattern);if(k){u=T,a={},T.paramNames.forEach((w,A)=>{a[w]=decodeURIComponent(k[A+1]??"");});break}}let b=Object.assign(e,{params:a}),f=u?u.handler:this.notFoundHandler;try{await this.runMiddlewareChain(b,n,f);}catch(T){this.errorHandler(T,e,n);}}async runMiddlewareChain(e,n,r){let i=0,u=async()=>{if(i<this.middlewares.length){let a=this.middlewares[i++];await a(e,n,u);}else await r(e,n);};await u();}};function I(t,e,n){let r=e==="/"?"":e.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let a=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",b=process.env.FUNCTION_REGION??"us-central1",f=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${a}/${b}/${f}${r}`}let i=process.env.K_SERVICE,u=t?.hostname??t?.headers?.host??"";return i&&typeof u=="string"&&u.includes("cloudfunctions.net")?`/${i.toLowerCase()}${r}`:r}function W(t){return !!t&&typeof t=="object"&&t.__authExtension===true}function ye(t){if(typeof t!="function")return [];let n=t.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!n?.[1])return [];let r=n[1].split(",").map(i=>i.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function me(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(r=>typeof r=="string"),n=t?.history&&typeof t.history=="object"?t.history:void 0;return {schema:t?.schema,_systemKeys:e,_pathKey:t?.pathKey??null,_isGroup:!!t?.isGroup,_createdKey:t?.createdKey??null,_parentKeys:t?.isGroup?ye(t?.refCb):[],relationalKeys:t?.relationalKeys,_historyConfig:n,_historySubcollection:n?.enabled?n.subcollection??"history":void 0,_collectionPath:typeof t?.path=="string"?t.path:null}}function Y(t,e){let n=me(t),r,i=()=>{let u=r??(r=e());if(!u){let a=n._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${a}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return u};return new Proxy(n,{get(u,a){return typeof a=="string"&&a in n?n[a]:i()[a]},has(u,a){return typeof a=="string"&&a in n?true:a in i()}})}var ge={string:"ZodString",number:"ZodNumber",bigint:"ZodBigInt",boolean:"ZodBoolean",date:"ZodDate",enum:"ZodEnum",nativeEnum:"ZodNativeEnum",literal:"ZodLiteral",object:"ZodObject",array:"ZodArray",optional:"ZodOptional",nullable:"ZodNullable",default:"ZodDefault",coerce:"ZodCoerce",union:"ZodUnion",undefined:"ZodUndefined",unknown:"ZodUnknown",any:"ZodAny",record:"ZodRecord"};function Q(t){let e=t,n=e._zod?.def?.type;if(n)return ge[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let r=e._def?.typeName;return r||""}function X(t){let e=t;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function K(t){let e=t;return e.shape&&typeof e.shape=="object"?e.shape:e._zod?.def?.shape&&typeof e._zod.def.shape=="object"?e._zod.def.shape:e._def?.shape?typeof e._def.shape=="function"?e._def.shape():e._def.shape:{}}var H="__sync_version";var he=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function ee(t){let e=t,n=false;for(;;){let r=Q(e);if(!he.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(n=true);let i=X(e);if(!i)break;e=i;}return {inner:e,nullable:n}}var te={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function be(t){let{inner:e}=ee(t);return te[Q(e)]??"json"}function ne(t,e,n,r,i,u,a,b){for(let[f,T]of Object.entries(t)){let k=n?`${n}__${f}`:f;if(i.has(f)||i.has(k))continue;let{inner:w,nullable:A}=ee(T),s=Q(w),l=r||A;if(s==="ZodObject"){let S=K(w);ne(S,e,k,l,i,u,a,b);continue}let c=te[s]??"json",o=k===a||f===a,p=u[k]??u[f]??k;b.push({name:p,sqlType:e.mapType(c),nullable:o?false:l,isPrimaryKey:o});}}function $(t,e,n={}){let{primaryKey:r,exclude:i=[],columnMap:u={}}=n,a=new Set(i),b=K(t),f=[];return ne(b,e,"",false,a,u,r,f),f.some(T=>T.name===H)||f.push({name:H,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),f}function q(t){if(t==null)return null;if(typeof t=="object"&&typeof t.toDate=="function")return t.toDate().toISOString();if(t instanceof Date)return t.toISOString();if(Buffer.isBuffer(t))return t.toString("base64");if(t instanceof Uint8Array)return Buffer.from(t).toString("base64");if(typeof t=="object"&&"latitude"in t&&"longitude"in t){let e=t;return JSON.stringify({lat:e.latitude,lng:e.longitude})}return Array.isArray(t)?JSON.stringify(t.map(q)):t}var we=32,Te=5e3;function re(t,e,n,r=new WeakSet,i=0){if(i>we){n[e||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(t)){n[e||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(t);for(let[u,a]of Object.entries(t)){if(Object.keys(n).length>=Te)break;let b=e?`${e}__${u}`:u;a!=null&&typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Date)&&!Buffer.isBuffer(a)&&!(a instanceof Uint8Array)&&typeof a.toDate!="function"&&!("latitude"in a&&"longitude"in a)?re(a,b,n,r,i+1):n[b]=q(a);}r.delete(t);}function N(t,e){let n=new Set(e?.exclude),r=e?.columnMap??{},i={};re(t,"",i);let u={};for(let[a,b]of Object.entries(i)){if(n.has(a))continue;let f=a.split("__")[0];if(f!==a&&n.has(f))continue;let T=r[a]??(a.includes("__")?r[a.split("__").pop()]:void 0)??a;u[T]=b;}return u}function _(t,e,n){return `<!DOCTYPE html>
2
2
  <html lang="en"><head>
3
3
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4
4
  <title>${t} \u2014 Sync Admin</title>
@@ -28,7 +28,7 @@ import'firebase-admin/firestore';import'crypto';function ue(t){let e=[],n=t.repl
28
28
  <nav><a href="${e}/">\u2190 Dashboard</a></nav>
29
29
  <h1>${t}</h1>
30
30
  ${n}
31
- </body></html>`}function M(t,e,n=200){t.status(n).set("Content-Type","text/html; charset=utf-8").send(e);}function j(t,e,n=200){t.status(n).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function Z(t){return (t.headers?.accept??"").includes("application/json")}function Se(t,e,n,r,i,u,a,b){let f=(i.basePath??"/").replace(/\/$/,"")||"",T=i.featuresFlag??{},k=t?.rawMapping,w=[];for(let s of Object.keys(t)){let l=u[s],c=k?Y(k[s],()=>t[s]):t[s];w.push({name:s,schema:c.schema??null,documentKey:c._systemKeys?.[0]??c.documentKey??"docId",tableName:l?.tableName??s,isGroup:!!c._isGroup,repoCfg:l,repo:c});}let A=new L;if(i.auth)if(K(i.auth)){let s=i.auth;for(let l of s.routes){let c=`${f}${l.path}`;l.method==="GET"?A.get(c,l.handler):A.post(c,l.handler);}A.use(s.middleware);}else if(typeof i.auth=="function")A.use(i.auth);else {let s=i.auth.realm??"Sync Admin",l="Basic "+Buffer.from(`${i.auth.username}:${i.auth.password}`).toString("base64");A.use((c,o,p)=>{if((c.headers?.authorization??"")!==l){o.status(401).set("WWW-Authenticate",`Basic realm="${s}"`).set("Content-Type","text/plain").send("Unauthorized");return}p();});}return A.get(`${f}/`,(s,l)=>{let c=I(s,f),o=w.map(d=>{let h=[];return T.healthCheck&&h.push(`<a class="btn" href="${c}/${d.name}/health">Health</a>`),T.manualSync&&h.push(`<a class="btn btn-primary" href="${c}/${d.name}/force-sync">Force Sync</a>`),`<tr>
31
+ </body></html>`}function M(t,e,n=200){t.status(n).set("Content-Type","text/html; charset=utf-8").send(e);}function j(t,e,n=200){t.status(n).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function Z(t){return (t.headers?.accept??"").includes("application/json")}function Se(t,e,n,r,i,u,a,b){let f=(i.basePath??"/").replace(/\/$/,"")||"",T=i.featuresFlag??{},k=t?.rawMapping,w=[];for(let s of Object.keys(t)){let l=u[s],c=k?Y(k[s],()=>t[s]):t[s];w.push({name:s,schema:c.schema??null,documentKey:c._systemKeys?.[0]??c.documentKey??"docId",tableName:l?.tableName??s,isGroup:!!c._isGroup,repoCfg:l,repo:c});}let A=new L;if(i.auth)if(W(i.auth)){let s=i.auth;for(let l of s.routes){let c=`${f}${l.path}`;l.method==="GET"?A.get(c,l.handler):A.post(c,l.handler);}A.use(s.middleware);}else if(typeof i.auth=="function")A.use(i.auth);else {let s=i.auth.realm??"Sync Admin",l="Basic "+Buffer.from(`${i.auth.username}:${i.auth.password}`).toString("base64");A.use((c,o,p)=>{if((c.headers?.authorization??"")!==l){o.status(401).set("WWW-Authenticate",`Basic realm="${s}"`).set("Content-Type","text/plain").send("Unauthorized");return}p();});}return A.get(`${f}/`,(s,l)=>{let c=I(s,f),o=w.map(d=>{let h=[];return T.healthCheck&&h.push(`<a class="btn" href="${c}/${d.name}/health">Health</a>`),T.manualSync&&h.push(`<a class="btn btn-primary" href="${c}/${d.name}/force-sync">Force Sync</a>`),`<tr>
32
32
  <td><strong>${d.name}</strong></td>
33
33
  <td>${d.tableName}</td>
34
34
  <td>${d.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
@@ -87,5 +87,5 @@ ${n}
87
87
  );`}function ke(t,e,n){return n.map(r=>`ALTER TABLE ${t.quoteIdentifier(e)} ADD COLUMN ${t.quoteIdentifier(r.name)} ${r.sqlType};`).join(`
88
88
  `)}function xe(t,e,n){let r=[];for(let[i,u]of Object.entries(t)){let a=u.schema??u._schema??void 0;if(!a)continue;let b=n?.repos?.[i],f=b?.tableName??i,T=u._systemKeys?.[0]??u.documentKey??"docId",k=$(a,e,{primaryKey:T,exclude:b?.exclude,columnMap:b?.columnMap}),w={tableName:f,columns:k};r.push(oe(e,w));}return r.join(`
89
89
 
90
- `)}async function Re(t,e,n){let r={created:[],altered:[],upToDate:[],skipped:[]};for(let[i,u]of Object.entries(t)){let a=u.schema??void 0;if(!a){r.skipped.push(i);continue}let b=n?.repos?.[i],f=b?.tableName??i,T=u._systemKeys?.[0]??u.documentKey??"docId",k=$(a,e.dialect,{primaryKey:T,exclude:b?.exclude,columnMap:b?.columnMap}),w={tableName:f,columns:k};if(!await e.tableExists(f))await e.createTable(w),r.created.push(f);else {let s=new Set(await e.getTableColumns(f)),l=k.filter(c=>!s.has(c.name));l.length>0?(await e.addColumns(f,l),r.altered.push(f)):r.upToDate.push(f);}}return r}var F=class{constructor(e){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;this.adapter=e.adapter,this.tableName=e.tableName,this.primaryKey=e.primaryKey,this.batchSize=e.batchSize??100,this.onFlushError=e.onFlushError;let n=e.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...e){this.buffer.push(...e),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let e=this.buffer.splice(0,this.batchSize);try{let n=new Map,r=[];for(let u of e)if(u.operation==="DELETE")r.push(u.docId),n.delete(u.docId);else if(u.data){let a=n.get(u.docId);if(!a)n.set(u.docId,u.data);else {let b=Number(a[H]??0);Number(u.data[H]??0)>=b&&n.set(u.docId,u.data);}}let i=Array.from(n.values());i.length>0&&await this.adapter.upsertRows(this.tableName,i,this.primaryKey),r.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r);}catch(n){if(this.onFlushError)await this.onFlushError(e,n);else return this.buffer.unshift(...e),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var Ae="firestore-sync";function Ce(t,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${t}". Skipping.`),null)}function Ee(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(n=>typeof n=="string");return {isGroup:!!t?.isGroup,documentKey:e[0]??"docId",collectionPath:typeof t?.path=="string"?t.path:null}}function Oe(t){return {isGroup:!!t?._isGroup,documentKey:t?._systemKeys?.[0]??"docId",collectionPath:t?.ref?.path??null}}function Pe(t,e){let{onDocumentCreated:n,onDocumentUpdated:r,onDocumentDeleted:i}=e.deps.firestoreTriggers,u=e.deps.pubsub,a=e?.topicPrefix??Ae,b={},f=new Map;function T(s){let l=f.get(s);return l||(l=u.topic(s),f.set(s,l),l)}async function k(s,l){await T(s).publishMessage({json:l});}let w=t?.rawMapping,A=w?Object.entries(w).map(([s,l])=>[s,Ee(l)]):Object.entries(t).map(([s,l])=>[s,Oe(l)]);for(let[s,l]of A){let c=e?.repos?.[s],o;if(l.isGroup){if(!c?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${s}". Provide a triggerPath in the sync repos config for group collections.`);continue}o=c.triggerPath;}else o=c?.triggerPath??Ce(s,l.collectionPath);if(!o)continue;let p=l.documentKey,S=`${a}-${s}`;b[`${s}_onCreate`]=n(o,async d=>{let h=d.data;if(!h)return;let C=h.data();if(!C)return;let E=String(C[p]??h.id),O=N(C,{exclude:c?.exclude,columnMap:c?.columnMap}),P={operation:"INSERT",repoName:s,docId:E,data:O,timestamp:new Date().toISOString(),version:Date.now()};await k(S,P);}),b[`${s}_onUpdate`]=r(o,async d=>{let h=d.data?.after;if(!h)return;let C=h.data();if(!C)return;let E=String(C[p]??h.id),O=N(C,{exclude:c?.exclude,columnMap:c?.columnMap}),P={operation:"UPSERT",repoName:s,docId:E,data:O,timestamp:new Date().toISOString(),version:Date.now()};await k(S,P);}),b[`${s}_onDelete`]=i(o,async d=>{let h=d.data;if(!h)return;let C=h.data(),E=String(C?.[p]??h.id),O={operation:"DELETE",repoName:s,docId:E,data:null,timestamp:new Date().toISOString(),version:Date.now()};await k(S,O);});}return b}function se(t){let e=t.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function ie(t,e){let n=se(t),r=se(e);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var ae=new Set,V=class extends Error{constructor(n,r,i,u){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${i} in BigQuery but the current Zod schema maps it to ${u}. BigQuery cannot safely convert between these types \u2014 to resolve, either (a) keep the BigQuery type and add a transform in your repo to coerce values, (b) rename the field in your Zod schema (creates a new column), or (c) drop & recreate the table.`);this.tableName=n;this.column=r;this.existingType=i;this.desiredType=u;this.name="SchemaTypeMismatchError";}};async function De(t,e,n,r,i,u,a){if(ae.has(t))return;let b=$(n,e.dialect,{primaryKey:i,exclude:u,columnMap:a});if(!await e.tableExists(r))await e.createTable({tableName:r,columns:b});else if(e.getTableColumnsWithTypes){let T=await e.getTableColumnsWithTypes(r),k=[];for(let w of b){let A=T.get(w.name);if(A===void 0){k.push(w);continue}if(e.dialect.name==="bigquery"&&!ie(A,w.sqlType))throw new V(r,w.name,A,w.sqlType)}k.length>0&&(await e.addColumns(r,k),await e.onSchemaChange?.(r));}else {let T=new Set(await e.getTableColumns(r)),k=b.filter(w=>!T.has(w.name));k.length>0&&(await e.addColumns(r,k),await e.onSchemaChange?.(r));}ae.add(t);}function ve(t,e){let{deps:n,adapter:r,batchSize:i=100,flushIntervalMs:u=5e3,autoMigrate:a=false,topicPrefix:b="firestore-sync",maxDlqAttempts:f=5,workerOptions:T,repos:k={}}=e,w=new Map;function A(c,o){let p=w.get(c);if(p)return p;let d=k[c]?.tableName??c,h=`${b}-${c}-dlq`,C=n.pubsub.topic(h),E=false,O=async()=>{if(!E){try{await C.create(),console.info(`[SyncWorker] Created DLQ topic "${h}"`);}catch(v){if(v?.code!==6)throw v}E=true;}},P=async(v,y)=>{console.error(`[SyncWorker] Flush failed for "${c}" (${v.length} events):`,y),await O(),await Promise.all(v.map(g=>{let x=(g.attempts??0)+1;if(f>0&&x>f)return console.error(`[SyncWorker] Dropping event for "${c}" after ${x-1} DLQ attempts:`,{docId:g.docId,operation:g.operation}),Promise.resolve();let R={...g,attempts:x,firstFailedAt:g.firstFailedAt??Date.now()};return C.publishMessage({json:R})}));};return p=new F({adapter:r,tableName:d,primaryKey:o,batchSize:i,flushIntervalMs:u,onFlushError:P}),w.set(c,p),p}async function s(c){let{repoName:o}=c,p=t[o];if(!p){console.warn(`[SyncWorker] Unknown repo "${o}", skipping event`);return}let S=p._systemKeys?.[0]??p.documentKey??"docId",d=k[o],h=d?.columnMap,C=h?.[S]??S;if(a){let O=p.schema??void 0;if(O){let P=d?.tableName??o;await De(o,r,O,P,S,d?.exclude,h);}}let E=A(o,C);c.data&&(c.data[H]=c.version??Date.now()),E.enqueue(c);}function l(c){let o=async p=>{let S=p.data?.message?.json??p.data?.json;if(!S){console.warn("[SyncWorker] Received empty PubSub message");return}await s(S);let d=w.get(S.repoName);d&&await d.flush();};return T?n.pubsubHandler.onMessagePublished({topic:c,...T},o):n.pubsubHandler.onMessagePublished(c,o)}return {handleMessage:s,createHandler:l,queues:w,async shutdown(){let c=[];for(let o of w.values())c.push(o.shutdown());await Promise.all(c);}}}export{F as SyncQueue,ke as addColumnsDDL,Re as autoMigrate,Pe as createSyncTriggers,ve as createSyncWorker,oe as createTableDDL,Se as createadminsyncServer,xe as generateDDL,N as serializeDocument,q as serializeValue,$ as zodSchemaToColumns,be as zodTypeToLogical};//# sourceMappingURL=index.js.map
90
+ `)}async function Re(t,e,n){let r={created:[],altered:[],upToDate:[],skipped:[]};for(let[i,u]of Object.entries(t)){let a=u.schema??void 0;if(!a){r.skipped.push(i);continue}let b=n?.repos?.[i],f=b?.tableName??i,T=u._systemKeys?.[0]??u.documentKey??"docId",k=$(a,e.dialect,{primaryKey:T,exclude:b?.exclude,columnMap:b?.columnMap}),w={tableName:f,columns:k};if(!await e.tableExists(f))await e.createTable(w),r.created.push(f);else {let s=new Set(await e.getTableColumns(f)),l=k.filter(c=>!s.has(c.name));l.length>0?(await e.addColumns(f,l),r.altered.push(f)):r.upToDate.push(f);}}return r}var F=class{constructor(e){this.buffer=[];this.flushing=false;this.flushPromise=null;this.timer=null;this.adapter=e.adapter,this.tableName=e.tableName,this.primaryKey=e.primaryKey,this.batchSize=e.batchSize??100,this.onFlushError=e.onFlushError;let n=e.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...e){this.buffer.push(...e),this.buffer.length>=this.batchSize&&this.flush();}async flush(){for(;this.flushPromise;)await this.flushPromise;this.buffer.length!==0&&(this.flushing=true,this.flushPromise=this._drain().finally(()=>{this.flushing=false,this.flushPromise=null;}),await this.flushPromise);}async _drain(){for(;this.buffer.length>0&&await this._doFlush(););}async _doFlush(){let e=this.buffer.splice(0,this.batchSize);try{let n=new Map,r=[];for(let u of e)if(u.operation==="DELETE")r.push(u.docId),n.delete(u.docId);else if(u.data){let a=n.get(u.docId);if(!a)n.set(u.docId,u.data);else {let b=Number(a[H]??0);Number(u.data[H]??0)>=b&&n.set(u.docId,u.data);}}let i=Array.from(n.values());i.length>0&&await this.adapter.upsertRows(this.tableName,i,this.primaryKey),r.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r);}catch(n){if(this.onFlushError)await this.onFlushError(e,n);else return this.buffer.unshift(...e),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var Ae="firestore-sync";function Ce(t,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${t}". Skipping.`),null)}function Ee(t){let e=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(n=>typeof n=="string");return {isGroup:!!t?.isGroup,documentKey:e[0]??"docId",collectionPath:typeof t?.path=="string"?t.path:null}}function Oe(t){return {isGroup:!!t?._isGroup,documentKey:t?._systemKeys?.[0]??"docId",collectionPath:t?.ref?.path??null}}function Pe(t,e){let{onDocumentCreated:n,onDocumentUpdated:r,onDocumentDeleted:i}=e.deps.firestoreTriggers,u=e.deps.pubsub,a=e?.topicPrefix??Ae,b={},f=new Map;function T(s){let l=f.get(s);return l||(l=u.topic(s),f.set(s,l),l)}async function k(s,l){await T(s).publishMessage({json:l});}let w=t?.rawMapping,A=w?Object.entries(w).map(([s,l])=>[s,Ee(l)]):Object.entries(t).map(([s,l])=>[s,Oe(l)]);for(let[s,l]of A){let c=e?.repos?.[s],o;if(l.isGroup){if(!c?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${s}". Provide a triggerPath in the sync repos config for group collections.`);continue}o=c.triggerPath;}else o=c?.triggerPath??Ce(s,l.collectionPath);if(!o)continue;let p=l.documentKey,S=`${a}-${s}`;b[`${s}_onCreate`]=n(o,async d=>{let h=d.data;if(!h)return;let C=h.data();if(!C)return;let E=String(C[p]??h.id),O=N(C,{exclude:c?.exclude,columnMap:c?.columnMap}),P={operation:"INSERT",repoName:s,docId:E,data:O,timestamp:new Date().toISOString(),version:Date.now()};await k(S,P);}),b[`${s}_onUpdate`]=r(o,async d=>{let h=d.data?.after;if(!h)return;let C=h.data();if(!C)return;let E=String(C[p]??h.id),O=N(C,{exclude:c?.exclude,columnMap:c?.columnMap}),P={operation:"UPSERT",repoName:s,docId:E,data:O,timestamp:new Date().toISOString(),version:Date.now()};await k(S,P);}),b[`${s}_onDelete`]=i(o,async d=>{let h=d.data;if(!h)return;let C=h.data(),E=String(C?.[p]??h.id),O={operation:"DELETE",repoName:s,docId:E,data:null,timestamp:new Date().toISOString(),version:Date.now()};await k(S,O);});}return b}function se(t){let e=t.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function ie(t,e){let n=se(t),r=se(e);return n===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[n]?.includes(r)??false}var ae=new Set,G=class extends Error{constructor(n,r,i,u){super(`Schema drift detected on \`${n}\`: column \`${r}\` has type ${i} in BigQuery but the current Zod schema maps it to ${u}. BigQuery cannot safely convert between these types \u2014 to resolve, either (a) keep the BigQuery type and add a transform in your repo to coerce values, (b) rename the field in your Zod schema (creates a new column), or (c) drop & recreate the table.`);this.tableName=n;this.column=r;this.existingType=i;this.desiredType=u;this.name="SchemaTypeMismatchError";}};async function De(t,e,n,r,i,u,a){if(ae.has(t))return;let b=$(n,e.dialect,{primaryKey:i,exclude:u,columnMap:a});if(!await e.tableExists(r))await e.createTable({tableName:r,columns:b});else if(e.getTableColumnsWithTypes){let T=await e.getTableColumnsWithTypes(r),k=[];for(let w of b){let A=T.get(w.name);if(A===void 0){k.push(w);continue}if(e.dialect.name==="bigquery"&&!ie(A,w.sqlType))throw new G(r,w.name,A,w.sqlType)}k.length>0&&(await e.addColumns(r,k),await e.onSchemaChange?.(r));}else {let T=new Set(await e.getTableColumns(r)),k=b.filter(w=>!T.has(w.name));k.length>0&&(await e.addColumns(r,k),await e.onSchemaChange?.(r));}ae.add(t);}function ve(t,e){let{deps:n,adapter:r,batchSize:i=100,flushIntervalMs:u=5e3,autoMigrate:a=false,topicPrefix:b="firestore-sync",maxDlqAttempts:f=5,workerOptions:T,repos:k={}}=e,w=new Map;function A(c,o){let p=w.get(c);if(p)return p;let d=k[c]?.tableName??c,h=`${b}-${c}-dlq`,C=n.pubsub.topic(h),E=false,O=async()=>{if(!E){try{await C.create(),console.info(`[SyncWorker] Created DLQ topic "${h}"`);}catch(v){if(v?.code!==6)throw v}E=true;}},P=async(v,y)=>{console.error(`[SyncWorker] Flush failed for "${c}" (${v.length} events):`,y),await O(),await Promise.all(v.map(g=>{let x=(g.attempts??0)+1;if(f>0&&x>f)return console.error(`[SyncWorker] Dropping event for "${c}" after ${x-1} DLQ attempts:`,{docId:g.docId,operation:g.operation}),Promise.resolve();let R={...g,attempts:x,firstFailedAt:g.firstFailedAt??Date.now()};return C.publishMessage({json:R})}));};return p=new F({adapter:r,tableName:d,primaryKey:o,batchSize:i,flushIntervalMs:u,onFlushError:P}),w.set(c,p),p}async function s(c){let{repoName:o}=c,p=t[o];if(!p){console.warn(`[SyncWorker] Unknown repo "${o}", skipping event`);return}let S=p._systemKeys?.[0]??p.documentKey??"docId",d=k[o],h=d?.columnMap,C=h?.[S]??S;if(a){let O=p.schema??void 0;if(O){let P=d?.tableName??o;await De(o,r,O,P,S,d?.exclude,h);}}let E=A(o,C);c.data&&(c.data[H]=c.version??Date.now()),E.enqueue(c);}function l(c){let o=async p=>{let S=p.data?.message?.json??p.data?.json;if(!S){console.warn("[SyncWorker] Received empty PubSub message");return}await s(S);let d=w.get(S.repoName);d&&await d.flush();};return T?n.pubsubHandler.onMessagePublished({topic:c,...T},o):n.pubsubHandler.onMessagePublished(c,o)}return {handleMessage:s,createHandler:l,queues:w,async shutdown(){let c=[];for(let o of w.values())c.push(o.shutdown());await Promise.all(c);}}}export{F as SyncQueue,ke as addColumnsDDL,Re as autoMigrate,Pe as createSyncTriggers,ve as createSyncWorker,oe as createTableDDL,Se as createadminsyncServer,xe as generateDDL,N as serializeDocument,q as serializeValue,$ as zodSchemaToColumns,be as zodTypeToLogical};//# sourceMappingURL=index.js.map
91
91
  //# sourceMappingURL=index.js.map
@@ -218,6 +218,10 @@ interface PaginationResult<T> {
218
218
  hasPrevPage: boolean;
219
219
  /** Total number of items in current page */
220
220
  pageSize: number;
221
+ /** Total count of items matching the query (when withTotal is true) */
222
+ totalCount?: number;
223
+ /** Whether totalCount is exact (true) or estimated due to OR conditions (false) */
224
+ totalCountIsExact?: boolean;
221
225
  }
222
226
  /**
223
227
  * Pagination options for cursor-based pagination
@@ -230,6 +234,8 @@ interface PaginationOptions<T> extends Omit<QueryOptions<T>, "limit"> {
230
234
  cursor?: DocumentSnapshot;
231
235
  /** Direction of pagination */
232
236
  direction?: "next" | "prev";
237
+ /** Whether to calculate and return total count of matching items */
238
+ withTotal?: boolean;
233
239
  }
234
240
  /**
235
241
  * Executes a paginated query and returns results with pagination info.
@@ -998,6 +1004,8 @@ interface ApiResponse<T = unknown> {
998
1004
  indexUrl?: string;
999
1005
  meta?: {
1000
1006
  total?: number;
1007
+ totalCount?: number;
1008
+ totalCountIsExact?: boolean;
1001
1009
  page?: number;
1002
1010
  pageSize?: number;
1003
1011
  hasMore?: boolean;
@@ -1017,6 +1025,10 @@ interface ListResponseData<T = unknown> {
1017
1025
  hasNextPage: boolean;
1018
1026
  /** Whether there is a previous page */
1019
1027
  hasPrevPage: boolean;
1028
+ /** Total count of items matching the query (when withTotal is true) */
1029
+ totalCount?: number;
1030
+ /** Whether totalCount is exact (true) or estimated due to OR conditions (false) */
1031
+ totalCountIsExact?: boolean;
1020
1032
  }
1021
1033
  /**
1022
1034
  * Query request body for POST /query endpoint.
@@ -1075,6 +1087,10 @@ interface QueryRequestBody {
1075
1087
  relation: string;
1076
1088
  select?: string[];
1077
1089
  })[];
1090
+ /**
1091
+ * Whether to calculate and return total count of matching items.
1092
+ */
1093
+ withTotal?: boolean;
1078
1094
  }
1079
1095
 
1080
1096
  export { type ApiResponse as A, type ConfiguredRepository as C, DEFAULT_HTML_CSP as D, type ExtractDocumentRefSignature as E, type FieldRole as F, type GetOptions as G, type IncludeConfigTyped as I, type ListResponseData as L, type OpenAPISpecOptions as O, type PaginationOptions as P, type QueryRequestBody as Q, type RepoFieldPath as R, type SecurityHeadersOptions as S, type UserFieldPath as U, type WhereClause as W, type CrudServerOptions as a, type CrudRepoConfig as b, type CrudRepoEntry as c, type CrudRepoRegistry as d, type RepoRelationKeys as e, type RepositoryConfig as f, type FieldPath as g, type QueryOptions as h, type RelationConfig as i, type ExtractUpdateSignature as j, type GetResult as k, type RelationalKeys as l, createPaginationIterator as m, executePaginatedQuery as n, type PaginationResult as o, type SystemBackfillFailure as p, type SystemBackfillOptions as q, type SystemBackfillResult as r, securityHeaders as s, type GenerateGetMethods as t, type GenerateQueryMethods as u, type PaginationWithIncludeOptionsTyped as v, type PopulateOptionsTyped as w };
@@ -218,6 +218,10 @@ interface PaginationResult<T> {
218
218
  hasPrevPage: boolean;
219
219
  /** Total number of items in current page */
220
220
  pageSize: number;
221
+ /** Total count of items matching the query (when withTotal is true) */
222
+ totalCount?: number;
223
+ /** Whether totalCount is exact (true) or estimated due to OR conditions (false) */
224
+ totalCountIsExact?: boolean;
221
225
  }
222
226
  /**
223
227
  * Pagination options for cursor-based pagination
@@ -230,6 +234,8 @@ interface PaginationOptions<T> extends Omit<QueryOptions<T>, "limit"> {
230
234
  cursor?: DocumentSnapshot;
231
235
  /** Direction of pagination */
232
236
  direction?: "next" | "prev";
237
+ /** Whether to calculate and return total count of matching items */
238
+ withTotal?: boolean;
233
239
  }
234
240
  /**
235
241
  * Executes a paginated query and returns results with pagination info.
@@ -998,6 +1004,8 @@ interface ApiResponse<T = unknown> {
998
1004
  indexUrl?: string;
999
1005
  meta?: {
1000
1006
  total?: number;
1007
+ totalCount?: number;
1008
+ totalCountIsExact?: boolean;
1001
1009
  page?: number;
1002
1010
  pageSize?: number;
1003
1011
  hasMore?: boolean;
@@ -1017,6 +1025,10 @@ interface ListResponseData<T = unknown> {
1017
1025
  hasNextPage: boolean;
1018
1026
  /** Whether there is a previous page */
1019
1027
  hasPrevPage: boolean;
1028
+ /** Total count of items matching the query (when withTotal is true) */
1029
+ totalCount?: number;
1030
+ /** Whether totalCount is exact (true) or estimated due to OR conditions (false) */
1031
+ totalCountIsExact?: boolean;
1020
1032
  }
1021
1033
  /**
1022
1034
  * Query request body for POST /query endpoint.
@@ -1075,6 +1087,10 @@ interface QueryRequestBody {
1075
1087
  relation: string;
1076
1088
  select?: string[];
1077
1089
  })[];
1090
+ /**
1091
+ * Whether to calculate and return total count of matching items.
1092
+ */
1093
+ withTotal?: boolean;
1078
1094
  }
1079
1095
 
1080
1096
  export { type ApiResponse as A, type ConfiguredRepository as C, DEFAULT_HTML_CSP as D, type ExtractDocumentRefSignature as E, type FieldRole as F, type GetOptions as G, type IncludeConfigTyped as I, type ListResponseData as L, type OpenAPISpecOptions as O, type PaginationOptions as P, type QueryRequestBody as Q, type RepoFieldPath as R, type SecurityHeadersOptions as S, type UserFieldPath as U, type WhereClause as W, type CrudServerOptions as a, type CrudRepoConfig as b, type CrudRepoEntry as c, type CrudRepoRegistry as d, type RepoRelationKeys as e, type RepositoryConfig as f, type FieldPath as g, type QueryOptions as h, type RelationConfig as i, type ExtractUpdateSignature as j, type GetResult as k, type RelationalKeys as l, createPaginationIterator as m, executePaginatedQuery as n, type PaginationResult as o, type SystemBackfillFailure as p, type SystemBackfillOptions as q, type SystemBackfillResult as r, securityHeaders as s, type GenerateGetMethods as t, type GenerateQueryMethods as u, type PaginationWithIncludeOptionsTyped as v, type PopulateOptionsTyped as w };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lpdjs/firestore-repo-service",
3
- "version": "2.6.47",
3
+ "version": "2.6.49",
4
4
  "workspaces": [
5
5
  "test/functions"
6
6
  ],