@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.
Files changed (75) hide show
  1. package/dist/actor-context-DQZgWqj3.d.cts +117 -0
  2. package/dist/actor-context-DQZgWqj3.d.ts +117 -0
  3. package/dist/{create-servers-LyRLAOh3.d.cts → create-servers-B5Z5v2SP.d.cts} +11 -5
  4. package/dist/{create-servers-Db1xUY2N.d.ts → create-servers-p1-jJNTG.d.ts} +11 -5
  5. package/dist/history/index.cjs +1 -1
  6. package/dist/history/index.cjs.map +1 -1
  7. package/dist/history/index.d.cts +67 -7
  8. package/dist/history/index.d.ts +67 -7
  9. package/dist/history/index.js +1 -1
  10. package/dist/history/index.js.map +1 -1
  11. package/dist/index.cjs +81 -81
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +20 -14
  14. package/dist/index.d.ts +20 -14
  15. package/dist/index.js +81 -81
  16. package/dist/index.js.map +1 -1
  17. package/dist/llms-full.txt +1 -1
  18. package/dist/llms.txt +1 -1
  19. package/dist/{openapi-QVpqnnes.d.cts → openapi-B9utXiEH.d.cts} +1 -1
  20. package/dist/{openapi-CNIA7QRw.d.ts → openapi-Bsqq2zgh.d.ts} +1 -1
  21. package/dist/{queue-BEB-ujA3.d.ts → queue-NFod6hTT.d.ts} +1 -1
  22. package/dist/{queue-CpHe6M5j.d.cts → queue-zw2B7GPx.d.cts} +1 -1
  23. package/dist/{read-15-TcgCz.d.ts → read-BPov7lws.d.ts} +30 -7
  24. package/dist/{read-B15YaPyR.d.cts → read-Dfah1PPl.d.cts} +30 -7
  25. package/dist/{rules-Cafrkb9v.d.ts → rules-18wH7Uak.d.ts} +1 -1
  26. package/dist/{rules-Bu2NB7Eb.d.cts → rules-oSXoV4Js.d.cts} +1 -1
  27. package/dist/servers/admin/index.cjs +5 -5
  28. package/dist/servers/admin/index.cjs.map +1 -1
  29. package/dist/servers/admin/index.d.cts +5 -4
  30. package/dist/servers/admin/index.d.ts +5 -4
  31. package/dist/servers/admin/index.js +5 -5
  32. package/dist/servers/admin/index.js.map +1 -1
  33. package/dist/servers/crud/index.cjs +2 -2
  34. package/dist/servers/crud/index.cjs.map +1 -1
  35. package/dist/servers/crud/index.d.cts +10 -9
  36. package/dist/servers/crud/index.d.ts +10 -9
  37. package/dist/servers/crud/index.js +2 -2
  38. package/dist/servers/crud/index.js.map +1 -1
  39. package/dist/servers/hono/index.cjs +14 -14
  40. package/dist/servers/hono/index.cjs.map +1 -1
  41. package/dist/servers/hono/index.d.cts +11 -3
  42. package/dist/servers/hono/index.d.ts +11 -3
  43. package/dist/servers/hono/index.js +14 -14
  44. package/dist/servers/hono/index.js.map +1 -1
  45. package/dist/servers/index.cjs +94 -94
  46. package/dist/servers/index.cjs.map +1 -1
  47. package/dist/servers/index.d.cts +13 -12
  48. package/dist/servers/index.d.ts +13 -12
  49. package/dist/servers/index.js +94 -94
  50. package/dist/servers/index.js.map +1 -1
  51. package/dist/sync/bigquery.d.cts +2 -2
  52. package/dist/sync/bigquery.d.ts +2 -2
  53. package/dist/sync/index.cjs +55 -55
  54. package/dist/sync/index.cjs.map +1 -1
  55. package/dist/sync/index.d.cts +6 -6
  56. package/dist/sync/index.d.ts +6 -6
  57. package/dist/sync/index.js +55 -55
  58. package/dist/sync/index.js.map +1 -1
  59. package/dist/sync/meilisearch.cjs +2 -2
  60. package/dist/sync/meilisearch.cjs.map +1 -1
  61. package/dist/sync/meilisearch.d.cts +2 -2
  62. package/dist/sync/meilisearch.d.ts +2 -2
  63. package/dist/sync/meilisearch.js +2 -2
  64. package/dist/sync/meilisearch.js.map +1 -1
  65. package/dist/{types-o-9qoExc.d.cts → types-BDTx8VPg.d.cts} +8 -0
  66. package/dist/{types-CNseHqF7.d.cts → types-BGh5_2fl.d.cts} +4 -4
  67. package/dist/{types-DGQURFSq.d.ts → types-B_FrzmO4.d.ts} +1 -1
  68. package/dist/{types-DmXW_fVz.d.ts → types-Cc6lelk1.d.ts} +4 -4
  69. package/dist/{types--RamYGF1.d.cts → types-D6zvWzRt.d.cts} +96 -2
  70. package/dist/{types--RamYGF1.d.ts → types-D6zvWzRt.d.ts} +96 -2
  71. package/dist/{types-VVuLlmfc.d.cts → types-D78FPJeF.d.cts} +1 -1
  72. package/dist/{types-B51LYvQZ.d.cts → types-Dc3lX99O.d.cts} +20 -19
  73. package/dist/{types-Ci0dGbuW.d.ts → types-DgFJLwAu.d.ts} +20 -19
  74. package/dist/{types-D3W_RaDA.d.ts → types-w1rEqs0Z.d.ts} +8 -0
  75. package/package.json +1 -1
@@ -5,8 +5,8 @@ import '../firebase-auth-nG3prKoj.cjs';
5
5
  import 'firebase-functions/v2/firestore';
6
6
  import 'firebase-functions/v2/https';
7
7
  import 'firebase-functions/v2/pubsub';
8
- import '../types-B51LYvQZ.cjs';
9
- import '../types--RamYGF1.cjs';
8
+ import '../types-Dc3lX99O.cjs';
9
+ import '../types-D6zvWzRt.cjs';
10
10
  import 'firebase-admin/firestore';
11
11
 
