@lpdjs/firestore-repo-service 2.1.7 → 2.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/sync/index.cjs +9 -9
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.js +9 -9
- package/dist/sync/index.js.map +1 -1
- package/package.json +1 -1
package/dist/sync/index.cjs
CHANGED
|
@@ -28,12 +28,12 @@
|
|
|
28
28
|
<nav><a href="${e}/">\u2190 Dashboard</a></nav>
|
|
29
29
|
<h1>${o}</h1>
|
|
30
30
|
${n}
|
|
31
|
-
</body></html>`}function D(o,e,n=200){o.status(n).set("Content-Type","text/html; charset=utf-8").send(e);}function _(o,e,n=200){o.status(n).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function j(o){return (o.headers?.accept??"").includes("application/json")}function K(o,e,n,s,r,p,g,$){let i=(r.basePath??"/").replace(/\/$/,"")||"",f=r.featuresFlag??{},m=[];for(let[l,a]of Object.entries(o)){let c=p[l];m.push({name:l,schema:a.schema??null,documentKey:a._systemKeys?.[0]??a.documentKey??"docId",tableName:c?.tableName??l,isGroup:!!a._isGroup,repoCfg:c,repo:a});}let b=new I;if(r.auth)if(typeof r.auth=="function")b.use(r.auth);else {let l=r.auth.realm??"Sync Admin",a="Basic "+Buffer.from(`${r.auth.username}:${r.auth.password}`).toString("base64");b.use((c,t,u)=>{if((c.headers?.authorization??"")!==a){t.status(401).set("WWW-Authenticate",`Basic realm="${l}"`).set("Content-Type","text/plain").send("Unauthorized");return}u();});}return b.get(`${i}/`,(l,a)=>{let c=q(l,i),t=m.map(T=>{let
|
|
31
|
+
</body></html>`}function D(o,e,n=200){o.status(n).set("Content-Type","text/html; charset=utf-8").send(e);}function _(o,e,n=200){o.status(n).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function j(o){return (o.headers?.accept??"").includes("application/json")}function K(o,e,n,s,r,p,g,$){let i=(r.basePath??"/").replace(/\/$/,"")||"",f=r.featuresFlag??{},m=[];for(let[l,a]of Object.entries(o)){let c=p[l];m.push({name:l,schema:a.schema??null,documentKey:a._systemKeys?.[0]??a.documentKey??"docId",tableName:c?.tableName??l,isGroup:!!a._isGroup,repoCfg:c,repo:a});}let b=new I;if(r.auth)if(typeof r.auth=="function")b.use(r.auth);else {let l=r.auth.realm??"Sync Admin",a="Basic "+Buffer.from(`${r.auth.username}:${r.auth.password}`).toString("base64");b.use((c,t,u)=>{if((c.headers?.authorization??"")!==a){t.status(401).set("WWW-Authenticate",`Basic realm="${l}"`).set("Content-Type","text/plain").send("Unauthorized");return}u();});}return b.get(`${i}/`,(l,a)=>{let c=q(l,i),t=m.map(T=>{let C=[];return f.healthCheck&&C.push(`<a class="btn" href="${c}/${T.name}/health">Health</a>`),f.manualSync&&C.push(`<a class="btn btn-primary" href="${c}/${T.name}/force-sync">Force Sync</a>`),`<tr>
|
|
32
32
|
<td><strong>${T.name}</strong></td>
|
|
33
33
|
<td>${T.tableName}</td>
|
|
34
34
|
<td>${T.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
|
|
35
35
|
<td>${T.schema?"\u2713":"\u2717"}</td>
|
|
36
|
-
<td>${
|
|
36
|
+
<td>${C.join(" ")}</td>
|
|
37
37
|
</tr>`}).join(`
|
|
38
38
|
`),u=f.viewQueue?`<p><a class="btn" href="${c}/queues">View Queues</a></p>`:"",y=f.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${c}/config-check">\u2699 Config Check</a></p>`:"",d=E("Sync Dashboard",c,`<div class="card">
|
|
39
39
|
<table>
|
|
@@ -42,7 +42,7 @@ ${n}
|
|
|
42
42
|
</table>
|
|
43
43
|
${u}
|
|
44
44
|
${y}
|
|
45
|
-
</div>`);D(a,d);}),b.get(`${i}`,(l,a)=>{let c=q(l,i);a.status(302).set("Location",`${c}/`).send("");}),f.healthCheck&&b.get(`${i}/:repoName/health`,async(l,a)=>{let c=q(l,i),t=m.find(h=>h.name===l.params.repoName);if(!t){D(a,E("Not Found",c,`<p>Unknown repo: ${l.params.repoName}</p>`),404);return}if(!t.schema){D(a,E("Health Check",c,`<p class="badge badge-warn">No Zod schema attached to "${t.name}"</p>`));return}let u=A(t.schema,e.dialect,{primaryKey:t.documentKey,exclude:t.repoCfg?.exclude,columnMap:t.repoCfg?.columnMap}),y=[],d=false,T=null;try{d=await e.tableExists(t.tableName),d&&(y=await e.getTableColumns(t.tableName));}catch(h){T=h?.message??String(h);}let
|
|
45
|
+
</div>`);D(a,d);}),b.get(`${i}`,(l,a)=>{let c=q(l,i);a.status(302).set("Location",`${c}/`).send("");}),f.healthCheck&&b.get(`${i}/:repoName/health`,async(l,a)=>{let c=q(l,i),t=m.find(h=>h.name===l.params.repoName);if(!t){D(a,E("Not Found",c,`<p>Unknown repo: ${l.params.repoName}</p>`),404);return}if(!t.schema){D(a,E("Health Check",c,`<p class="badge badge-warn">No Zod schema attached to "${t.name}"</p>`));return}let u=A(t.schema,e.dialect,{primaryKey:t.documentKey,exclude:t.repoCfg?.exclude,columnMap:t.repoCfg?.columnMap}),y=[],d=false,T=null;try{d=await e.tableExists(t.tableName),d&&(y=await e.getTableColumns(t.tableName));}catch(h){T=h?.message??String(h);}let C=new Set(y),x=new Set(u.map(h=>h.name)),N=u.filter(h=>!C.has(h.name)),k=y.filter(h=>!x.has(h)),O=u.filter(h=>C.has(h.name)),S=d&&N.length===0&&!T;if(j(l)){_(a,{repo:t.name,table:t.tableName,tableExists:d,healthy:S,error:T,columns:{expected:u.map(h=>({name:h.name,type:h.sqlType,nullable:h.nullable,isPrimaryKey:h.isPrimaryKey})),actual:y,matched:O.map(h=>h.name),missing:N.map(h=>({name:h.name,type:h.sqlType})),extra:k}});return}let R=S?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',w=u.map(h=>{let L=C.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.sqlType}</td><td>${h.nullable?"Yes":"No"}</td><td>${h.isPrimaryKey?"\u2713":""}</td><td>${L}</td></tr>`}).join(`
|
|
46
46
|
`),v=k.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(`
|
|
47
47
|
`),P=E(`Health: ${t.name}`,c,`<div class="card">
|
|
48
48
|
<p>Table: <code>${t.tableName}</code> ${d?R:'<span class="badge badge-err">NOT FOUND</span>'}</p>
|
|
@@ -59,7 +59,7 @@ ${n}
|
|
|
59
59
|
<form method="POST" action="${c}/${t.name}/force-sync">
|
|
60
60
|
<button type="submit" class="btn btn-primary">Start Force Sync</button>
|
|
61
61
|
</form>
|
|
62
|
-
</div>`);D(a,u);}),b.post(`${i}/:repoName/force-sync`,async(l,a)=>{let c=q(l,i),t=m.find(k=>k.name===l.params.repoName);if(!t){_(a,{error:`Unknown repo: ${l.params.repoName}`},404);return}let u=t.repo.ref;if(!u){_(a,{error:`No collection reference for "${t.name}"`},400);return}let y=0,d=0,T=500,
|
|
62
|
+
</div>`);D(a,u);}),b.post(`${i}/:repoName/force-sync`,async(l,a)=>{let c=q(l,i),t=m.find(k=>k.name===l.params.repoName);if(!t){_(a,{error:`Unknown repo: ${l.params.repoName}`},404);return}let u=t.repo.ref;if(!u){_(a,{error:`No collection reference for "${t.name}"`},400);return}let y=0,d=0,T=500,C=u.limit(T),x=null;try{for(;;){let S=await(x?C.startAfter(x):C).get();if(S.empty)break;for(let R of S.docs){let w=R.data(),v=String(w[t.documentKey]??R.id),P=z(w,{exclude:t.repoCfg?.exclude,columnMap:t.repoCfg?.columnMap});try{await s({operation:"UPSERT",repoName:t.name,docId:v,data:P,timestamp:new Date().toISOString()}),y++;}catch{d++;}}if(x=S.docs[S.docs.length-1],S.docs.length<T)break}let k=n.get(t.name);k&&await k.flush();}catch(k){if(j(l)){_(a,{error:k?.message??String(k),synced:y,errors:d},500);return}D(a,E(`Force Sync: ${t.name}`,c,`<div class="card">
|
|
63
63
|
<p class="badge badge-err">Error: ${k?.message??String(k)}</p>
|
|
64
64
|
<p>Synced ${y} docs before failure (${d} errors).</p>
|
|
65
65
|
</div>`),500);return}if(j(l)){_(a,{repo:t.name,table:t.tableName,synced:y,errors:d});return}let N=E(`Force Sync: ${t.name}`,c,`<div class="card">
|
|
@@ -73,7 +73,7 @@ ${n}
|
|
|
73
73
|
<tbody>${u}</tbody>
|
|
74
74
|
</table>
|
|
75
75
|
</div>`);D(a,y);}),f.configCheck&&b.get(`${i}/config-check`,async(l,a)=>{let c=q(l,i),t=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",u="https://console.cloud.google.com",y=$??"firestore-sync",d=[];try{await e.tableExists("__nonexistent_health_check__"),d.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(S){let R=S?.message??String(S),w=R.toLowerCase(),v=w.includes("disabled")||w.includes("has not been used")||w.includes("accessnotconfigured"),P=w.includes("permission")||R.includes("403")||w.includes("access denied"),h=w.includes("project")&&w.includes("not found"),L=w.includes("not found")||R.includes("404");v?d.push({name:"BigQuery API",category:"bigquery",status:"error",message:"BigQuery API is not enabled",fix:{gcloud:`gcloud services enable bigquery.googleapis.com --project=${t}`,console:`${u}/apis/library/bigquery.googleapis.com?project=${t}`}}):h?d.push({name:"BigQuery Project",category:"bigquery",status:"error",message:R,fix:{hint:"The GCP project does not exist or the credentials don't have access to it. In the Firebase emulator, GCLOUD_PROJECT may override the configured projectId. Ensure you pass the correct projectId to the BigQuery constructor and have valid credentials.",console:`${u}/home/dashboard`}}):P?d.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${R}`,fix:{hint:"Grant the service account BigQuery Data Editor + BigQuery Job User roles",gcloud:[`SA=$(gcloud run services describe YOUR_SERVICE --region=YOUR_REGION --format="value(spec.template.spec.serviceAccountName)" --project=${t})`,`gcloud projects add-iam-policy-binding ${t} --member="serviceAccount:$SA" --role="roles/bigquery.dataEditor"`,`gcloud projects add-iam-policy-binding ${t} --member="serviceAccount:$SA" --role="roles/bigquery.jobUser"`].join(`
|
|
76
|
-
`),console:`${u}/iam-admin/iam?project=${t}`}}):L?d.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${R}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${t}:YOUR_DATASET_ID`,console:`${u}/bigquery?project=${t}`}}):d.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}for(let S of m)try{let R=await e.tableExists(S.tableName);d.push({name:`Table: ${S.tableName}`,category:"bigquery",status:R?"ok":"warn",message:R?`Table \`${S.tableName}\` exists`:`Table \`${S.tableName}\` does not exist yet`,...!R&&{fix:{hint:"Table will be auto-created on first sync if autoMigrate is enabled. Or create it manually."}}});}catch(R){d.push({name:`Table: ${S.tableName}`,category:"bigquery",status:"error",message:R?.message??String(R)});}if(g)for(let S of m){let R=`${y}-${S.name}`;try{let w=g.topic(R);if(typeof w.exists=="function"){let[v]=await w.exists();d.push({name:`Topic: ${R}`,category:"pubsub",status:v?"ok":"error",message:v?`Topic \`${R}\` exists`:`Topic \`${R}\` does not exist`,...!v&&{fix:{gcloud:`gcloud pubsub topics create ${R} --project=${t}`,console:`${u}/cloudpubsub/topic/list?project=${t}`}}});}else d.push({name:`Topic: ${R}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${R} --project=${t}`,console:`${u}/cloudpubsub/topic/list?project=${t}`,hint:"Ensure the topic exists. It is auto-created by the Firebase emulator but must exist in production."}});}catch(w){let v=w?.message??String(w),P=v.includes("disabled")||v.includes("has not been used");if(d.push({name:P?"Pub/Sub API":`Topic: ${R}`,category:"pubsub",status:"error",message:P?"Pub/Sub API is not enabled":v,fix:P?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${t}`,console:`${u}/apis/library/pubsub.googleapis.com?project=${t}`}:{gcloud:`gcloud pubsub topics create ${R} --project=${t}`,console:`${u}/cloudpubsub/topic/list?project=${t}`}}),P)break}}else d.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(j(l)){let S=d.every(R=>R.status==="ok");_(a,{project:t,healthy:S,checks:d});return}let T=S=>S==="ok"?'<span class="badge badge-ok">OK</span>':S==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',
|
|
76
|
+
`),console:`${u}/iam-admin/iam?project=${t}`}}):L?d.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${R}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${t}:YOUR_DATASET_ID`,console:`${u}/bigquery?project=${t}`}}):d.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}for(let S of m)try{let R=await e.tableExists(S.tableName);d.push({name:`Table: ${S.tableName}`,category:"bigquery",status:R?"ok":"warn",message:R?`Table \`${S.tableName}\` exists`:`Table \`${S.tableName}\` does not exist yet`,...!R&&{fix:{hint:"Table will be auto-created on first sync if autoMigrate is enabled. Or create it manually."}}});}catch(R){d.push({name:`Table: ${S.tableName}`,category:"bigquery",status:"error",message:R?.message??String(R)});}if(g)for(let S of m){let R=`${y}-${S.name}`;try{let w=g.topic(R);if(typeof w.exists=="function"){let[v]=await w.exists();d.push({name:`Topic: ${R}`,category:"pubsub",status:v?"ok":"error",message:v?`Topic \`${R}\` exists`:`Topic \`${R}\` does not exist`,...!v&&{fix:{gcloud:`gcloud pubsub topics create ${R} --project=${t}`,console:`${u}/cloudpubsub/topic/list?project=${t}`}}});}else d.push({name:`Topic: ${R}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${R} --project=${t}`,console:`${u}/cloudpubsub/topic/list?project=${t}`,hint:"Ensure the topic exists. It is auto-created by the Firebase emulator but must exist in production."}});}catch(w){let v=w?.message??String(w),P=v.includes("disabled")||v.includes("has not been used");if(d.push({name:P?"Pub/Sub API":`Topic: ${R}`,category:"pubsub",status:"error",message:P?"Pub/Sub API is not enabled":v,fix:P?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${t}`,console:`${u}/apis/library/pubsub.googleapis.com?project=${t}`}:{gcloud:`gcloud pubsub topics create ${R} --project=${t}`,console:`${u}/cloudpubsub/topic/list?project=${t}`}}),P)break}}else d.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(j(l)){let S=d.every(R=>R.status==="ok");_(a,{project:t,healthy:S,checks:d});return}let T=S=>S==="ok"?'<span class="badge badge-ok">OK</span>':S==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',C={bigquery:d.filter(S=>S.category==="bigquery"),pubsub:d.filter(S=>S.category==="pubsub"),firestore:d.filter(S=>S.category==="firestore")},x=(S,R)=>{if(R.length===0)return "";let w=R.map(v=>{let P="";if(v.fix){let h=[];v.fix.hint&&h.push(`<p class="muted">${v.fix.hint}</p>`),v.fix.gcloud&&h.push(`<pre>$ ${v.fix.gcloud}</pre>`),v.fix.console&&h.push(`<p><a href="${v.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),P=`<div style="margin-top:.5rem">${h.join("")}</div>`;}return `<tr>
|
|
77
77
|
<td>${T(v.status)}</td>
|
|
78
78
|
<td><strong>${v.name}</strong><br><span class="muted">${v.message}</span>${P}</td>
|
|
79
79
|
</tr>`}).join(`
|
|
@@ -81,10 +81,10 @@ ${n}
|
|
|
81
81
|
<table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
|
|
82
82
|
<tbody>${w}</tbody></table>`},k=d.every(S=>S.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',O=E("Config Check",c,`<div class="card">
|
|
83
83
|
<p>Project: <code>${t}</code> ${k}</p>
|
|
84
|
-
${
|
|
85
|
-
${
|
|
86
|
-
${
|
|
87
|
-
</div>`);D(a,O);}),async(l,a)=>{await b.handle(l,a);}}var ae="firestore-sync";function ie(o,e){let n=e.ref?.path??void 0;return n?`${n}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${o}". Skipping.`),null)}function Q(o,e){let{onDocumentCreated:n,onDocumentUpdated:s,onDocumentDeleted:r}=e.deps.firestoreTriggers,p=e.deps.pubsub,g=e?.topicPrefix??ae,$={};for(let[i,f]of Object.entries(o)){let m=e?.repos?.[i],b;if(f._isGroup){if(!m?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${i}". Provide a triggerPath in the sync repos config for group collections.`);continue}b=m.triggerPath;}else b=m?.triggerPath??ie(i,f);if(!b)continue;let l=f._systemKeys?.[0]??"docId",a=`${g}-${i}`;$[`${i}_onCreate`]=n(b,async c=>{let t=c.data;if(!t)return;let u=t.data();if(!u)return;let y=String(u[l]??t.id),d=z(u,{exclude:m?.exclude,columnMap:m?.columnMap}),T={operation:"INSERT",repoName:i,docId:y,data:d,timestamp:new Date().toISOString()};await p.topic(a).publishMessage({json:T});}),$[`${i}_onUpdate`]=s(b,async c=>{let t=c.data?.after;if(!t)return;let u=t.data();if(!u)return;let y=String(u[l]??t.id),d=z(u,{exclude:m?.exclude,columnMap:m?.columnMap}),T={operation:"UPSERT",repoName:i,docId:y,data:d,timestamp:new Date().toISOString()};await p.topic(a).publishMessage({json:T});}),$[`${i}_onDelete`]=r(b,async c=>{let t=c.data;if(!t)return;let u=t.data(),y=String(u?.[l]??t.id),d={operation:"DELETE",repoName:i,docId:y,data:null,timestamp:new Date().toISOString()};await p.topic(a).publishMessage({json:d});});}return $}var Z=class{constructor(e){this.buffer=[];this.flushing=false;this.timer=null;this.adapter=e.adapter,this.tableName=e.tableName,this.primaryKey=e.primaryKey,this.batchSize=e.batchSize??100,this.onFlushError=e.onFlushError;let n=e.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...e){this.buffer.push(...e),this.buffer.length>=this.batchSize&&this.flush();}async flush(){if(this.flushing||this.buffer.length===0)return;this.flushing=true;let e=this.buffer.splice(0,this.batchSize);try{let n=[],s=[];for(let r of e)r.operation==="DELETE"?s.push(r.docId):r.data&&n.push(r.data);n.length>0&&await this.adapter.upsertRows(this.tableName,n,this.primaryKey),s.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,s);}catch(n){this.onFlushError?await this.onFlushError(e,n).catch(
|
|
84
|
+
${x("BigQuery",C.bigquery)}
|
|
85
|
+
${x("Pub/Sub",C.pubsub)}
|
|
86
|
+
${x("Firestore",C.firestore)}
|
|
87
|
+
</div>`);D(a,O);}),async(l,a)=>{await b.handle(l,a);}}var ae="firestore-sync";function ie(o,e){let n=e.ref?.path??void 0;return n?`${n}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${o}". Skipping.`),null)}function Q(o,e){let{onDocumentCreated:n,onDocumentUpdated:s,onDocumentDeleted:r}=e.deps.firestoreTriggers,p=e.deps.pubsub,g=e?.topicPrefix??ae,$={};for(let[i,f]of Object.entries(o)){let m=e?.repos?.[i],b;if(f._isGroup){if(!m?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${i}". Provide a triggerPath in the sync repos config for group collections.`);continue}b=m.triggerPath;}else b=m?.triggerPath??ie(i,f);if(!b)continue;let l=f._systemKeys?.[0]??"docId",a=`${g}-${i}`;$[`${i}_onCreate`]=n(b,async c=>{let t=c.data;if(!t)return;let u=t.data();if(!u)return;let y=String(u[l]??t.id),d=z(u,{exclude:m?.exclude,columnMap:m?.columnMap}),T={operation:"INSERT",repoName:i,docId:y,data:d,timestamp:new Date().toISOString()};await p.topic(a).publishMessage({json:T});}),$[`${i}_onUpdate`]=s(b,async c=>{let t=c.data?.after;if(!t)return;let u=t.data();if(!u)return;let y=String(u[l]??t.id),d=z(u,{exclude:m?.exclude,columnMap:m?.columnMap}),T={operation:"UPSERT",repoName:i,docId:y,data:d,timestamp:new Date().toISOString()};await p.topic(a).publishMessage({json:T});}),$[`${i}_onDelete`]=r(b,async c=>{let t=c.data;if(!t)return;let u=t.data(),y=String(u?.[l]??t.id),d={operation:"DELETE",repoName:i,docId:y,data:null,timestamp:new Date().toISOString()};await p.topic(a).publishMessage({json:d});});}return $}var Z=class{constructor(e){this.buffer=[];this.flushing=false;this.timer=null;this.adapter=e.adapter,this.tableName=e.tableName,this.primaryKey=e.primaryKey,this.batchSize=e.batchSize??100,this.onFlushError=e.onFlushError;let n=e.flushIntervalMs??5e3;n>0&&(this.timer=setInterval(()=>{this.flush();},n),typeof this.timer=="object"&&"unref"in this.timer&&this.timer.unref());}get size(){return this.buffer.length}enqueue(...e){this.buffer.push(...e),this.buffer.length>=this.batchSize&&this.flush();}async flush(){if(this.flushing||this.buffer.length===0)return;this.flushing=true;let e=this.buffer.splice(0,this.batchSize);try{let n=[],s=[];for(let r of e)r.operation==="DELETE"?s.push(r.docId):r.data&&n.push(r.data);n.length>0&&await this.adapter.upsertRows(this.tableName,n,this.primaryKey),s.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,s);}catch(n){this.onFlushError?await this.onFlushError(e,n).catch(s=>{console.error(`[SyncQueue] Flush error for ${this.tableName}:`,n),console.error("[SyncQueue] Error handler also failed:",s);}):(this.buffer.unshift(...e),console.error(`[SyncQueue] Flush failed for ${this.tableName}:`,n));}finally{this.flushing=false;}}async shutdown(){this.timer&&(clearInterval(this.timer),this.timer=null),await this.flush();}};var Y=new Set;async function ce(o,e,n,s,r,p,g){if(Y.has(o))return;let $=A(n,e.dialect,{primaryKey:r,exclude:p,columnMap:g});if(!await e.tableExists(s))await e.createTable({tableName:s,columns:$});else {let f=new Set(await e.getTableColumns(s)),m=$.filter(b=>!f.has(b.name));m.length>0&&await e.addColumns(s,m);}Y.add(o);}function B(o,e){let{deps:n,adapter:s,batchSize:r=100,flushIntervalMs:p=5e3,autoMigrate:g=false,topicPrefix:$="firestore-sync",repos:i={}}=e,f=new Map;function m(a,c){let t=f.get(a);if(t)return t;let y=i[a]?.tableName??a,d=async(T,C)=>{console.error(`[SyncWorker] Flush failed for "${a}" (${T.length} events):`,C);try{let x=`${$}-${a}-dlq`,N=n.pubsub.topic(x),[k]=await N.exists();k||(await N.create(),console.info(`[SyncWorker] Created DLQ topic "${x}"`));for(let O of T)await N.publishMessage({json:O});}catch(x){console.error(`[SyncWorker] Dead-letter publish also failed for ${a}:`,x);}};return t=new Z({adapter:s,tableName:y,primaryKey:c,batchSize:r,flushIntervalMs:p,onFlushError:d}),f.set(a,t),t}async function b(a){let{repoName:c}=a,t=o[c];if(!t){console.warn(`[SyncWorker] Unknown repo "${c}", skipping event`);return}let u=t._systemKeys?.[0]??t.documentKey??"docId",y=i[c],d=y?.columnMap,T=d?.[u]??u;if(g){let x=t.schema??void 0;if(x){let N=y?.tableName??c;await ce(c,s,x,N,u,y?.exclude,d);}}m(c,T).enqueue(a);}function l(a){return n.pubsubHandler.onMessagePublished(a,async c=>{let t=c.data?.message?.json??c.data?.json;if(!t){console.warn("[SyncWorker] Received empty PubSub message");return}await b(t);let u=f.get(t.repoName);u&&await u.flush();})}return {handleMessage:b,createHandler:l,queues:f,async shutdown(){let a=[];for(let c of f.values())a.push(c.shutdown());await Promise.all(a);}}}var de="firestore-sync";function X(o){if(typeof o!="function")return o;let e=o,n;return new Proxy({},{get(s,r){return n||(n=e()),n[r]},has(s,r){return n||(n=e()),r in n}})}function ue(o,e){let{deps:n,adapter:s,topicPrefix:r=de,batchSize:p,flushIntervalMs:g,autoMigrate:$,admin:i,repos:f}=e,m=X(n.pubsub),b=X(s),l=Q(o,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:m},topicPrefix:r,repos:f}),a=B(o,{deps:{pubsubHandler:n.pubsubHandler,pubsub:m},adapter:b,batchSize:p,flushIntervalMs:g,autoMigrate:$,topicPrefix:r,repos:f}),c={};for(let y of Object.keys(o))c[`sync_${y}`]=a.createHandler(`${r}-${y}`);let t=null;i&&(t=K(o,b,a.queues,a.handleMessage,i,f??{},m,r),c.adminsync=i.onRequest?i.httpsOptions?i.onRequest(i.httpsOptions,t):i.onRequest(t):t);let u={functions:{...l,...c},adminHandler:t,handleMessage:a.handleMessage,queues:a.queues,shutdown:a.shutdown};for(let y of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(u,y,{enumerable:false});return u}function ee(o,e){let n=e.columns.map(s=>{let r=s.isPrimaryKey?" NOT NULL":"";return ` ${o.quoteIdentifier(s.name)} ${s.sqlType}${r}`}).join(`,
|
|
88
88
|
`);return `CREATE TABLE IF NOT EXISTS ${o.quoteIdentifier(e.tableName)} (
|
|
89
89
|
${n}
|
|
90
90
|
);`}function le(o,e,n){return n.map(s=>`ALTER TABLE ${o.quoteIdentifier(e)} ADD COLUMN ${o.quoteIdentifier(s.name)} ${s.sqlType};`).join(`
|