12
12
  /**
@@ -5,8 +5,8 @@ import '../firebase-auth-nG3prKoj.js';
5
5
  import 'firebase-functions/v2/firestore';
6
6
  import 'firebase-functions/v2/https';
7
7
  import 'firebase-functions/v2/pubsub';
8
- import '../types-Ci0dGbuW.js';
9
- import '../types--RamYGF1.js';
8
+ import '../types-DgFJLwAu.js';
9
+ import '../types-D6zvWzRt.js';
10
10
  import 'firebase-admin/firestore';
11
11
 
12
12
  /**
@@ -1,4 +1,4 @@
1
- 'use strict';require('firebase-admin/firestore'),require('crypto');var ye=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});function ve(n){let e=[],t=n.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,s)=>(e.push(s),"([^/]+)"));return {pattern:new RegExp(`^${t}$`),paramNames:e}}function Me(n){let e=n.path??n.url??"/",t=e.indexOf("?");return t===-1?e:e.slice(0,t)}var V=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(e,t)=>{t.status(404).send("Not Found");};this.errorHandler=(e,t,r)=>{console.error("[MiniRouter]",e),r.status(500).send("Internal Server Error");};}use(e){return this.middlewares.push(e),this}get(e,t){return this.addRoute("GET",e,t)}post(e,t){return this.addRoute("POST",e,t)}put(e,t){return this.addRoute("PUT",e,t)}patch(e,t){return this.addRoute("PATCH",e,t)}delete(e,t){return this.addRoute("DELETE",e,t)}onNotFound(e){return this.notFoundHandler=e,this}onError(e){return this.errorHandler=e,this}addRoute(e,t,r){let{pattern:s,paramNames:o}=ve(t);return this.routes.push({method:e.toUpperCase(),pattern:s,paramNames:o,handler:r}),this}async handle(e,t){let r=(e.method??"GET").toUpperCase(),s=Me(e),o=null,i={};for(let y of this.routes){if(y.method!==r)continue;let S=s.match(y.pattern);if(S){o=y,i={},y.paramNames.forEach((T,O)=>{i[T]=decodeURIComponent(S[O+1]??"");});break}}let a=Object.assign(e,{params:i}),c=o?o.handler:this.notFoundHandler;try{await this.runMiddlewareChain(a,t,c);}catch(y){this.errorHandler(y,e,t);}}async runMiddlewareChain(e,t,r){let s=0,o=async()=>{if(s<this.middlewares.length){let i=this.middlewares[s++];await i(e,t,o);}else await r(e,t);};await o();}};function B(n,e,t){let r=e==="/"?"":e.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let i=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",a=t??process.env.FUNCTION_REGION??"us-central1",c=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${i}/${a}/${c}${r}`}let s=process.env.K_SERVICE,o=n?.hostname??n?.headers?.host??"";return s&&typeof o=="string"&&o.includes("cloudfunctions.net")?`/${s.toLowerCase()}${r}`:r}function me(n){if(typeof n=="string")return n;if(Array.isArray(n)){let e=n[0];return typeof e=="string"?e:void 0}}function oe(n){return !!n&&typeof n=="object"&&n.__authExtension===true}function Ne(n){return n.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function J(n,e="docId",t=false){if(typeof n!="string"||!n.trim())return {rawPath:n??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=n.split("/").map(T=>T.trim()).filter(Boolean);if(r.length===0)return {rawPath:n,collectionId:n,collectionPath:n,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let T=r[0];return {rawPath:n,collectionId:T,collectionPath:T,parentKeys:[],documentPathTemplate:t?null:`${T}/{${e}}`,hasTemplate:n.includes("{")&&n.includes("}")}}let s=r.length%2===0,o=s?r.slice(0,-1):r,i=o[o.length-1],a=o.join("/"),y=o.slice(0,-1).map(Ne).filter(T=>T!==null),S=s?r.join("/"):`${a}/{${e}}`;return {rawPath:n,collectionId:i,collectionPath:a,parentKeys:y,documentPathTemplate:S,hasTemplate:true}}function He(n){if(typeof n!="function")return [];let t=n.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!t?.[1])return [];let r=t[1].split(",").map(s=>s.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function je(n){let e=n?.documentKey??"docId",t=!!n?.isGroup,r=J(typeof n?.path=="string"?n.path:"",e,t),s=r.parentKeys.length>0?r.parentKeys:t?He(n?.refCb):[],o=[n?.documentKey,n?.pathKey,n?.createdKey,n?.updatedKey].filter(a=>typeof a=="string"),i=n?.history&&typeof n.history=="object"?n.history:void 0;return {schema:n?.schema,_systemKeys:o,_pathKey:n?.pathKey??null,_isGroup:t,_createdKey:n?.createdKey??null,_parentKeys:s,_documentPathTemplate:r.documentPathTemplate,_collectionId:typeof n?.path=="string"?r.collectionId:null,relationalKeys:n?.relationalKeys,_historyConfig:i,_historySubcollection:i?.enabled?i.subcollection??"history":void 0,_collectionPath:typeof n?.path=="string"?r.collectionPath:null}}function be(n,e){let t=je(n),r,s=()=>{let o=r??(r=e());if(!o){let i=t._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${i}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return o};return new Proxy(t,{get(o,i){return typeof i=="string"&&i in t?t[i]:s()[i]},has(o,i){return typeof i=="string"&&i in t?true:i in s()}})}function X(n,e,t=new WeakSet,r=0){if(n==null)return null;if(typeof n=="object"&&typeof n.toDate=="function")return n.toDate().toISOString();if(n instanceof Date)return n.toISOString();if(Buffer.isBuffer(n))return n.toString("base64");if(n instanceof Uint8Array)return Buffer.from(n).toString("base64");if(typeof n=="object"&&"latitude"in n&&"longitude"in n){let s=n;return e?.stringifyArrays===false?{lat:s.latitude,lng:s.longitude}:JSON.stringify({lat:s.latitude,lng:s.longitude})}if(Array.isArray(n)){let s=n.map(o=>X(o,e,t,r+1));return e?.stringifyArrays===false?s:JSON.stringify(s)}return typeof n=="object"&&n!==null&&e?.stringifyArrays===false?ie(n,new Set,{},t,r+1):n}var we=32,Fe=5e3;function Te(n,e,t,r=new WeakSet,s=0){if(s>we){t[e||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(n)){t[e||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(n);for(let[o,i]of Object.entries(n)){if(Object.keys(t).length>=Fe)break;let a=e?`${e}__${o}`:o;i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!Buffer.isBuffer(i)&&!(i instanceof Uint8Array)&&typeof i.toDate!="function"&&!("latitude"in i&&"longitude"in i)?Te(i,a,t,r,s+1):t[a]=X(i);}r.delete(n);}function ie(n,e,t,r=new WeakSet,s=0){if(s>we)return {__truncated:true};if(r.has(n))return {__cycle:true};r.add(n);let o={};for(let[i,a]of Object.entries(n)){if(e.has(i))continue;let c=t[i]??i;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)?o[c]=ie(a,new Set,{},r,s+1):o[c]=X(a,{stringifyArrays:false},r,s+1);}return r.delete(n),o}function ae(n){let e={};for(let[t,r]of Object.entries(n)){let s=r;if(typeof s=="string"){let a=s.trim();if(a.startsWith("[")&&a.endsWith("]")||a.startsWith("{")&&a.endsWith("}"))try{s=JSON.parse(a);}catch{}}if(t.startsWith("__")||!t.includes("__")){e[t]=s;continue}let o=t.split("__").filter(Boolean),i=e;for(let a=0;a<o.length-1;a++){let c=o[a];(!i[c]||typeof i[c]!="object"||Array.isArray(i[c]))&&(i[c]={}),i=i[c];}i[o[o.length-1]]=s;}return e}function Q(n,e){let t=e?.flat!==false,r;if(t){let s=new Set(e?.exclude),o=e?.columnMap??{},i={};Te(n,"",i),r={};for(let[a,c]of Object.entries(i)){if(s.has(a))continue;let y=a.split("__")[0];if(y!==a&&s.has(y))continue;let S=o[a]??(a.includes("__")?o[a.split("__").pop()]:void 0)??a;r[S]=c;}}else {let s=new Set(e?.exclude),o=e?.columnMap??{};r=ie(n,s,o);}return typeof e?.transformDoc=="function"&&(r=e.transformDoc(r)),r}function L(n,e,t){return `<!DOCTYPE html>
1
+ 'use strict';var async_hooks=require('async_hooks');require('firebase-admin/firestore'),require('crypto');var Te=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});function Le(n){let e=[],t=n.replace(/[.*+?^${}()|[\]\\]/g,r=>r===":"?r:`\\${r}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(r,o)=>(e.push(o),"([^/]+)"));return {pattern:new RegExp(`^${t}$`),paramNames:e}}function Ke(n){let e=n.path??n.url??"/",t=e.indexOf("?");return t===-1?e:e.slice(0,t)}var J=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(e,t)=>{t.status(404).send("Not Found");};this.errorHandler=(e,t,r)=>{console.error("[MiniRouter]",e),r.status(500).send("Internal Server Error");};}use(e){return this.middlewares.push(e),this}get(e,t){return this.addRoute("GET",e,t)}post(e,t){return this.addRoute("POST",e,t)}put(e,t){return this.addRoute("PUT",e,t)}patch(e,t){return this.addRoute("PATCH",e,t)}delete(e,t){return this.addRoute("DELETE",e,t)}onNotFound(e){return this.notFoundHandler=e,this}onError(e){return this.errorHandler=e,this}addRoute(e,t,r){let{pattern:o,paramNames:s}=Le(t);return this.routes.push({method:e.toUpperCase(),pattern:o,paramNames:s,handler:r}),this}async handle(e,t){let r=(e.method??"GET").toUpperCase(),o=Ke(e),s=null,i={};for(let p of this.routes){if(p.method!==r)continue;let b=o.match(p.pattern);if(b){s=p,i={},p.paramNames.forEach((m,A)=>{i[m]=decodeURIComponent(b[A+1]??"");});break}}let c=Object.assign(e,{params:i}),a=s?s.handler:this.notFoundHandler;try{await this.runMiddlewareChain(c,t,a);}catch(p){this.errorHandler(p,e,t);}}async runMiddlewareChain(e,t,r){let o=0,s=async()=>{if(o<this.middlewares.length){let i=this.middlewares[o++];await i(e,t,s);}else await r(e,t);};await s();}};function L(n,e,t){let r=e==="/"?"":e.replace(/\/$/,"");if(process.env.FUNCTIONS_EMULATOR==="true"){let i=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",c=t??process.env.FUNCTION_REGION??"us-central1",a=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${i}/${c}/${a}${r}`}let o=process.env.K_SERVICE,s=n?.hostname??n?.headers?.host??"";return o&&typeof s=="string"&&s.includes("cloudfunctions.net")?`/${o.toLowerCase()}${r}`:r}function Se(n){if(typeof n=="string")return n;if(Array.isArray(n)){let e=n[0];return typeof e=="string"?e:void 0}}function ie(n){return !!n&&typeof n=="object"&&n.__authExtension===true}var ae=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),ce=globalThis;ce[ae]??(ce[ae]=new async_hooks.AsyncLocalStorage);function Ue(n,e){if(!e.includes("."))return n[e];let t=n;for(let r of e.split(".")){if(!t||typeof t!="object")return;t=t[r];}return t}function xe(n,e){for(let t of e){let r=Ue(n,t);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function ke(n,e){if(e===false)return;let t=n?.req?.header;if(typeof t!="function")return;let r=t.call(n.req,e);return typeof r=="string"&&r.length>0?r:void 0}function Ve(n={}){let e=n.contextKeys??["user","docsUser"],t=n.userIdFields??["uid","id","sub"],r=n.userEmailFields??["email"],o=n.reasonHeader===void 0?"x-history-reason":n.reasonHeader,s=n.commentHeader===void 0?"x-history-comment":n.commentHeader,i=n.extras;return c=>{let a=null,p=c?.get;if(typeof p=="function")for(let P of e){let k=p.call(c,P);if(k&&typeof k=="object"){a=k;break}}let b=ke(c,o),m=ke(c,s),A=i?i(c,a):void 0;return a?{userId:xe(a,t),userEmail:xe(a,r),...b!==void 0?{reason:b}:{},...m!==void 0?{comment:m}:{},...A?{extras:A}:{}}:b===void 0&&m===void 0&&!A?null:{...b!==void 0?{reason:b}:{},...m!==void 0?{comment:m}:{},...A?{extras:A}:{}}}}Ve();var Re="_historyMeta";function le(n){if(!n?.enabled||n.shadow===false||n.meta&&n.shadow===void 0)return null;let e=n.shadow,t=typeof e=="string"&&e.trim().length>0?e.trim():typeof e=="object"&&e!==null&&typeof e.key=="string"&&e.key.trim().length>0?e.key.trim():Re,r=typeof e=="object"&&e!==null?e.fields:void 0;return {key:t,fields:{userId:r?.userId??"userId",userEmail:r?.userEmail??"userEmail",reason:r?.reason??"reason",comment:r?.comment??"comment",extras:r?.extras??"extras"}}}function B(n){return le(n)?.key??null}function Ae(n){let e=le(n);return e?[e.key]:[]}function Ge(n){return n.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function Y(n,e="docId",t=false){if(typeof n!="string"||!n.trim())return {rawPath:n??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=n.split("/").map(m=>m.trim()).filter(Boolean);if(r.length===0)return {rawPath:n,collectionId:n,collectionPath:n,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let m=r[0];return {rawPath:n,collectionId:m,collectionPath:m,parentKeys:[],documentPathTemplate:t?null:`${m}/{${e}}`,hasTemplate:n.includes("{")&&n.includes("}")}}let o=r.length%2===0,s=o?r.slice(0,-1):r,i=s[s.length-1],c=s.join("/"),p=s.slice(0,-1).map(Ge).filter(m=>m!==null),b=o?r.join("/"):`${c}/{${e}}`;return {rawPath:n,collectionId:i,collectionPath:c,parentKeys:p,documentPathTemplate:b,hasTemplate:true}}function Ye(n){if(typeof n!="function")return [];let t=n.toString().match(/^\s*(?:function\s*\w*\s*)?\(([^)]*)\)/);if(!t?.[1])return [];let r=t[1].split(",").map(o=>o.trim().replace(/\s*[:=].*$/,"").trim()).filter(Boolean);return r.length<=2?[]:r.slice(1,-1)}function Xe(n){let e=n?.documentKey??"docId",t=!!n?.isGroup,r=Y(typeof n?.path=="string"?n.path:"",e,t),o=r.parentKeys.length>0?r.parentKeys:t?Ye(n?.refCb):[],s=[n?.documentKey,n?.pathKey,n?.createdKey,n?.updatedKey].filter(c=>typeof c=="string"),i=n?.history&&typeof n.history=="object"?n.history:void 0;return {schema:n?.schema,_systemKeys:s,_pathKey:n?.pathKey??null,_isGroup:t,_createdKey:n?.createdKey??null,_parentKeys:o,_documentPathTemplate:r.documentPathTemplate,_collectionId:typeof n?.path=="string"?r.collectionId:null,relationalKeys:n?.relationalKeys,_historyConfig:i,_historyShadowKey:B(i),_historyIdentityKeys:Ae(i),_historySubcollection:i?.enabled?i.subcollection??"history":void 0,_collectionPath:typeof n?.path=="string"?r.collectionPath:null}}function Pe(n,e){let t=Xe(n),r,o=()=>{let s=r??(r=e());if(!s){let i=t._collectionPath||"unknown";throw new Error(`[makeLazyRepo] Failed to resolve repository for path "${i}". The repository mapping resolved to undefined. This almost always indicates a circular import where the repository was exported as undefined.`)}return s};return new Proxy(t,{get(s,i){return typeof i=="string"&&i in t?t[i]:o()[i]},has(s,i){return typeof i=="string"&&i in t?true:i in o()}})}function ee(n,e,t=new WeakSet,r=0){if(n==null)return null;if(typeof n=="object"&&typeof n.toDate=="function")return n.toDate().toISOString();if(n instanceof Date)return n.toISOString();if(Buffer.isBuffer(n))return n.toString("base64");if(n instanceof Uint8Array)return Buffer.from(n).toString("base64");if(typeof n=="object"&&"latitude"in n&&"longitude"in n){let o=n;return e?.stringifyArrays===false?{lat:o.latitude,lng:o.longitude}:JSON.stringify({lat:o.latitude,lng:o.longitude})}if(Array.isArray(n)){let o=n.map(s=>ee(s,e,t,r+1));return e?.stringifyArrays===false?o:JSON.stringify(o)}return typeof n=="object"&&n!==null&&e?.stringifyArrays===false?fe(n,new Set,{},t,r+1):n}var Oe=32,et=5e3;function ve(n,e,t,r=new WeakSet,o=0){if(o>Oe){t[e||"_truncated"]=JSON.stringify({__truncated:true});return}if(r.has(n)){t[e||"_cycle"]=JSON.stringify({__cycle:true});return}r.add(n);for(let[s,i]of Object.entries(n)){if(Object.keys(t).length>=et)break;let c=e?`${e}__${s}`:s;i!=null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)&&!Buffer.isBuffer(i)&&!(i instanceof Uint8Array)&&typeof i.toDate!="function"&&!("latitude"in i&&"longitude"in i)?ve(i,c,t,r,o+1):t[c]=ee(i);}r.delete(n);}function fe(n,e,t,r=new WeakSet,o=0){if(o>Oe)return {__truncated:true};if(r.has(n))return {__cycle:true};r.add(n);let s={};for(let[i,c]of Object.entries(n)){if(e.has(i))continue;let a=t[i]??i;c!=null&&typeof c=="object"&&!Array.isArray(c)&&!(c instanceof Date)&&!Buffer.isBuffer(c)&&!(c instanceof Uint8Array)&&typeof c.toDate!="function"&&!("latitude"in c&&"longitude"in c)?s[a]=fe(c,new Set,{},r,o+1):s[a]=ee(c,{stringifyArrays:false},r,o+1);}return r.delete(n),s}function pe(n){let e={};for(let[t,r]of Object.entries(n)){let o=r;if(typeof o=="string"){let c=o.trim();if(c.startsWith("[")&&c.endsWith("]")||c.startsWith("{")&&c.endsWith("}"))try{o=JSON.parse(c);}catch{}}if(t.startsWith("__")||!t.includes("__")){e[t]=o;continue}let s=t.split("__").filter(Boolean),i=e;for(let c=0;c<s.length-1;c++){let a=s[c];(!i[a]||typeof i[a]!="object"||Array.isArray(i[a]))&&(i[a]={}),i=i[a];}i[s[s.length-1]]=o;}return e}function W(n,e){let t=e?.flat!==false,r;if(t){let o=new Set(e?.exclude),s=e?.columnMap??{},i=n;if(o.size>0){let a=false,p={};for(let[b,m]of Object.entries(n)){if(o.has(b)){a=true;continue}p[b]=m;}a&&(i=p);}let c={};ve(i,"",c),r={};for(let[a,p]of Object.entries(c)){if(o.has(a))continue;let b=a.split("__")[0];if(b!==a&&o.has(b))continue;let m=s[a]??(a.includes("__")?s[a.split("__").pop()]:void 0)??a;r[m]=p;}}else {let o=new Set(e?.exclude),s=e?.columnMap??{};r=fe(n,o,s);}return typeof e?.transformDoc=="function"&&(r=e.transformDoc(r)),r}function K(n,e,t){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>${n} \u2014 Sync Admin</title>
@@ -28,84 +28,84 @@
28
28
  <nav><a href="${e}/">\u2190 Dashboard</a></nav>
29
29
  <h1>${n}</h1>
30
30
  ${t}
31
- </body></html>`}function q(n,e,t=200){n.status(t).set("Content-Type","text/html; charset=utf-8").send(e);}function W(n,e,t=200){n.status(t).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function ee(n){return (n.headers?.accept??"").includes("application/json")}function ce(n,e,t,r,s,o,i,a){let c=(s.basePath??"/").replace(/\/$/,"")||"",y=s.featuresFlag??{},S=me(s.httpsOptions?.region),T=Array.isArray(e)?e:[e],O=n?.rawMapping,P=[],k=Object.keys(o??{}),m=k.length>0,M=Object.keys(O||n),$=m?k.filter(u=>M.includes(u)||u in n):M;for(let u of $){let d=o[u],g=O?be(O[u],()=>n[u]):n[u],l=!!g._isGroup,w=g._collectionPath,A=typeof w=="string"&&w.includes("/");if(!m&&l&&!d?.triggerPath&&!A)continue;let f=d?.adapters&&d.adapters.length>0?T.filter(C=>d.adapters.includes(C.name)):T;P.push({name:u,schema:g.schema??null,documentKey:g._systemKeys?.[0]??g.documentKey??"docId",tableName:d?.tableName??u,isGroup:l,repoCfg:d,repo:g,adapters:f});}let D=new V;if(s.auth)if(oe(s.auth)){let u=s.auth;for(let d of u.routes){let g=`${c}${d.path}`;d.method==="GET"?D.get(g,d.handler):D.post(g,d.handler);}D.use(u.middleware);}else if(typeof s.auth=="function")D.use(s.auth);else {let u=s.auth.realm??"Sync Admin",d="Basic "+Buffer.from(`${s.auth.username}:${s.auth.password}`).toString("base64");D.use((g,l,w)=>{if((g.headers?.authorization??"")!==d){l.status(401).set("WWW-Authenticate",`Basic realm="${u}"`).set("Content-Type","text/plain").send("Unauthorized");return}w();});}return D.get(`${c}/`,(u,d)=>{let g=B(u,c,S),l=P.map(f=>{let C=[];y.healthCheck&&C.push(`<a class="btn" href="${g}/${f.name}/health">Health</a>`),y.manualSync&&C.push(`<a class="btn btn-primary" href="${g}/${f.name}/force-sync">Force Sync</a>`);let h=f.adapters.map(R=>`<span class="badge badge-ok">${R.name}</span>`).join(" ");return `<tr>
32
- <td><strong>${f.name}</strong></td>
33
- <td>${f.tableName}</td>
34
- <td>${h||'<span class="badge badge-warn">none</span>'}</td>
35
- <td>${f.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
36
- <td>${f.schema?"\u2713":"\u2717"}</td>
37
- <td>${C.join(" ")}</td>
31
+ </body></html>`}function q(n,e,t=200){n.status(t).set("Content-Type","text/html; charset=utf-8").send(e);}function U(n,e,t=200){n.status(t).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function te(n){return (n.headers?.accept??"").includes("application/json")}function ye(n,e,t,r,o,s,i,c){let a=(o.basePath??"/").replace(/\/$/,"")||"",p=o.featuresFlag??{},b=Se(o.httpsOptions?.region),m=Array.isArray(e)?e:[e],A=n?.rawMapping,P=[],k=Object.keys(s??{}),g=k.length>0,H=Object.keys(A||n),M=g?k.filter(u=>H.includes(u)||u in n):H;for(let u of M){let d=s[u],h=A?Pe(A[u],()=>n[u]):n[u],l=!!h._isGroup,S=h._collectionPath,E=typeof S=="string"&&S.includes("/");if(!g&&l&&!d?.triggerPath&&!E)continue;let y=d?.adapters&&d.adapters.length>0?m.filter(w=>d.adapters.includes(w.name)):m,R=typeof h._historyShadowKey=="string"?h._historyShadowKey:B(h._historyConfig);P.push({name:u,schema:h.schema??null,documentKey:h._systemKeys?.[0]??h.documentKey??"docId",tableName:d?.tableName??u,isGroup:l,repoCfg:d,repo:h,adapters:y,historyShadowKey:R});}let D=new J;if(o.auth)if(ie(o.auth)){let u=o.auth;for(let d of u.routes){let h=`${a}${d.path}`;d.method==="GET"?D.get(h,d.handler):D.post(h,d.handler);}D.use(u.middleware);}else if(typeof o.auth=="function")D.use(o.auth);else {let u=o.auth.realm??"Sync Admin",d="Basic "+Buffer.from(`${o.auth.username}:${o.auth.password}`).toString("base64");D.use((h,l,S)=>{if((h.headers?.authorization??"")!==d){l.status(401).set("WWW-Authenticate",`Basic realm="${u}"`).set("Content-Type","text/plain").send("Unauthorized");return}S();});}return D.get(`${a}/`,(u,d)=>{let h=L(u,a,b),l=P.map(y=>{let R=[];p.healthCheck&&R.push(`<a class="btn" href="${h}/${y.name}/health">Health</a>`),p.manualSync&&R.push(`<a class="btn btn-primary" href="${h}/${y.name}/force-sync">Force Sync</a>`);let w=y.adapters.map(C=>`<span class="badge badge-ok">${C.name}</span>`).join(" ");return `<tr>
32
+ <td><strong>${y.name}</strong></td>
33
+ <td>${y.tableName}</td>
34
+ <td>${w||'<span class="badge badge-warn">none</span>'}</td>
35
+ <td>${y.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
36
+ <td>${y.schema?"\u2713":"\u2717"}</td>
37
+ <td>${R.join(" ")}</td>
38
38
  </tr>`}).join(`
39
- `),w=y.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${g}/config-check">\u2699 Config Check</a></p>`:"",A=L("Sync Dashboard",g,`<div class="card">
39
+ `),S=p.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${h}/config-check">\u2699 Config Check</a></p>`:"",E=K("Sync Dashboard",h,`<div class="card">
40
40
  <table>
41
41
  <thead><tr><th>Repository</th><th>Target Name</th><th>Adapters</th><th>Type</th><th>Schema</th><th>Actions</th></tr></thead>
42
42
  <tbody>${l}</tbody>
43
43
  </table>
44
- ${w}
45
- </div>`);q(d,A);}),D.get(`${c}`,(u,d)=>{let g=B(u,c,S);d.status(302).set("Location",`${g}/`).send("");}),y.healthCheck&&D.get(`${c}/:repoName/health`,async(u,d)=>{let g=B(u,c,S),l=P.find(h=>h.name===u.params.repoName);if(!l){q(d,L("Not Found",g,`<p>Unknown repo: ${u.params.repoName}</p>`),404);return}let w=[];for(let h of l.adapters)if(typeof h.healthCheck=="function"){let R=await h.healthCheck({targetName:l.tableName,primaryKey:l.documentKey,schema:l.schema??void 0,repoConfig:l.repoCfg});w.push({adapterName:h.name,health:R});}else try{let R=await h.targetExists(l.tableName);w.push({adapterName:h.name,health:{healthy:R,targetName:l.tableName,targetExists:R,error:R?null:`Target "${l.tableName}" does not exist`}});}catch(R){w.push({adapterName:h.name,health:{healthy:false,targetName:l.tableName,targetExists:false,error:R?.message??String(R)}});}let A=w.length>0&&w.every(h=>h.health.healthy);if(ee(u)){W(d,{repo:l.name,targetName:l.tableName,healthy:A,adapters:w.map(h=>({name:h.adapterName,...h.health}))});return}let f=h=>{let{adapterName:R,health:v}=h,N=v.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',I="",p=v.details;if(p?.expected&&Array.isArray(p.expected)){let b=p.expected,E=new Set(p.actual??[]),x=p.extra??[],_=b.map(H=>{let U=E.has(H.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${H.name}</td><td>${H.type}</td><td>${H.nullable?"Yes":"No"}</td><td>${H.isPrimaryKey?"\u2713":""}</td><td>${U}</td></tr>`}).join(`
46
- `),F=x.map(H=>`<tr><td>${H}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
44
+ ${S}
45
+ </div>`);q(d,E);}),D.get(`${a}`,(u,d)=>{let h=L(u,a,b);d.status(302).set("Location",`${h}/`).send("");}),p.healthCheck&&D.get(`${a}/:repoName/health`,async(u,d)=>{let h=L(u,a,b),l=P.find(w=>w.name===u.params.repoName);if(!l){q(d,K("Not Found",h,`<p>Unknown repo: ${u.params.repoName}</p>`),404);return}let S=[];for(let w of l.adapters)if(typeof w.healthCheck=="function"){let C=await w.healthCheck({targetName:l.tableName,primaryKey:l.documentKey,schema:l.schema??void 0,repoConfig:l.repoCfg});S.push({adapterName:w.name,health:C});}else try{let C=await w.targetExists(l.tableName);S.push({adapterName:w.name,health:{healthy:C,targetName:l.tableName,targetExists:C,error:C?null:`Target "${l.tableName}" does not exist`}});}catch(C){S.push({adapterName:w.name,health:{healthy:false,targetName:l.tableName,targetExists:false,error:C?.message??String(C)}});}let E=S.length>0&&S.every(w=>w.health.healthy);if(te(u)){U(d,{repo:l.name,targetName:l.tableName,healthy:E,adapters:S.map(w=>({name:w.adapterName,...w.health}))});return}let y=w=>{let{adapterName:C,health:O}=w,$=O.healthy?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',I="",f=O.details;if(f?.expected&&Array.isArray(f.expected)){let T=f.expected,v=new Set(f.actual??[]),x=f.extra??[],_=T.map(F=>{let Q=v.has(F.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${F.name}</td><td>${F.type}</td><td>${F.nullable?"Yes":"No"}</td><td>${F.isPrimaryKey?"\u2713":""}</td><td>${Q}</td></tr>`}).join(`
46
+ `),N=x.map(F=>`<tr><td>${F}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
47
47
  `);I=`<h2>Columns</h2>
48
48
  <table>
49
49
  <thead><tr><th>Column</th><th>SQL Type</th><th>Nullable</th><th>PK</th><th>Status</th></tr></thead>
50
- <tbody>${_}${F}</tbody>
51
- </table>`;}else p?.numberOfDocuments!==void 0&&(I=`<h2>Index Stats</h2>
50
+ <tbody>${_}${N}</tbody>
51
+ </table>`;}else f?.numberOfDocuments!==void 0&&(I=`<h2>Index Stats</h2>
52
52
  <table>
53
- <tr><th>Documents Count</th><td>${p.numberOfDocuments}</td></tr>
54
- <tr><th>Indexing in Progress</th><td>${p.isIndexing?'<span class="badge badge-warn">Yes</span>':'<span class="badge badge-ok">No</span>'}</td></tr>
55
- <tr><th>Primary Key</th><td><code>${p.primaryKey??"default"}</code></td></tr>
53
+ <tr><th>Documents Count</th><td>${f.numberOfDocuments}</td></tr>
54
+ <tr><th>Indexing in Progress</th><td>${f.isIndexing?'<span class="badge badge-warn">Yes</span>':'<span class="badge badge-ok">No</span>'}</td></tr>
55
+ <tr><th>Primary Key</th><td><code>${f.primaryKey??"default"}</code></td></tr>
56
56
  </table>`);return `<div class="card" style="margin-top:1rem">
57
- <h2>Adapter: <code>${R}</code> ${N}</h2>
58
- <p>Target: <code>${v.targetName}</code> ${v.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
59
- ${v.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${v.error}</p>`:""}
57
+ <h2>Adapter: <code>${C}</code> ${$}</h2>
58
+ <p>Target: <code>${O.targetName}</code> ${O.targetExists?"":'<span class="badge badge-err">NOT FOUND</span>'}</p>
59
+ ${O.error?`<p class="badge badge-err" style="margin-top:.5rem">Error: ${O.error}</p>`:""}
60
60
  ${I}
61
- </div>`},C=L(`Health: ${l.name}`,g,`<div class="card">
62
- <p>Overall status for <strong>${l.name}</strong>: ${A?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
61
+ </div>`},R=K(`Health: ${l.name}`,h,`<div class="card">
62
+ <p>Overall status for <strong>${l.name}</strong>: ${E?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Issues detected</span>'}</p>
63
63
  </div>
64
- ${w.map(f).join(`
65
- `)}`);q(d,C);}),y.manualSync&&(D.get(`${c}/:repoName/force-sync`,(u,d)=>{let g=B(u,c,S),l=P.find(A=>A.name===u.params.repoName);if(!l){q(d,L("Not Found",g,`<p>Unknown repo: ${u.params.repoName}</p>`),404);return}let w=L(`Force Sync: ${l.name}`,g,`<div class="card">
64
+ ${S.map(y).join(`
65
+ `)}`);q(d,R);}),p.manualSync&&(D.get(`${a}/:repoName/force-sync`,(u,d)=>{let h=L(u,a,b),l=P.find(E=>E.name===u.params.repoName);if(!l){q(d,K("Not Found",h,`<p>Unknown repo: ${u.params.repoName}</p>`),404);return}let S=K(`Force Sync: ${l.name}`,h,`<div class="card">
66
66
  <p>This will read <strong>all</strong> documents from the <code>${l.name}</code> Firestore collection
67
- and upsert them into all active target storage adapters (${l.adapters.map(A=>A.name).join(", ")}).</p>
67
+ and upsert them into all active target storage adapters (${l.adapters.map(E=>E.name).join(", ")}).</p>
68
68
  <p class="muted" style="margin:.75rem 0">This may take a while for large collections.</p>
69
- <form method="POST" action="${g}/${l.name}/force-sync">
69
+ <form method="POST" action="${h}/${l.name}/force-sync">
70
70
  <button type="submit" class="btn btn-primary">Start Force Sync</button>
71
71
  </form>
72
- </div>`);q(d,w);}),D.post(`${c}/:repoName/force-sync`,async(u,d)=>{let g=B(u,c,S),l=P.find(p=>p.name===u.params.repoName);if(!l){W(d,{error:`Unknown repo: ${u.params.repoName}`},404);return}let w=l.repo.ref;if(!w){W(d,{error:`No collection reference for "${l.name}"`},400);return}let A=0,f=0,C=[],h=500,R=w.limit(h),v=null;try{for(;;){let b=await(v?R.startAfter(v):R).get();if(b.empty)break;for(let E of b.docs){let x=E.data(),_=String(x[l.documentKey]??E.id),F=Q(x,{exclude:l.repoCfg?.exclude,columnMap:l.repoCfg?.columnMap,flat:l.repoCfg?.flat,transformDoc:l.repoCfg?.transformDoc});try{await r({operation:"UPSERT",repoName:l.name,docId:_,data:F,timestamp:new Date().toISOString()}),A++;}catch(H){f++;let U=H?.message??String(H);console.error(`[ForceSync:${l.name}] doc=${_} failed:`,H),C.length<5&&C.push(`${_}: ${U}`);}}if(v=b.docs[b.docs.length-1],b.docs.length<h)break}for(let p of l.adapters){let b=`${l.name}:${p.name}`,E=t.get(b)??t.get(l.name);E&&await E.flush();}}catch(p){if(ee(u)){W(d,{error:p?.message??String(p),synced:A,errors:f},500);return}q(d,L(`Force Sync: ${l.name}`,g,`<div class="card">
73
- <p class="badge badge-err">Error: ${p?.message??String(p)}</p>
74
- <p>Synced ${A} docs before failure (${f} errors).</p>
75
- </div>`),500);return}if(ee(u)){W(d,{repo:l.name,table:l.tableName,synced:A,errors:f,...C.length>0&&{errorSamples:C}});return}let N=C.length>0?`<details style="margin-top:1rem"><summary>First ${C.length} error(s)</summary>
76
- <pre style="white-space:pre-wrap">${C.map(p=>p.replace(/[<>&]/g,b=>`&#${b.charCodeAt(0)};`)).join(`
72
+ </div>`);q(d,S);}),D.post(`${a}/:repoName/force-sync`,async(u,d)=>{let h=L(u,a,b),l=P.find(f=>f.name===u.params.repoName);if(!l){U(d,{error:`Unknown repo: ${u.params.repoName}`},404);return}let S=l.repo.ref;if(!S){U(d,{error:`No collection reference for "${l.name}"`},400);return}let E=0,y=0,R=[],w=500,C=S.limit(w),O=null;try{for(;;){let T=await(O?C.startAfter(O):C).get();if(T.empty)break;let v=l.historyShadowKey?Array.from(new Set([...l.repoCfg?.exclude??[],l.historyShadowKey])):l.repoCfg?.exclude;for(let x of T.docs){let _=x.data(),N=String(_[l.documentKey]??x.id),F=W(_,{exclude:v,columnMap:l.repoCfg?.columnMap,flat:l.repoCfg?.flat,transformDoc:l.repoCfg?.transformDoc});try{await r({operation:"UPSERT",repoName:l.name,docId:N,data:F,timestamp:new Date().toISOString()}),E++;}catch(Q){y++;let Be=Q?.message??String(Q);console.error(`[ForceSync:${l.name}] doc=${N} failed:`,Q),R.length<5&&R.push(`${N}: ${Be}`);}}if(O=T.docs[T.docs.length-1],T.docs.length<w)break}for(let f of l.adapters){let T=`${l.name}:${f.name}`,v=t.get(T)??t.get(l.name);v&&await v.flush();}}catch(f){if(te(u)){U(d,{error:f?.message??String(f),synced:E,errors:y},500);return}q(d,K(`Force Sync: ${l.name}`,h,`<div class="card">
73
+ <p class="badge badge-err">Error: ${f?.message??String(f)}</p>
74
+ <p>Synced ${E} docs before failure (${y} errors).</p>
75
+ </div>`),500);return}if(te(u)){U(d,{repo:l.name,table:l.tableName,synced:E,errors:y,...R.length>0&&{errorSamples:R}});return}let $=R.length>0?`<details style="margin-top:1rem"><summary>First ${R.length} error(s)</summary>
76
+ <pre style="white-space:pre-wrap">${R.map(f=>f.replace(/[<>&]/g,T=>`&#${T.charCodeAt(0)};`)).join(`
77
77
 
78
- `)}</pre></details>`:"",I=L(`Force Sync: ${l.name}`,g,`<div class="card">
79
- <p class="badge ${f>0?"badge-warn":"badge-ok"}">${f>0?"Completed with errors":"Complete"}</p>
80
- <p>Synced <strong>${A}</strong> documents to targets (${l.adapters.map(p=>p.name).join(", ")}).</p>
81
- ${f>0?`<p class="badge badge-warn">${f} error(s)</p>`:""}
82
- ${N}
83
- </div>`);q(d,I);})),y.configCheck&&D.get(`${c}/config-check`,async(u,d)=>{let g=B(u,c,S),l=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",w="https://console.cloud.google.com",A=a??"firestore-sync",f=[];for(let p of T)if(p.name==="bigquery")try{await p.targetExists("__nonexistent_health_check__"),f.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(b){let E=b?.message??String(b),x=E.toLowerCase(),_=x.includes("disabled")||x.includes("has not been used")||x.includes("accessnotconfigured"),F=x.includes("permission")||E.includes("403")||x.includes("access denied"),H=x.includes("project")&&x.includes("not found"),U=x.includes("not found")||E.includes("404");_?f.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${l}`,console:`${w}/apis/library/bigquery.googleapis.com?project=${l}`}}):H?f.push({name:"BigQuery Project",category:"bigquery",status:"error",message:E,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${w}/home/dashboard`}}):F?f.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${E}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${w}/iam-admin/iam?project=${l}`}}):U?f.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${E}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${l}:YOUR_DATASET_ID`,console:`${w}/bigquery?project=${l}`}}):f.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(p.name==="meilisearch"||typeof p.checkConnection=="function")try{let b=typeof p.checkConnection=="function"?await p.checkConnection():{healthy:await p.targetExists("__nonexistent__")};f.push({name:"Meilisearch API",category:"meilisearch",status:b.healthy?"ok":"error",message:b.healthy?`Meilisearch is reachable${b.version?` (v${b.version})`:""}`:`Meilisearch connection error: ${b.error??"unknown"}`,...b.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(b){f.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${b?.message??String(b)}`});}for(let p of P)for(let b of p.adapters){let E=b.name==="bigquery"?"bigquery":b.name==="meilisearch"?"meilisearch":"storage";try{let x=await b.targetExists(p.tableName);f.push({name:`[${b.name}] Target: ${p.tableName}`,category:E,status:x?"ok":"warn",message:x?`Target \`${p.tableName}\` exists`:`Target \`${p.tableName}\` does not exist yet`,...!x&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(x){f.push({name:`[${b.name}] Target: ${p.tableName}`,category:E,status:"error",message:x?.message??String(x)});}}if(i)for(let p of P){let b=`${A}-${p.name}`;try{let E=i.topic(b);if(typeof E.exists=="function"){let[x]=await E.exists();f.push({name:`Topic: ${b}`,category:"pubsub",status:x?"ok":"error",message:x?`Topic \`${b}\` exists`:`Topic \`${b}\` does not exist`,...!x&&{fix:{gcloud:`gcloud pubsub topics create ${b} --project=${l}`,console:`${w}/cloudpubsub/topic/list?project=${l}`}}});}else f.push({name:`Topic: ${b}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${b} --project=${l}`,console:`${w}/cloudpubsub/topic/list?project=${l}`}});}catch(E){let x=E?.message??String(E),_=x.includes("disabled")||x.includes("has not been used");if(f.push({name:_?"Pub/Sub API":`Topic: ${b}`,category:"pubsub",status:"error",message:_?"Pub/Sub API is not enabled":x,fix:_?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${l}`,console:`${w}/apis/library/pubsub.googleapis.com?project=${l}`}:{gcloud:`gcloud pubsub topics create ${b} --project=${l}`,console:`${w}/cloudpubsub/topic/list?project=${l}`}}),_)break}}else f.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(ee(u)){let p=f.every(b=>b.status==="ok");W(d,{project:l,healthy:p,checks:f});return}let C=p=>p==="ok"?'<span class="badge badge-ok">OK</span>':p==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',h={bigquery:f.filter(p=>p.category==="bigquery"),meilisearch:f.filter(p=>p.category==="meilisearch"),pubsub:f.filter(p=>p.category==="pubsub"),firestore:f.filter(p=>p.category==="firestore"),storage:f.filter(p=>p.category==="storage")},R=(p,b)=>{if(b.length===0)return "";let E=b.map(x=>{let _="";if(x.fix){let F=[];x.fix.hint&&F.push(`<p class="muted">${x.fix.hint}</p>`),x.fix.gcloud&&F.push(`<pre>$ ${x.fix.gcloud}</pre>`),x.fix.console&&F.push(`<p><a href="${x.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),_=`<div style="margin-top:.5rem">${F.join("")}</div>`;}return `<tr>
84
- <td>${C(x.status)}</td>
78
+ `)}</pre></details>`:"",I=K(`Force Sync: ${l.name}`,h,`<div class="card">
79
+ <p class="badge ${y>0?"badge-warn":"badge-ok"}">${y>0?"Completed with errors":"Complete"}</p>
80
+ <p>Synced <strong>${E}</strong> documents to targets (${l.adapters.map(f=>f.name).join(", ")}).</p>
81
+ ${y>0?`<p class="badge badge-warn">${y} error(s)</p>`:""}
82
+ ${$}
83
+ </div>`);q(d,I);})),p.configCheck&&D.get(`${a}/config-check`,async(u,d)=>{let h=L(u,a,b),l=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",S="https://console.cloud.google.com",E=c??"firestore-sync",y=[];for(let f of m)if(f.name==="bigquery")try{await f.targetExists("__nonexistent_health_check__"),y.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(T){let v=T?.message??String(T),x=v.toLowerCase(),_=x.includes("disabled")||x.includes("has not been used")||x.includes("accessnotconfigured"),N=x.includes("permission")||v.includes("403")||x.includes("access denied"),F=x.includes("project")&&x.includes("not found"),Q=x.includes("not found")||v.includes("404");_?y.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${l}`,console:`${S}/apis/library/bigquery.googleapis.com?project=${l}`}}):F?y.push({name:"BigQuery Project",category:"bigquery",status:"error",message:v,fix:{hint:"The GCP project does not exist or the credentials don't have access to it.",console:`${S}/home/dashboard`}}):N?y.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${v}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",console:`${S}/iam-admin/iam?project=${l}`}}):Q?y.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${v}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${l}:YOUR_DATASET_ID`,console:`${S}/bigquery?project=${l}`}}):y.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}else if(f.name==="meilisearch"||typeof f.checkConnection=="function")try{let T=typeof f.checkConnection=="function"?await f.checkConnection():{healthy:await f.targetExists("__nonexistent__")};y.push({name:"Meilisearch API",category:"meilisearch",status:T.healthy?"ok":"error",message:T.healthy?`Meilisearch is reachable${T.version?` (v${T.version})`:""}`:`Meilisearch connection error: ${T.error??"unknown"}`,...T.error&&{fix:{hint:"Ensure Meilisearch is running and host/apiKey options are valid."}}});}catch(T){y.push({name:"Meilisearch API",category:"meilisearch",status:"error",message:`Meilisearch error: ${T?.message??String(T)}`});}for(let f of P)for(let T of f.adapters){let v=T.name==="bigquery"?"bigquery":T.name==="meilisearch"?"meilisearch":"storage";try{let x=await T.targetExists(f.tableName);y.push({name:`[${T.name}] Target: ${f.tableName}`,category:v,status:x?"ok":"warn",message:x?`Target \`${f.tableName}\` exists`:`Target \`${f.tableName}\` does not exist yet`,...!x&&{fix:{hint:"Target will be auto-created on first sync if autoMigrate is enabled."}}});}catch(x){y.push({name:`[${T.name}] Target: ${f.tableName}`,category:v,status:"error",message:x?.message??String(x)});}}if(i)for(let f of P){let T=`${E}-${f.name}`;try{let v=i.topic(T);if(typeof v.exists=="function"){let[x]=await v.exists();y.push({name:`Topic: ${T}`,category:"pubsub",status:x?"ok":"error",message:x?`Topic \`${T}\` exists`:`Topic \`${T}\` does not exist`,...!x&&{fix:{gcloud:`gcloud pubsub topics create ${T} --project=${l}`,console:`${S}/cloudpubsub/topic/list?project=${l}`}}});}else y.push({name:`Topic: ${T}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${T} --project=${l}`,console:`${S}/cloudpubsub/topic/list?project=${l}`}});}catch(v){let x=v?.message??String(v),_=x.includes("disabled")||x.includes("has not been used");if(y.push({name:_?"Pub/Sub API":`Topic: ${T}`,category:"pubsub",status:"error",message:_?"Pub/Sub API is not enabled":x,fix:_?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${l}`,console:`${S}/apis/library/pubsub.googleapis.com?project=${l}`}:{gcloud:`gcloud pubsub topics create ${T} --project=${l}`,console:`${S}/cloudpubsub/topic/list?project=${l}`}}),_)break}}else y.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(te(u)){let f=y.every(T=>T.status==="ok");U(d,{project:l,healthy:f,checks:y});return}let R=f=>f==="ok"?'<span class="badge badge-ok">OK</span>':f==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',w={bigquery:y.filter(f=>f.category==="bigquery"),meilisearch:y.filter(f=>f.category==="meilisearch"),pubsub:y.filter(f=>f.category==="pubsub"),firestore:y.filter(f=>f.category==="firestore"),storage:y.filter(f=>f.category==="storage")},C=(f,T)=>{if(T.length===0)return "";let v=T.map(x=>{let _="";if(x.fix){let N=[];x.fix.hint&&N.push(`<p class="muted">${x.fix.hint}</p>`),x.fix.gcloud&&N.push(`<pre>$ ${x.fix.gcloud}</pre>`),x.fix.console&&N.push(`<p><a href="${x.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),_=`<div style="margin-top:.5rem">${N.join("")}</div>`;}return `<tr>
84
+ <td>${R(x.status)}</td>
85
85
  <td><strong>${x.name}</strong><br><span class="muted">${x.message}</span>${_}</td>
86
86
  </tr>`}).join(`
87
- `);return `<h2>${p}</h2>
87
+ `);return `<h2>${f}</h2>
88
88
  <table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
89
- <tbody>${E}</tbody></table>`},N=f.every(p=>p.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',I=L("Config Check",g,`<div class="card">
90
- <p>Project: <code>${l}</code> ${N}</p>
91
- ${R("BigQuery",h.bigquery)}
92
- ${R("Meilisearch",h.meilisearch)}
93
- ${R("Pub/Sub",h.pubsub)}
94
- ${R("Other Targets",h.storage)}
95
- ${R("Firestore",h.firestore)}
96
- </div>`);q(d,I);}),async(u,d)=>{await D.handle(u,d);}}var ze="firestore-sync";function Be(n,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${n}". Skipping.`),null)}function Le(n){let e=[n?.documentKey,n?.pathKey,n?.createdKey,n?.updatedKey].filter(s=>typeof s=="string"),t=typeof n?.path=="string"?n.path:null,r=t?J(t,n?.documentKey??"docId"):null;return {isGroup:!!n?.isGroup,documentKey:e[0]??"docId",collectionPath:r?r.collectionPath:null,documentPathTemplate:r&&(!n?.isGroup||r.collectionPath.includes("/"))?r.documentPathTemplate:null}}function qe(n){let e=n?._collectionPath??n?.ref?.path??null,t=typeof n?._documentPathTemplate=="string"?n._documentPathTemplate:null;return {isGroup:!!n?._isGroup,documentKey:n?._systemKeys?.[0]??"docId",collectionPath:e,documentPathTemplate:t&&(!n?._isGroup||e&&e.includes("/"))?t:null}}function le(n,e){let{onDocumentWritten:t}=e.deps.firestoreTriggers,r=e.deps.pubsub,s=e?.topicPrefix??ze,o={},i=new Map;function a(k){let m=i.get(k);return m||(m=r.topic(k),i.set(k,m),m)}async function c(k,m){await a(k).publishMessage({json:m});}let y=n?.rawMapping,S=y?Object.entries(y).map(([k,m])=>[k,Le(m)]):Object.entries(n).map(([k,m])=>[k,qe(m)]),T=e?.repos,P=Object.keys(T??{}).length>0;for(let[k,m]of S){if(P&&(!T||!(k in T)))continue;let M=T?.[k],$;if(m.isGroup){let w=M?.triggerPath??m.documentPathTemplate;if(!w){console.warn(`[SyncTriggers] Skipping collection-group repo "${k}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}$=w;}else $=M?.triggerPath??m.documentPathTemplate??Be(k,m.collectionPath);if(!$)continue;let D=m.documentKey,u=`${s}-${k}`,d={...e?.triggerOptions,...M?.triggerOptions},g=Object.keys(d).length>0,l=async w=>{let A=w.data?.before,f=w.data?.after;if(!A&&!f)return;let C=!!A?.exists,h=!!f?.exists;if(!C&&h){let R=f.data();if(!R)return;let v=String(R[D]??f.id),N=Q(R,{exclude:M?.exclude,columnMap:M?.columnMap,flat:M?.flat,transformDoc:M?.transformDoc}),I={operation:"INSERT",repoName:k,docId:v,data:N,timestamp:new Date().toISOString(),version:Date.now()};await c(u,I);}else if(C&&h){let R=f.data();if(!R)return;let v=String(R[D]??f.id),N=Q(R,{exclude:M?.exclude,columnMap:M?.columnMap,flat:M?.flat,transformDoc:M?.transformDoc}),I={operation:"UPSERT",repoName:k,docId:v,data:N,timestamp:new Date().toISOString(),version:Date.now()};await c(u,I);}else if(C&&!h){let R=A.data(),v=String(R?.[D]??A.id),N={operation:"DELETE",repoName:k,docId:v,data:null,timestamp:new Date().toISOString(),version:Date.now()};await c(u,N);}};o[`${k}_onSync`]=t(g?{document:$,...d}:$,l);}return o}var j="__sync_version";var Qe={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 te(n){let e=n,t=e._zod?.def?.type;if(t)return Qe[t]??`Zod${t.charAt(0).toUpperCase()}${t.slice(1)}`;let r=e._def?.typeName;return r||""}function Se(n){let e=n;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function ue(n){let e=n;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 We=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function xe(n){let e=n,t=false;for(;;){let r=te(e);if(!We.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(t=true);let s=Se(e);if(!s)break;e=s;}return {inner:e,nullable:t}}var Re={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function Ke(n){let{inner:e}=xe(n);return Re[te(e)]??"json"}function ke(n,e,t,r,s,o,i,a){for(let[c,y]of Object.entries(n)){let S=t?`${t}__${c}`:c;if(s.has(c)||s.has(S))continue;let{inner:T,nullable:O}=xe(y),P=te(T),k=r||O;if(P==="ZodObject"){let D=ue(T);ke(D,e,S,k,s,o,i,a);continue}let m=Re[P]??"json",M=S===i||c===i,$=o[S]??o[c]??S;a.push({name:$,sqlType:e.mapType(m),nullable:M?false:k,isPrimaryKey:M});}}function z(n,e,t={}){let{primaryKey:r,exclude:s=[],columnMap:o={}}=t,i=new Set(s),a=ue(n),c=[];return ke(a,e,"",false,i,o,r,c),c.some(y=>y.name===j)||c.push({name:j,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),c}function ne(n){let e=n.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function Ae(n,e){let t=ne(n),r=ne(e);return t===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[t]?.includes(r)??false}var de=class{constructor(){this.name="bigquery";}mapType(e){switch(e){case "string":return "STRING";case "number":return "FLOAT64";case "bigint":return "INT64";case "boolean":return "BOOL";case "timestamp":return "TIMESTAMP";case "json":return "JSON";case "text":return "STRING"}}quoteIdentifier(e){return "`"+e.replace(/`/g,"``")+"`"}},Pe=new de,re=null;function Ue(){return re||(re=ye("@google-cloud/bigquery-storage"),re)}function Ce(n){let e;return typeof n=="bigint"?e=n:typeof n=="number"||typeof n=="string"?e=BigInt(n):e=0n,e<0n&&(e=0n),e.toString(16).padStart(16,"0")}function Ze(n){if(!n||typeof n!="object")return false;let e=n;return e.code===4||e.code===10||e.code===13||e.code===14}async function Ge(n,e=6,t=200){let r=0;for(;;)try{return await n()}catch(s){if(r++,!Ze(s)||r>e)throw s;let o=t*Math.pow(2,r),i=Math.random()*o;await new Promise(a=>setTimeout(a,i));}}var Z=class extends Error{constructor(t,r,s,o){super(`Schema drift detected on \`${t}\`: column \`${r}\` has type ${s} in BigQuery but the current Zod schema maps it to ${o}. 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=t;this.column=r;this.existingType=s;this.desiredType=o;this.name="SchemaTypeMismatchError";}},K=class K{constructor(e){this.name="bigquery";this.writers=new Map;this.bigquery=e.bigquery,this.projectId=e.projectId,this.datasetId=e.datasetId,this.maxStaleness=e.maxStaleness===void 0?"INTERVAL 15 MINUTE":e.maxStaleness,this.writerClient=e.writerClient;}get dialect(){return Pe}async targetExists(e){return this.tableExists(e)}async upsert(e,t,r){return this.upsertRows(e,t,r)}async delete(e,t,r){return this.deleteRows(e,t,r)}async ensureTarget(e){if(!e.schema)return;let{targetName:t,primaryKey:r,schema:s,exclude:o,columnMap:i}=e,a=z(s,this.dialect,{primaryKey:r,exclude:o,columnMap:i});if(!await this.tableExists(t))await this.createTable({tableName:t,columns:a});else {let y=await this.getTableColumnsWithTypes(t),S=[];for(let T of a){let O=y.get(T.name);if(O===void 0){S.push(T);continue}if(!Ae(O,T.sqlType))throw new Z(t,T.name,O,T.sqlType)}S.length>0&&(await this.addColumns(t,S),await this.onSchemaChange?.(t));}}async healthCheck(e){let{targetName:t,primaryKey:r,schema:s,repoConfig:o}=e;if(!s)return {healthy:false,targetName:t,targetExists:false,error:"No Zod schema attached to repository"};try{if(!await this.tableExists(t))return {healthy:!1,targetName:t,targetExists:!1,error:`Table \`${t}\` does not exist`};let a=await this.getTableColumns(t),c=z(s,this.dialect,{primaryKey:r,exclude:o?.exclude,columnMap:o?.columnMap}),y=new Set(a),S=new Set(c.map(m=>m.name)),T=c.filter(m=>!y.has(m.name)),O=a.filter(m=>!S.has(m)),P=c.filter(m=>y.has(m.name)),k=T.length===0;return {healthy:k,targetName:t,targetExists:!0,error:k?null:`Missing columns: ${T.map(m=>m.name).join(", ")}`,details:{expected:c.map(m=>({name:m.name,type:m.sqlType,nullable:m.nullable,isPrimaryKey:m.isPrimaryKey})),actual:a,matched:P.map(m=>m.name),missing:T.map(m=>({name:m.name,type:m.sqlType})),extra:O}}}catch(i){return {healthy:false,targetName:t,targetExists:false,error:i?.message??String(i)}}}async tableExists(e){let[t]=await this.dataset.table(e).exists();return t}async getTableColumns(e){let[t]=await this.dataset.table(e).getMetadata();return (t.schema?.fields??[]).map(s=>s.name)}async getTableColumnsWithTypes(e){let[t]=await this.dataset.table(e).getMetadata(),r=t.schema?.fields??[],s=new Map;for(let o of r)s.set(o.name,ne(o.type));return s}async createTable(e){let t=c=>this.dialect.quoteIdentifier(c),r=e.columns.find(c=>c.isPrimaryKey)?.name;if(!r)throw new Error(`BigQueryAdapter requires a primary key on table \`${e.tableName}\` (Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`);let s=e.columns.map(c=>{let y=c.isPrimaryKey?" NOT NULL":"";return ` ${t(c.name)} ${c.sqlType}${y}`}).join(`,
97
- `),o=[];this.maxStaleness!==null&&o.push(`max_staleness = ${this.maxStaleness}`);let i=o.length>0?`
98
- OPTIONS(${o.join(", ")})`:"",a=`CREATE TABLE IF NOT EXISTS ${this.fqn(e.tableName)} (
99
- ${s},
89
+ <tbody>${v}</tbody></table>`},$=y.every(f=>f.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',I=K("Config Check",h,`<div class="card">
90
+ <p>Project: <code>${l}</code> ${$}</p>
91
+ ${C("BigQuery",w.bigquery)}
92
+ ${C("Meilisearch",w.meilisearch)}
93
+ ${C("Pub/Sub",w.pubsub)}
94
+ ${C("Other Targets",w.storage)}
95
+ ${C("Firestore",w.firestore)}
96
+ </div>`);q(d,I);}),async(u,d)=>{await D.handle(u,d);}}var tt="firestore-sync";function nt(n,e){return e?`${e}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${n}". Skipping.`),null)}function rt(n){let e=[n?.documentKey,n?.pathKey,n?.createdKey,n?.updatedKey].filter(o=>typeof o=="string"),t=typeof n?.path=="string"?n.path:null,r=t?Y(t,n?.documentKey??"docId"):null;return {isGroup:!!n?.isGroup,documentKey:e[0]??"docId",collectionPath:r?r.collectionPath:null,documentPathTemplate:r&&(!n?.isGroup||r.collectionPath.includes("/"))?r.documentPathTemplate:null,historyShadowKey:B(n?.history)}}function ot(n){let e=n?._collectionPath??n?.ref?.path??null,t=typeof n?._documentPathTemplate=="string"?n._documentPathTemplate:null;return {isGroup:!!n?._isGroup,documentKey:n?._systemKeys?.[0]??"docId",collectionPath:e,documentPathTemplate:t&&(!n?._isGroup||e&&e.includes("/"))?t:null,historyShadowKey:typeof n?._historyShadowKey=="string"?n._historyShadowKey:B(n?._historyConfig)}}function me(n,e){let{onDocumentWritten:t}=e.deps.firestoreTriggers,r=e.deps.pubsub,o=e?.topicPrefix??tt,s={},i=new Map;function c(k){let g=i.get(k);return g||(g=r.topic(k),i.set(k,g),g)}async function a(k,g){await c(k).publishMessage({json:g});}let p=n?.rawMapping,b=p?Object.entries(p).map(([k,g])=>[k,rt(g)]):Object.entries(n).map(([k,g])=>[k,ot(g)]),m=e?.repos,P=Object.keys(m??{}).length>0;for(let[k,g]of b){if(P&&(!m||!(k in m)))continue;let H=m?.[k],M;if(g.isGroup){let E=H?.triggerPath??g.documentPathTemplate;if(!E){console.warn(`[SyncTriggers] Skipping collection-group repo "${k}". Provide a triggerPath in the sync repos config for group collections or use a full path template.`);continue}M=E;}else M=H?.triggerPath??g.documentPathTemplate??nt(k,g.collectionPath);if(!M)continue;let D=g.documentKey,u=g.historyShadowKey?Array.from(new Set([...H?.exclude??[],g.historyShadowKey])):H?.exclude,d=`${o}-${k}`,h={...e?.triggerOptions,...H?.triggerOptions},l=Object.keys(h).length>0,S=async E=>{let y=E.data?.before,R=E.data?.after;if(!y&&!R)return;let w=!!y?.exists,C=!!R?.exists;if(!w&&C){let O=R.data();if(!O)return;let $=String(O[D]??R.id),I=W(O,{exclude:u,columnMap:H?.columnMap,flat:H?.flat,transformDoc:H?.transformDoc}),f={operation:"INSERT",repoName:k,docId:$,data:I,timestamp:new Date().toISOString(),version:Date.now()};await a(d,f);}else if(w&&C){let O=R.data();if(!O)return;let $=String(O[D]??R.id),I=W(O,{exclude:u,columnMap:H?.columnMap,flat:H?.flat,transformDoc:H?.transformDoc}),f={operation:"UPSERT",repoName:k,docId:$,data:I,timestamp:new Date().toISOString(),version:Date.now()};await a(d,f);}else if(w&&!C){let O=y.data(),$=String(O?.[D]??y.id),I={operation:"DELETE",repoName:k,docId:$,data:null,timestamp:new Date().toISOString(),version:Date.now()};await a(d,I);}};s[`${k}_onSync`]=t(l?{document:M,...h}:M,S);}return s}var j="__sync_version";var st={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 ne(n){let e=n,t=e._zod?.def?.type;if(t)return st[t]??`Zod${t.charAt(0).toUpperCase()}${t.slice(1)}`;let r=e._def?.typeName;return r||""}function De(n){let e=n;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function ge(n){let e=n;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 it=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function He(n){let e=n,t=false;for(;;){let r=ne(e);if(!it.has(r))break;(r==="ZodOptional"||r==="ZodNullable")&&(t=true);let o=De(e);if(!o)break;e=o;}return {inner:e,nullable:t}}var Ie={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function at(n){let{inner:e}=He(n);return Ie[ne(e)]??"json"}function Me(n,e,t,r,o,s,i,c){for(let[a,p]of Object.entries(n)){let b=t?`${t}__${a}`:a;if(o.has(a)||o.has(b))continue;let{inner:m,nullable:A}=He(p),P=ne(m),k=r||A;if(P==="ZodObject"){let D=ge(m);Me(D,e,b,k,o,s,i,c);continue}let g=Ie[P]??"json",H=b===i||a===i,M=s[b]??s[a]??b;c.push({name:M,sqlType:e.mapType(g),nullable:H?false:k,isPrimaryKey:H});}}function z(n,e,t={}){let{primaryKey:r,exclude:o=[],columnMap:s={}}=t,i=new Set(o),c=ge(n),a=[];return Me(c,e,"",false,i,s,r,a),a.some(p=>p.name===j)||a.push({name:j,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),a}function re(n){let e=n.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function $e(n,e){let t=re(n),r=re(e);return t===r?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[t]?.includes(r)??false}var he=class{constructor(){this.name="bigquery";}mapType(e){switch(e){case "string":return "STRING";case "number":return "FLOAT64";case "bigint":return "INT64";case "boolean":return "BOOL";case "timestamp":return "TIMESTAMP";case "json":return "JSON";case "text":return "STRING"}}quoteIdentifier(e){return "`"+e.replace(/`/g,"``")+"`"}},Ne=new he,oe=null;function ct(){return oe||(oe=Te("@google-cloud/bigquery-storage"),oe)}function _e(n){let e;return typeof n=="bigint"?e=n:typeof n=="number"||typeof n=="string"?e=BigInt(n):e=0n,e<0n&&(e=0n),e.toString(16).padStart(16,"0")}function lt(n){if(!n||typeof n!="object")return false;let e=n;return e.code===4||e.code===10||e.code===13||e.code===14}async function ut(n,e=6,t=200){let r=0;for(;;)try{return await n()}catch(o){if(r++,!lt(o)||r>e)throw o;let s=t*Math.pow(2,r),i=Math.random()*s;await new Promise(c=>setTimeout(c,i));}}var Z=class extends Error{constructor(t,r,o,s){super(`Schema drift detected on \`${t}\`: column \`${r}\` has type ${o} in BigQuery but the current Zod schema maps it to ${s}. 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=t;this.column=r;this.existingType=o;this.desiredType=s;this.name="SchemaTypeMismatchError";}},V=class V{constructor(e){this.name="bigquery";this.writers=new Map;this.bigquery=e.bigquery,this.projectId=e.projectId,this.datasetId=e.datasetId,this.maxStaleness=e.maxStaleness===void 0?"INTERVAL 15 MINUTE":e.maxStaleness,this.writerClient=e.writerClient;}get dialect(){return Ne}async targetExists(e){return this.tableExists(e)}async upsert(e,t,r){return this.upsertRows(e,t,r)}async delete(e,t,r){return this.deleteRows(e,t,r)}async ensureTarget(e){if(!e.schema)return;let{targetName:t,primaryKey:r,schema:o,exclude:s,columnMap:i}=e,c=z(o,this.dialect,{primaryKey:r,exclude:s,columnMap:i});if(!await this.tableExists(t))await this.createTable({tableName:t,columns:c});else {let p=await this.getTableColumnsWithTypes(t),b=[];for(let m of c){let A=p.get(m.name);if(A===void 0){b.push(m);continue}if(!$e(A,m.sqlType))throw new Z(t,m.name,A,m.sqlType)}b.length>0&&(await this.addColumns(t,b),await this.onSchemaChange?.(t));}}async healthCheck(e){let{targetName:t,primaryKey:r,schema:o,repoConfig:s}=e;if(!o)return {healthy:false,targetName:t,targetExists:false,error:"No Zod schema attached to repository"};try{if(!await this.tableExists(t))return {healthy:!1,targetName:t,targetExists:!1,error:`Table \`${t}\` does not exist`};let c=await this.getTableColumns(t),a=z(o,this.dialect,{primaryKey:r,exclude:s?.exclude,columnMap:s?.columnMap}),p=new Set(c),b=new Set(a.map(g=>g.name)),m=a.filter(g=>!p.has(g.name)),A=c.filter(g=>!b.has(g)),P=a.filter(g=>p.has(g.name)),k=m.length===0;return {healthy:k,targetName:t,targetExists:!0,error:k?null:`Missing columns: ${m.map(g=>g.name).join(", ")}`,details:{expected:a.map(g=>({name:g.name,type:g.sqlType,nullable:g.nullable,isPrimaryKey:g.isPrimaryKey})),actual:c,matched:P.map(g=>g.name),missing:m.map(g=>({name:g.name,type:g.sqlType})),extra:A}}}catch(i){return {healthy:false,targetName:t,targetExists:false,error:i?.message??String(i)}}}async tableExists(e){let[t]=await this.dataset.table(e).exists();return t}async getTableColumns(e){let[t]=await this.dataset.table(e).getMetadata();return (t.schema?.fields??[]).map(o=>o.name)}async getTableColumnsWithTypes(e){let[t]=await this.dataset.table(e).getMetadata(),r=t.schema?.fields??[],o=new Map;for(let s of r)o.set(s.name,re(s.type));return o}async createTable(e){let t=a=>this.dialect.quoteIdentifier(a),r=e.columns.find(a=>a.isPrimaryKey)?.name;if(!r)throw new Error(`BigQueryAdapter requires a primary key on table \`${e.tableName}\` (Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`);let o=e.columns.map(a=>{let p=a.isPrimaryKey?" NOT NULL":"";return ` ${t(a.name)} ${a.sqlType}${p}`}).join(`,
97
+ `),s=[];this.maxStaleness!==null&&s.push(`max_staleness = ${this.maxStaleness}`);let i=s.length>0?`
98
+ OPTIONS(${s.join(", ")})`:"",c=`CREATE TABLE IF NOT EXISTS ${this.fqn(e.tableName)} (
99
+ ${o},
100
100
  PRIMARY KEY (${t(r)}) NOT ENFORCED
101
101
  )
102
- CLUSTER BY ${t(r)}${i};`;await this.bigquery.query({query:a});}async addColumns(e,t){let r=s=>this.dialect.quoteIdentifier(s);for(let s of t){let o=`ALTER TABLE ${this.fqn(e)} ADD COLUMN ${r(s.name)} ${s.sqlType};`;await this.bigquery.query({query:o});}}async executeRaw(e){await this.bigquery.query({query:e});}onSchemaChange(e){let t=this.writers.get(e);if(t){try{t.writer.close();}catch{}this.writers.delete(e);}}async insertRows(e,t){if(t.length===0)return;let r=await this.getOrCreateWriter(e),s=this.writers.get(e)?.timestampColumns,o=t.map(i=>({...this.normalizeRow(i,s),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:Ce(i[j])}));await this.appendWithRetry(e,r,o);}async upsertRows(e,t,r){if(t.length===0)return;let s=await this.getOrCreateWriter(e,r),o=this.writers.get(e)?.timestampColumns,i=t.map(a=>({...this.normalizeRow(a,o),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:Ce(a[j])}));await this.appendWithRetry(e,s,i);}async deleteRows(e,t,r){if(r.length===0)return;let s=await this.getOrCreateWriter(e,t),o=r.map(i=>({[t]:i,_CHANGE_TYPE:"DELETE",_CHANGE_SEQUENCE_NUMBER:"ffffffffffffffff"}));await this.appendWithRetry(e,s,o);}get dataset(){return this.bigquery.dataset(this.datasetId)}fqn(e){let t=r=>r.replace(/`/g,"``");return `\`${t(this.datasetId)}.${t(e)}\``}static toEpochMicros(e){let t=e.getTime();return (BigInt(t)*1000n).toString()}normalizeRow(e,t){let r={};for(let[s,o]of Object.entries(e))if(o!==void 0)if(o instanceof Date)r[s]=K.toEpochMicros(o);else if(typeof o=="string"&&this.shouldCoerceTimestamp(s,o,t)){let i=new Date(o);Number.isNaN(i.getTime())?r[s]=o:r[s]=K.toEpochMicros(i);}else typeof o=="object"&&o!==null?r[s]=JSON.stringify(o):typeof o=="bigint"?r[s]=o.toString():r[s]=o;return r}shouldCoerceTimestamp(e,t,r){return r?r.has(e):K.ISO_TIMESTAMP_RE.test(t)}async appendWithRetry(e,t,r){await Ge(async()=>{try{await t.appendRows(r).getResult();}catch(s){throw this.onSchemaChange(e),s}});}async getOrCreateWriter(e,t){let r=this.writers.get(e);if(r)if(t&&r.primaryKey!==t)this.onSchemaChange(e);else return r.writer;let s=Ue();this.writerClient||(this.writerClient=new s.managedwriter.WriterClient({projectId:this.projectId}));let[o]=await this.dataset.table(e).getMetadata(),i={fields:o.schema?.fields??[]};t||(t=o.tableConstraints?.primaryKey?.columns?.[0]??i.fields[0]?.name);let a=s.adapt.convertBigQuerySchemaToStorageTableSchema(i),c=s.adapt.convertStorageSchemaToProto2Descriptor(a,"Row",s.adapt.withChangeType(),s.adapt.withChangeSequenceNumber()),y=new Set(i.fields.filter(P=>["TIMESTAMP","DATETIME","DATE"].includes(String(P.type??"").toUpperCase())).map(P=>P.name)),S=`projects/${this.projectId}/datasets/${this.datasetId}/tables/${e}`,T=await this.writerClient.createStreamConnection({streamId:s.managedwriter.DefaultStream,destinationTable:S}),O=new s.managedwriter.JSONWriter({connection:T,protoDescriptor:c});return this.writers.set(e,{writer:O,primaryKey:t??"",timestampColumns:y}),O}async close(){for(let{writer:e}of this.writers.values())try{e.close();}catch{}if(this.writers.clear(),this.writerClient&&typeof this.writerClient.close=="function")try{this.writerClient.close();}catch{}}};K.ISO_TIMESTAMP_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;var fe=K;var G=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 t=e.flushIntervalMs??5e3;t>0&&(this.timer=setInterval(()=>{this.flush();},t),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 t=new Map,r=[];for(let o of e)if(o.operation==="DELETE")r.push(o.docId),t.delete(o.docId);else if(o.data){let i=t.get(o.docId);if(!i)t.set(o.docId,o.data);else {let a=Number(i[j]??0);Number(o.data[j]??0)>=a&&t.set(o.docId,o.data);}}let s=Array.from(t.values());s.length>0&&(typeof this.adapter.upsert=="function"?await this.adapter.upsert(this.tableName,s,this.primaryKey):typeof this.adapter.upsertRows=="function"&&await this.adapter.upsertRows(this.tableName,s,this.primaryKey)),r.length>0&&(typeof this.adapter.delete=="function"?await this.adapter.delete(this.tableName,this.primaryKey,r):typeof this.adapter.deleteRows=="function"&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r));}catch(t){if(this.onFlushError)await this.onFlushError(e,t);else return this.buffer.unshift(...e),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,t),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var Ee=new Set;async function Ve(n,e,t,r,s,o,i){let a=`${n}:${e.name}`;if(!Ee.has(a)){if(typeof e.ensureTarget=="function")await e.ensureTarget({targetName:r,primaryKey:s,schema:t,exclude:o,columnMap:i});else if("dialect"in e&&typeof e.createTable=="function"){let c=e,y=z(t,c.dialect,{primaryKey:s,exclude:o,columnMap:i});if(!await c.tableExists(r))await c.createTable({tableName:r,columns:y});else {let T=new Set(await c.getTableColumns(r)),O=y.filter(P=>!T.has(P.name));O.length>0&&(await c.addColumns(r,O),await c.onSchemaChange?.(r));}}Ee.add(a);}}function pe(n,e){let{deps:t,adapter:r,adapters:s,batchSize:o=100,flushIntervalMs:i=5e3,autoMigrate:a=false,topicPrefix:c="firestore-sync",maxDlqAttempts:y=5,workerOptions:S,repos:T={}}=e,P=(s||(Array.isArray(r)?r:r?[r]:[])).map(u=>typeof u=="function"?u():u);function k(u){let d=T[u];if(d?.adapters&&d.adapters.length>0){let g=new Set(d.adapters);return P.filter(l=>g.has(l.name))}return P}let m=new Map;function M(u,d,g){let l=`${u}:${d.name}`,w=m.get(l);if(w)return w;let f=T[u]?.tableName??u,C=`${c}-${u}-${d.name}-dlq`,h=t.pubsub.topic(C),R=false,v=async()=>{if(!R){try{await h.create(),console.info(`[SyncWorker:${d.name}] Created DLQ topic "${C}"`);}catch(I){if(I?.code!==6)throw I}R=true;}},N=async(I,p)=>{console.error(`[SyncWorker:${d.name}] Flush failed for "${u}" (${I.length} events):`,p),await v(),await Promise.all(I.map(b=>{let E=(b.attempts??0)+1;if(y>0&&E>y)return console.error(`[SyncWorker:${d.name}] Dropping event for "${u}" after ${E-1} DLQ attempts:`,{docId:b.docId,operation:b.operation}),Promise.resolve();let x={...b,attempts:E,firstFailedAt:b.firstFailedAt??Date.now()};return h.publishMessage({json:x})}));};return w=new G({adapter:d,tableName:f,primaryKey:g,batchSize:o,flushIntervalMs:i,onFlushError:N}),m.set(l,w),m.has(u)||m.set(u,w),w}async function $(u){let{repoName:d}=u,g=n[d];if(!g){console.warn(`[SyncWorker] Unknown repo "${d}", skipping event`);return}let l=g._systemKeys?.[0]??g.documentKey??"docId",w=T[d],A=w?.columnMap,f=A?.[l]??l;u.data&&(u.data[j]=u.version??Date.now());let C=k(d);for(let h of C){if(a){let v=g.schema??void 0;if(v){let N=w?.tableName??d;await Ve(d,h,v,N,f,w?.exclude,A);}}M(d,h,f).enqueue(u);}}function D(u){let d=async g=>{let l=g.data?.message?.json??g.data?.json;if(!l){console.warn("[SyncWorker] Received empty PubSub message");return}await $(l);let w=k(l.repoName);for(let A of w){let f=`${l.repoName}:${A.name}`,C=m.get(f);C&&await C.flush();}};return S?t.pubsubHandler.onMessagePublished({topic:u,...S},d):t.pubsubHandler.onMessagePublished(u,d)}return {handleMessage:$,createHandler:D,queues:m,async shutdown(){let u=[],d=new Set;for(let g of m.values())d.has(g)||(d.add(g),u.push(g.shutdown()));await Promise.all(u);}}}var Je="firestore-sync";function Oe(n){if(typeof n!="function")return n;let e=n,t;return new Proxy({},{get(r,s){return t||(t=e()),t[s]},has(r,s){return t||(t=e()),s in t}})}function Ye(n,e){let{deps:t,adapter:r,adapters:s,topicPrefix:o=Je,batchSize:i,flushIntervalMs:a,autoMigrate:c,admin:y,workerOptions:S,triggerOptions:T,repos:O}=e,P=Oe(t.pubsub),m=(s||(Array.isArray(r)?r:r?[r]:[])).map(h=>Oe(h)),M=le(n,{deps:{firestoreTriggers:t.firestoreTriggers,pubsub:P},topicPrefix:o,triggerOptions:T,repos:O}),$=pe(n,{deps:{pubsubHandler:t.pubsubHandler,pubsub:P},adapters:m,batchSize:i,flushIntervalMs:a,autoMigrate:c,topicPrefix:o,workerOptions:S,repos:O}),D={},u=O,d=n?.rawMapping,g=Object.keys(u??{}),l=g.length>0,w=Object.keys(d||n),A=l?g.filter(h=>w.includes(h)||h in n):w;for(let h of A){let R=n?.rawMapping,v=R?!!R[h]?.isGroup:!!n[h]?._isGroup,N=R?R[h]?.path:n[h]?._collectionPath,I=typeof N=="string"&&N.includes("/");!l&&v&&!u?.[h]?.triggerPath&&!I||(D[`sync_${h}`]=$.createHandler(`${o}-${h}`));}let f=null;y&&(f=ce(n,m,$.queues,$.handleMessage,y,O??{},P,o),D.adminsync=y.onRequest?y.httpsOptions?y.onRequest(y.httpsOptions,f):y.onRequest(f):f);let C={functions:{...M,...D},adminHandler:f,handleMessage:$.handleMessage,queues:$.queues,shutdown:$.shutdown};for(let h of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(C,h,{enumerable:false});return C}function De(n,e){let t=e.columns.map(r=>{let s=r.isPrimaryKey?" NOT NULL":"";return ` ${n.quoteIdentifier(r.name)} ${r.sqlType}${s}`}).join(`,
102
+ CLUSTER BY ${t(r)}${i};`;await this.bigquery.query({query:c});}async addColumns(e,t){let r=o=>this.dialect.quoteIdentifier(o);for(let o of t){let s=`ALTER TABLE ${this.fqn(e)} ADD COLUMN ${r(o.name)} ${o.sqlType};`;await this.bigquery.query({query:s});}}async executeRaw(e){await this.bigquery.query({query:e});}onSchemaChange(e){let t=this.writers.get(e);if(t){try{t.writer.close();}catch{}this.writers.delete(e);}}async insertRows(e,t){if(t.length===0)return;let r=await this.getOrCreateWriter(e),o=this.writers.get(e)?.timestampColumns,s=t.map(i=>({...this.normalizeRow(i,o),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:_e(i[j])}));await this.appendWithRetry(e,r,s);}async upsertRows(e,t,r){if(t.length===0)return;let o=await this.getOrCreateWriter(e,r),s=this.writers.get(e)?.timestampColumns,i=t.map(c=>({...this.normalizeRow(c,s),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:_e(c[j])}));await this.appendWithRetry(e,o,i);}async deleteRows(e,t,r){if(r.length===0)return;let o=await this.getOrCreateWriter(e,t),s=r.map(i=>({[t]:i,_CHANGE_TYPE:"DELETE",_CHANGE_SEQUENCE_NUMBER:"ffffffffffffffff"}));await this.appendWithRetry(e,o,s);}get dataset(){return this.bigquery.dataset(this.datasetId)}fqn(e){let t=r=>r.replace(/`/g,"``");return `\`${t(this.datasetId)}.${t(e)}\``}static toEpochMicros(e){let t=e.getTime();return (BigInt(t)*1000n).toString()}normalizeRow(e,t){let r={};for(let[o,s]of Object.entries(e))if(s!==void 0)if(s instanceof Date)r[o]=V.toEpochMicros(s);else if(typeof s=="string"&&this.shouldCoerceTimestamp(o,s,t)){let i=new Date(s);Number.isNaN(i.getTime())?r[o]=s:r[o]=V.toEpochMicros(i);}else typeof s=="object"&&s!==null?r[o]=JSON.stringify(s):typeof s=="bigint"?r[o]=s.toString():r[o]=s;return r}shouldCoerceTimestamp(e,t,r){return r?r.has(e):V.ISO_TIMESTAMP_RE.test(t)}async appendWithRetry(e,t,r){await ut(async()=>{try{await t.appendRows(r).getResult();}catch(o){throw this.onSchemaChange(e),o}});}async getOrCreateWriter(e,t){let r=this.writers.get(e);if(r)if(t&&r.primaryKey!==t)this.onSchemaChange(e);else return r.writer;let o=ct();this.writerClient||(this.writerClient=new o.managedwriter.WriterClient({projectId:this.projectId}));let[s]=await this.dataset.table(e).getMetadata(),i={fields:s.schema?.fields??[]};t||(t=s.tableConstraints?.primaryKey?.columns?.[0]??i.fields[0]?.name);let c=o.adapt.convertBigQuerySchemaToStorageTableSchema(i),a=o.adapt.convertStorageSchemaToProto2Descriptor(c,"Row",o.adapt.withChangeType(),o.adapt.withChangeSequenceNumber()),p=new Set(i.fields.filter(P=>["TIMESTAMP","DATETIME","DATE"].includes(String(P.type??"").toUpperCase())).map(P=>P.name)),b=`projects/${this.projectId}/datasets/${this.datasetId}/tables/${e}`,m=await this.writerClient.createStreamConnection({streamId:o.managedwriter.DefaultStream,destinationTable:b}),A=new o.managedwriter.JSONWriter({connection:m,protoDescriptor:a});return this.writers.set(e,{writer:A,primaryKey:t??"",timestampColumns:p}),A}async close(){for(let{writer:e}of this.writers.values())try{e.close();}catch{}if(this.writers.clear(),this.writerClient&&typeof this.writerClient.close=="function")try{this.writerClient.close();}catch{}}};V.ISO_TIMESTAMP_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;var be=V;var G=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 t=e.flushIntervalMs??5e3;t>0&&(this.timer=setInterval(()=>{this.flush();},t),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 t=new Map,r=[];for(let s of e)if(s.operation==="DELETE")r.push(s.docId),t.delete(s.docId);else if(s.data){let i=t.get(s.docId);if(!i)t.set(s.docId,s.data);else {let c=Number(i[j]??0);Number(s.data[j]??0)>=c&&t.set(s.docId,s.data);}}let o=Array.from(t.values());o.length>0&&(typeof this.adapter.upsert=="function"?await this.adapter.upsert(this.tableName,o,this.primaryKey):typeof this.adapter.upsertRows=="function"&&await this.adapter.upsertRows(this.tableName,o,this.primaryKey)),r.length>0&&(typeof this.adapter.delete=="function"?await this.adapter.delete(this.tableName,this.primaryKey,r):typeof this.adapter.deleteRows=="function"&&await this.adapter.deleteRows(this.tableName,this.primaryKey,r));}catch(t){if(this.onFlushError)await this.onFlushError(e,t);else return this.buffer.unshift(...e),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,t),false}return true}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var Fe=new Set;async function dt(n,e,t,r,o,s,i){let c=`${n}:${e.name}`;if(!Fe.has(c)){if(typeof e.ensureTarget=="function")await e.ensureTarget({targetName:r,primaryKey:o,schema:t,exclude:s,columnMap:i});else if("dialect"in e&&typeof e.createTable=="function"){let a=e,p=z(t,a.dialect,{primaryKey:o,exclude:s,columnMap:i});if(!await a.tableExists(r))await a.createTable({tableName:r,columns:p});else {let m=new Set(await a.getTableColumns(r)),A=p.filter(P=>!m.has(P.name));A.length>0&&(await a.addColumns(r,A),await a.onSchemaChange?.(r));}}Fe.add(c);}}function we(n,e){let{deps:t,adapter:r,adapters:o,batchSize:s=100,flushIntervalMs:i=5e3,autoMigrate:c=false,topicPrefix:a="firestore-sync",maxDlqAttempts:p=5,workerOptions:b,repos:m={}}=e,P=(o||(Array.isArray(r)?r:r?[r]:[])).map(u=>typeof u=="function"?u():u);function k(u){let d=m[u];if(d?.adapters&&d.adapters.length>0){let h=new Set(d.adapters);return P.filter(l=>h.has(l.name))}return P}let g=new Map;function H(u,d,h){let l=`${u}:${d.name}`,S=g.get(l);if(S)return S;let y=m[u]?.tableName??u,R=`${a}-${u}-${d.name}-dlq`,w=t.pubsub.topic(R),C=false,O=async()=>{if(!C){try{await w.create(),console.info(`[SyncWorker:${d.name}] Created DLQ topic "${R}"`);}catch(I){if(I?.code!==6)throw I}C=true;}},$=async(I,f)=>{console.error(`[SyncWorker:${d.name}] Flush failed for "${u}" (${I.length} events):`,f),await O(),await Promise.all(I.map(T=>{let v=(T.attempts??0)+1;if(p>0&&v>p)return console.error(`[SyncWorker:${d.name}] Dropping event for "${u}" after ${v-1} DLQ attempts:`,{docId:T.docId,operation:T.operation}),Promise.resolve();let x={...T,attempts:v,firstFailedAt:T.firstFailedAt??Date.now()};return w.publishMessage({json:x})}));};return S=new G({adapter:d,tableName:y,primaryKey:h,batchSize:s,flushIntervalMs:i,onFlushError:$}),g.set(l,S),g.has(u)||g.set(u,S),S}async function M(u){let{repoName:d}=u,h=n[d];if(!h){console.warn(`[SyncWorker] Unknown repo "${d}", skipping event`);return}let l=h._systemKeys?.[0]??h.documentKey??"docId",S=m[d],E=S?.columnMap,y=E?.[l]??l;u.data&&(u.data[j]=u.version??Date.now());let R=k(d);for(let w of R){if(c){let O=h.schema??void 0;if(O){let $=S?.tableName??d;await dt(d,w,O,$,y,S?.exclude,E);}}H(d,w,y).enqueue(u);}}function D(u){let d=async h=>{let l=h.data?.message?.json??h.data?.json;if(!l){console.warn("[SyncWorker] Received empty PubSub message");return}await M(l);let S=k(l.repoName);for(let E of S){let y=`${l.repoName}:${E.name}`,R=g.get(y);R&&await R.flush();}};return b?t.pubsubHandler.onMessagePublished({topic:u,...b},d):t.pubsubHandler.onMessagePublished(u,d)}return {handleMessage:M,createHandler:D,queues:g,async shutdown(){let u=[],d=new Set;for(let h of g.values())d.has(h)||(d.add(h),u.push(h.shutdown()));await Promise.all(u);}}}var ft="firestore-sync";function je(n){if(typeof n!="function")return n;let e=n,t;return new Proxy({},{get(r,o){return t||(t=e()),t[o]},has(r,o){return t||(t=e()),o in t}})}function pt(n,e){let{deps:t,adapter:r,adapters:o,topicPrefix:s=ft,batchSize:i,flushIntervalMs:c,autoMigrate:a,admin:p,workerOptions:b,triggerOptions:m,repos:A}=e,P=je(t.pubsub),g=(o||(Array.isArray(r)?r:r?[r]:[])).map(w=>je(w)),H=me(n,{deps:{firestoreTriggers:t.firestoreTriggers,pubsub:P},topicPrefix:s,triggerOptions:m,repos:A}),M=we(n,{deps:{pubsubHandler:t.pubsubHandler,pubsub:P},adapters:g,batchSize:i,flushIntervalMs:c,autoMigrate:a,topicPrefix:s,workerOptions:b,repos:A}),D={},u=A,d=n?.rawMapping,h=Object.keys(u??{}),l=h.length>0,S=Object.keys(d||n),E=l?h.filter(w=>S.includes(w)||w in n):S;for(let w of E){let C=n?.rawMapping,O=C?!!C[w]?.isGroup:!!n[w]?._isGroup,$=C?C[w]?.path:n[w]?._collectionPath,I=typeof $=="string"&&$.includes("/");!l&&O&&!u?.[w]?.triggerPath&&!I||(D[`sync_${w}`]=M.createHandler(`${s}-${w}`));}let y=null;p&&(y=ye(n,g,M.queues,M.handleMessage,p,A??{},P,s),D.adminsync=p.onRequest?p.httpsOptions?p.onRequest(p.httpsOptions,y):p.onRequest(y):y);let R={functions:{...H,...D},adminHandler:y,handleMessage:M.handleMessage,queues:M.queues,shutdown:M.shutdown};for(let w of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(R,w,{enumerable:false});return R}function ze(n,e){let t=e.columns.map(r=>{let o=r.isPrimaryKey?" NOT NULL":"";return ` ${n.quoteIdentifier(r.name)} ${r.sqlType}${o}`}).join(`,
103
103
  `);return `CREATE TABLE IF NOT EXISTS ${n.quoteIdentifier(e.tableName)} (
104
104
  ${t}
105
- );`}function Xe(n,e,t){return t.map(r=>`ALTER TABLE ${n.quoteIdentifier(e)} ADD COLUMN ${n.quoteIdentifier(r.name)} ${r.sqlType};`).join(`
106
- `)}function et(n,e,t){let r=[];for(let[s,o]of Object.entries(n)){let i=o.schema??o._schema??void 0;if(!i)continue;let a=t?.repos?.[s],c=a?.tableName??s,y=o._systemKeys?.[0]??o.documentKey??"docId",S=z(i,e,{primaryKey:y,exclude:a?.exclude,columnMap:a?.columnMap}),T={tableName:c,columns:S};r.push(De(e,T));}return r.join(`
105
+ );`}function yt(n,e,t){return t.map(r=>`ALTER TABLE ${n.quoteIdentifier(e)} ADD COLUMN ${n.quoteIdentifier(r.name)} ${r.sqlType};`).join(`
106
+ `)}function mt(n,e,t){let r=[];for(let[o,s]of Object.entries(n)){let i=s.schema??s._schema??void 0;if(!i)continue;let c=t?.repos?.[o],a=c?.tableName??o,p=s._systemKeys?.[0]??s.documentKey??"docId",b=z(i,e,{primaryKey:p,exclude:c?.exclude,columnMap:c?.columnMap}),m={tableName:a,columns:b};r.push(ze(e,m));}return r.join(`
107
107
 
108
- `)}async function tt(n,e,t){let r={created:[],altered:[],upToDate:[],skipped:[]};for(let[s,o]of Object.entries(n)){let i=o.schema??void 0;if(!i){r.skipped.push(s);continue}let a=t?.repos?.[s],c=a?.tableName??s,y=o._systemKeys?.[0]??o.documentKey??"docId",S=z(i,e.dialect,{primaryKey:y,exclude:a?.exclude,columnMap:a?.columnMap}),T={tableName:c,columns:S};if(!await e.tableExists(c))await e.createTable(T),r.created.push(c);else {let P=new Set(await e.getTableColumns(c)),k=S.filter(m=>!P.has(m.name));k.length>0?(await e.addColumns(c,k),r.altered.push(c)):r.upToDate.push(c);}}return r}function nt(n){if(n.client)return n.client;if(!n.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:e}=ye("meilisearch");return new e({host:n.host,apiKey:n.apiKey})}catch(e){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
108
+ `)}async function gt(n,e,t){let r={created:[],altered:[],upToDate:[],skipped:[]};for(let[o,s]of Object.entries(n)){let i=s.schema??void 0;if(!i){r.skipped.push(o);continue}let c=t?.repos?.[o],a=c?.tableName??o,p=s._systemKeys?.[0]??s.documentKey??"docId",b=z(i,e.dialect,{primaryKey:p,exclude:c?.exclude,columnMap:c?.columnMap}),m={tableName:a,columns:b};if(!await e.tableExists(a))await e.createTable(m),r.created.push(a);else {let P=new Set(await e.getTableColumns(a)),k=b.filter(g=>!P.has(g.name));k.length>0?(await e.addColumns(a,k),r.altered.push(a)):r.upToDate.push(a);}}return r}function ht(n){if(n.client)return n.client;if(!n.host)throw new Error("MeilisearchAdapter requires either a `client` instance or a `host` option.");try{let{MeiliSearch:e}=Te("meilisearch");return new e({host:n.host,apiKey:n.apiKey})}catch(e){throw new Error(`Failed to load the "meilisearch" package. Please install it with:
109
109
  bun add meilisearch # or npm install meilisearch
110
- Original error: ${e?.message??String(e)}`)}}function rt(n,e){if(!n||!e)return false;for(let[t,r]of Object.entries(e)){if(r===void 0)continue;let s=n[t];if(Array.isArray(r)){if(!Array.isArray(s)||r.length!==s.length)return false;for(let o=0;o<r.length;o++)if(r[o]!==s[o])return false}else if(typeof r=="object"&&r!==null){if(JSON.stringify(r)!==JSON.stringify(s))return false}else if(r!==s)return false}return true}var se=class{constructor(e){this.name="meilisearch";this._client=null;this.options=e,e.client&&(this._client=e.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=nt(this.options)),this._client}async targetExists(e){try{return await this.client.getIndex(e),!0}catch(t){if(t?.code==="index_not_found"||t?.cause?.code==="index_not_found"||t?.statusCode===404||t?.status===404||t?.response?.status===404||t?.cause?.status===404||t?.cause?.statusCode===404||t?.cause?.response?.status===404)return false;throw t}}async upsert(e,t,r){if(t.length===0)return;let s=this.options.unflatten!==false,o=t.map(a=>{let c=s?ae(a):a;return typeof this.options.transformDoc=="function"&&(c=this.options.transformDoc(c)),c});await this.client.index(e).addDocuments(o,{primaryKey:r});}async delete(e,t,r){if(r.length===0)return;await this.client.index(e).deleteDocuments(r);}async ensureTarget(e){let{targetName:t,primaryKey:r}=e;await this.targetExists(t)||await this.client.createIndex(t,{primaryKey:r});let o=this.options.indexesSettings?.[t];if(o){let{retrievableAttributes:i,attributesToRetrieve:a,...c}=o,y={...c,displayedAttributes:c.displayedAttributes??i??a};y.displayedAttributes===void 0&&delete y.displayedAttributes;let S=this.client.index(t);if(typeof S.getSettings=="function")try{let T=await S.getSettings();if(rt(T,y))return}catch{}await S.updateSettings(y);}}async healthCheck(e){let{targetName:t}=e;try{if(!await this.targetExists(t))return {healthy:!1,targetName:t,targetExists:!1,error:`Meilisearch index "${t}" does not exist`};let s=this.client.index(t),o=await s.getStats(),i=typeof s.getRawInfo=="function"?await s.getRawInfo():{};return {healthy:!0,targetName:t,targetExists:!0,error:null,details:{numberOfDocuments:o?.numberOfDocuments??0,isIndexing:o?.isIndexing??!1,fieldDistribution:o?.fieldDistribution??{},primaryKey:i?.primaryKey??e.primaryKey}}}catch(r){return {healthy:false,targetName:t,targetExists:false,error:r?.message??String(r)}}}async checkConnection(){try{let e=!0;if(typeof this.client.isHealthy=="function"){let r=await this.client.isHealthy();e=r?.status==="available"||r===!0;}else if(typeof this.client.health=="function"){let r=await this.client.health();e=r?.status==="available"||r===!0;}let t;return typeof this.client.getVersion=="function"&&(t=(await this.client.getVersion())?.pkgVersion),{healthy:e,version:t}}catch(e){return {healthy:false,error:e?.message??String(e)}}}};function st(n){return ()=>new se(n)}exports.BigQueryAdapter=fe;exports.MeilisearchAdapter=se;exports.SchemaTypeMismatchError=Z;exports.SyncQueue=G;exports.addColumnsDDL=Xe;exports.autoMigrate=tt;exports.bigqueryDialect=Pe;exports.createFirestoreSync=Ye;exports.createSyncTriggers=le;exports.createSyncWorker=pe;exports.createTableDDL=De;exports.createadminsyncServer=ce;exports.defineMeilisearchAdapter=st;exports.generateDDL=et;exports.serializeDocument=Q;exports.serializeValue=X;exports.unflattenDocument=ae;exports.zodSchemaToColumns=z;exports.zodTypeToLogical=Ke;//# sourceMappingURL=index.cjs.map
110
+ Original error: ${e?.message??String(e)}`)}}function bt(n,e){if(!n||!e)return false;for(let[t,r]of Object.entries(e)){if(r===void 0)continue;let o=n[t];if(Array.isArray(r)){if(!Array.isArray(o)||r.length!==o.length)return false;for(let s=0;s<r.length;s++)if(r[s]!==o[s])return false}else if(typeof r=="object"&&r!==null){if(JSON.stringify(r)!==JSON.stringify(o))return false}else if(r!==o)return false}return true}var se=class{constructor(e){this.name="meilisearch";this._client=null;this.options=e,e.client&&(this._client=e.client);}get indexesSettings(){return this.options.indexesSettings}get client(){return this._client||(this._client=ht(this.options)),this._client}async targetExists(e){try{return await this.client.getIndex(e),!0}catch(t){if(t?.code==="index_not_found"||t?.cause?.code==="index_not_found"||t?.statusCode===404||t?.status===404||t?.response?.status===404||t?.cause?.status===404||t?.cause?.statusCode===404||t?.cause?.response?.status===404)return false;throw t}}async upsert(e,t,r){if(t.length===0)return;let o=this.options.unflatten!==false,s=t.map(c=>{let a=o?pe(c):c;return typeof this.options.transformDoc=="function"&&(a=this.options.transformDoc(a)),a});await this.client.index(e).addDocuments(s,{primaryKey:r});}async delete(e,t,r){if(r.length===0)return;await this.client.index(e).deleteDocuments(r);}async ensureTarget(e){let{targetName:t,primaryKey:r}=e;await this.targetExists(t)||await this.client.createIndex(t,{primaryKey:r});let s=this.options.indexesSettings?.[t];if(s){let{retrievableAttributes:i,attributesToRetrieve:c,...a}=s,p={...a,displayedAttributes:a.displayedAttributes??i??c};p.displayedAttributes===void 0&&delete p.displayedAttributes;let b=this.client.index(t);if(typeof b.getSettings=="function")try{let m=await b.getSettings();if(bt(m,p))return}catch{}await b.updateSettings(p);}}async healthCheck(e){let{targetName:t}=e;try{if(!await this.targetExists(t))return {healthy:!1,targetName:t,targetExists:!1,error:`Meilisearch index "${t}" does not exist`};let o=this.client.index(t),s=await o.getStats(),i=typeof o.getRawInfo=="function"?await o.getRawInfo():{};return {healthy:!0,targetName:t,targetExists:!0,error:null,details:{numberOfDocuments:s?.numberOfDocuments??0,isIndexing:s?.isIndexing??!1,fieldDistribution:s?.fieldDistribution??{},primaryKey:i?.primaryKey??e.primaryKey}}}catch(r){return {healthy:false,targetName:t,targetExists:false,error:r?.message??String(r)}}}async checkConnection(){try{let e=!0;if(typeof this.client.isHealthy=="function"){let r=await this.client.isHealthy();e=r?.status==="available"||r===!0;}else if(typeof this.client.health=="function"){let r=await this.client.health();e=r?.status==="available"||r===!0;}let t;return typeof this.client.getVersion=="function"&&(t=(await this.client.getVersion())?.pkgVersion),{healthy:e,version:t}}catch(e){return {healthy:false,error:e?.message??String(e)}}}};function wt(n){return ()=>new se(n)}exports.BigQueryAdapter=be;exports.MeilisearchAdapter=se;exports.SchemaTypeMismatchError=Z;exports.SyncQueue=G;exports.addColumnsDDL=yt;exports.autoMigrate=gt;exports.bigqueryDialect=Ne;exports.createFirestoreSync=pt;exports.createSyncTriggers=me;exports.createSyncWorker=we;exports.createTableDDL=ze;exports.createadminsyncServer=ye;exports.defineMeilisearchAdapter=wt;exports.generateDDL=mt;exports.serializeDocument=W;exports.serializeValue=ee;exports.unflattenDocument=pe;exports.zodSchemaToColumns=z;exports.zodTypeToLogical=at;//# sourceMappingURL=index.cjs.map
111
111
  //# sourceMappingURL=index.cjs.map