@lpdjs/firestore-repo-service 2.1.14 → 2.1.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/sync/index.cjs +50 -46
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.js +50 -46
- package/dist/sync/index.js.map +1 -1
- package/package.json +1 -1
package/dist/sync/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
'use strict';function oe(
|
|
1
|
+
'use strict';function oe(r){let e=[],n=r.replace(/[.*+?^${}()|[\]\\]/g,i=>i===":"?i:`\\${i}`).replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g,(i,o)=>(e.push(o),"([^/]+)"));return {pattern:new RegExp(`^${n}$`),paramNames:e}}function se(r){let e=r.path??r.url??"/",n=e.indexOf("?");return n===-1?e:e.slice(0,n)}var L=class{constructor(){this.routes=[];this.middlewares=[];this.notFoundHandler=(e,n)=>{n.status(404).send("Not Found");};this.errorHandler=(e,n,i)=>{console.error("[MiniRouter]",e),i.status(500).send("Internal Server Error");};}use(e){return this.middlewares.push(e),this}get(e,n){return this.addRoute("GET",e,n)}post(e,n){return this.addRoute("POST",e,n)}put(e,n){return this.addRoute("PUT",e,n)}patch(e,n){return this.addRoute("PATCH",e,n)}delete(e,n){return this.addRoute("DELETE",e,n)}onNotFound(e){return this.notFoundHandler=e,this}onError(e){return this.errorHandler=e,this}addRoute(e,n,i){let{pattern:o,paramNames:g}=oe(n);return this.routes.push({method:e.toUpperCase(),pattern:o,paramNames:g,handler:i}),this}async handle(e,n){let i=(e.method??"GET").toUpperCase(),o=se(e),g=null,y={};for(let h of this.routes){if(h.method!==i)continue;let b=o.match(h.pattern);if(b){g=h,y={},h.paramNames.forEach((S,l)=>{y[S]=decodeURIComponent(b[l+1]??"");});break}}let R=Object.assign(e,{params:y}),u=g?g.handler:this.notFoundHandler;try{await this.runMiddlewareChain(R,n,u);}catch(h){this.errorHandler(h,e,n);}}async runMiddlewareChain(e,n,i){let o=0,g=async()=>{if(o<this.middlewares.length){let y=this.middlewares[o++];await y(e,n,g);}else await i(e,n);};await g();}};var ae={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 F(r){let e=r,n=e._zod?.def?.type;if(n)return ae[n]??`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`;let i=e._def?.typeName;return i||""}function W(r){let e=r;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function K(r){let e=r;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 ie=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function J(r){let e=r,n=false;for(;;){let i=F(e);if(!ie.has(i))break;(i==="ZodOptional"||i==="ZodNullable")&&(n=true);let o=W(e);if(!o)break;e=o;}return {inner:e,nullable:n}}var V={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function ce(r){let{inner:e}=J(r);return V[F(e)]??"json"}function Y(r,e,n,i,o,g,y,R){for(let[u,h]of Object.entries(r)){let b=n?`${n}__${u}`:u;if(o.has(u)||o.has(b))continue;let{inner:S,nullable:l}=J(h),a=F(S),s=i||l;if(a==="ZodObject"){let c=K(S);Y(c,e,b,s,o,g,y,R);continue}let t=V[a]??"json",d=b===y||u===y,f=g[b]??g[u]??b;R.push({name:f,sqlType:e.mapType(t),nullable:d?false:s,isPrimaryKey:d});}}function q(r,e,n={}){let{primaryKey:i,exclude:o=[],columnMap:g={}}=n,y=new Set(o),R=K(r),u=[];return Y(R,e,"",false,y,g,i,u),u}function Q(r){if(r==null)return null;if(typeof r=="object"&&typeof r.toDate=="function")return r.toDate().toISOString();if(r instanceof Date)return r.toISOString();if(Buffer.isBuffer(r))return r.toString("base64");if(r instanceof Uint8Array)return Buffer.from(r).toString("base64");if(typeof r=="object"&&"latitude"in r&&"longitude"in r){let e=r;return JSON.stringify({lat:e.latitude,lng:e.longitude})}return Array.isArray(r)?JSON.stringify(r.map(Q)):r}function X(r,e,n){for(let[i,o]of Object.entries(r)){let g=e?`${e}__${i}`:i;o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!Buffer.isBuffer(o)&&!(o instanceof Uint8Array)&&typeof o.toDate!="function"&&!("latitude"in o&&"longitude"in o)?X(o,g,n):n[g]=Q(o);}}function z(r,e){let n=new Set(e?.exclude),i=e?.columnMap??{},o={};X(r,"",o);let g={};for(let[y,R]of Object.entries(o)){if(n.has(y))continue;let u=y.split("__")[0];if(u!==y&&n.has(u))continue;let h=i[y]??(y.includes("__")?i[y.split("__").pop()]:void 0)??y;g[h]=R;}return g}async function U(r,e){let{pubsub:n,topicPrefix:i="firestore-sync",ordering:o=true,subscriptionSuffix:g="sync-sub",includeDLQ:y=true,ackDeadlineSeconds:R=60,messageRetentionDuration:u}=e,h={topics:[],subscriptions:[]};for(let b of Object.keys(r)){let S=`${i}-${b}`,l=`${i}-${b}-${g}`,a=n.topic(S),s=false,[t]=await a.exists();t||(await a.create(),s=true,console.info(`[ensureSyncInfra] Created topic "${S}"`)),h.topics.push({name:S,created:s});let d=a.subscription(l),[f]=await d.exists();if(!f)await d.create({enableMessageOrdering:o,ackDeadlineSeconds:R,...u?{messageRetentionDuration:u}:{}}),console.info(`[ensureSyncInfra] Created subscription "${l}" (ordering=${o})`),h.subscriptions.push({name:l,topic:S,created:true,orderingEnabled:o});else {let c,p=o;try{let[C]=await d.getMetadata();p=!!C?.enableMessageOrdering,p!==o&&(c=`Subscription "${l}" exists with enableMessageOrdering=${p}, but ordering=${o} was requested. This setting is immutable; delete and recreate the subscription to change it.`,console.warn(`[ensureSyncInfra] ${c}`));}catch{}h.subscriptions.push({name:l,topic:S,created:false,orderingEnabled:p,...c?{warning:c}:{}});}if(y){let c=`${i}-${b}-dlq`,p=n.topic(c),[C]=await p.exists(),w=false;C||(await p.create(),w=true,console.info(`[ensureSyncInfra] Created DLQ topic "${c}"`)),h.topics.push({name:c,created:w});}}return h}function I(r,e){if(process.env.FUNCTIONS_EMULATOR==="true"){let o=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??"demo-project",g=process.env.FUNCTION_REGION??"us-central1",y=(process.env.FUNCTION_TARGET??"").replace(/\./g,"-");return `/${o}/${g}/${y}${e}`}let n=process.env.K_SERVICE,i=r.hostname??r.headers?.host??"";return n&&i.includes("cloudfunctions.net")?`/${n.toLowerCase()}${e}`:e}function N(r,e,n){return `<!DOCTYPE html>
|
|
2
2
|
<html lang="en"><head>
|
|
3
3
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4
|
-
<title>${
|
|
4
|
+
<title>${r} \u2014 Sync Admin</title>
|
|
5
5
|
<style>
|
|
6
6
|
*{box-sizing:border-box;margin:0;padding:0}
|
|
7
7
|
body{font-family:system-ui,-apple-system,sans-serif;background:#f5f5f5;color:#1a1a1a;padding:2rem}
|
|
@@ -26,98 +26,102 @@
|
|
|
26
26
|
</style>
|
|
27
27
|
</head><body>
|
|
28
28
|
<nav><a href="${e}/">\u2190 Dashboard</a></nav>
|
|
29
|
-
<h1>${
|
|
29
|
+
<h1>${r}</h1>
|
|
30
30
|
${n}
|
|
31
|
-
</body></html>`}function O(
|
|
32
|
-
<td><strong>${
|
|
33
|
-
<td>${
|
|
34
|
-
<td>${
|
|
35
|
-
<td>${
|
|
31
|
+
</body></html>`}function O(r,e,n=200){r.status(n).set("Content-Type","text/html; charset=utf-8").send(e);}function _(r,e,n=200){r.status(n).set("Content-Type","application/json").send(JSON.stringify(e,null,2));}function j(r){return (r.headers?.accept??"").includes("application/json")}function B(r,e,n,i,o,g,y,R){let u=(o.basePath??"/").replace(/\/$/,"")||"",h=o.featuresFlag??{},b=[];for(let[l,a]of Object.entries(r)){let s=g[l];b.push({name:l,schema:a.schema??null,documentKey:a._systemKeys?.[0]??a.documentKey??"docId",tableName:s?.tableName??l,isGroup:!!a._isGroup,repoCfg:s,repo:a});}let S=new L;if(o.auth)if(typeof o.auth=="function")S.use(o.auth);else {let l=o.auth.realm??"Sync Admin",a="Basic "+Buffer.from(`${o.auth.username}:${o.auth.password}`).toString("base64");S.use((s,t,d)=>{if((s.headers?.authorization??"")!==a){t.status(401).set("WWW-Authenticate",`Basic realm="${l}"`).set("Content-Type","text/plain").send("Unauthorized");return}d();});}return S.get(`${u}/`,(l,a)=>{let s=I(l,u),t=b.map(p=>{let C=[];return h.healthCheck&&C.push(`<a class="btn" href="${s}/${p.name}/health">Health</a>`),h.manualSync&&C.push(`<a class="btn btn-primary" href="${s}/${p.name}/force-sync">Force Sync</a>`),`<tr>
|
|
32
|
+
<td><strong>${p.name}</strong></td>
|
|
33
|
+
<td>${p.tableName}</td>
|
|
34
|
+
<td>${p.isGroup?'<span class="badge badge-warn">group</span>':'<span class="badge badge-ok">collection</span>'}</td>
|
|
35
|
+
<td>${p.schema?"\u2713":"\u2717"}</td>
|
|
36
36
|
<td>${C.join(" ")}</td>
|
|
37
37
|
</tr>`}).join(`
|
|
38
|
-
`),d=
|
|
38
|
+
`),d=h.viewQueue?`<p><a class="btn" href="${s}/queues">View Queues</a></p>`:"",f=h.configCheck?`<p style="margin-top:.5rem"><a class="btn" href="${s}/config-check">\u2699 Config Check</a></p>`:"",c=N("Sync Dashboard",s,`<div class="card">
|
|
39
39
|
<table>
|
|
40
40
|
<thead><tr><th>Repository</th><th>Table</th><th>Type</th><th>Schema</th><th>Actions</th></tr></thead>
|
|
41
41
|
<tbody>${t}</tbody>
|
|
42
42
|
</table>
|
|
43
43
|
${d}
|
|
44
|
-
${
|
|
45
|
-
</div>`);O(a,c);}),S.get(`${u}`,(l,a)=>{let s=I(l,u);a.status(302).set("Location",`${s}/`).send("");}),
|
|
46
|
-
`),
|
|
44
|
+
${f}
|
|
45
|
+
</div>`);O(a,c);}),S.get(`${u}`,(l,a)=>{let s=I(l,u);a.status(302).set("Location",`${s}/`).send("");}),h.healthCheck&&S.get(`${u}/:repoName/health`,async(l,a)=>{let s=I(l,u),t=b.find(m=>m.name===l.params.repoName);if(!t){O(a,N("Not Found",s,`<p>Unknown repo: ${l.params.repoName}</p>`),404);return}if(!t.schema){O(a,N("Health Check",s,`<p class="badge badge-warn">No Zod schema attached to "${t.name}"</p>`));return}let d=q(t.schema,e.dialect,{primaryKey:t.documentKey,exclude:t.repoCfg?.exclude,columnMap:t.repoCfg?.columnMap}),f=[],c=false,p=null;try{c=await e.tableExists(t.tableName),c&&(f=await e.getTableColumns(t.tableName));}catch(m){p=m?.message??String(m);}let C=new Set(f),w=new Set(d.map(m=>m.name)),T=d.filter(m=>!C.has(m.name)),E=f.filter(m=>!w.has(m)),D=d.filter(m=>C.has(m.name)),P=c&&T.length===0&&!p;if(j(l)){_(a,{repo:t.name,table:t.tableName,tableExists:c,healthy:P,error:p,columns:{expected:d.map(m=>({name:m.name,type:m.sqlType,nullable:m.nullable,isPrimaryKey:m.isPrimaryKey})),actual:f,matched:D.map(m=>m.name),missing:T.map(m=>({name:m.name,type:m.sqlType})),extra:E}});return}let x=P?'<span class="badge badge-ok">Healthy</span>':'<span class="badge badge-err">Unhealthy</span>',$=d.map(m=>{let A=C.has(m.name)?'<span class="badge badge-ok">OK</span>':'<span class="badge badge-err">MISSING</span>';return `<tr><td>${m.name}</td><td>${m.sqlType}</td><td>${m.nullable?"Yes":"No"}</td><td>${m.isPrimaryKey?"\u2713":""}</td><td>${A}</td></tr>`}).join(`
|
|
46
|
+
`),k=E.map(m=>`<tr><td>${m}</td><td colspan="3" class="muted">not in schema</td><td><span class="badge badge-warn">EXTRA</span></td></tr>`).join(`
|
|
47
47
|
`),v=N(`Health: ${t.name}`,s,`<div class="card">
|
|
48
48
|
<p>Table: <code>${t.tableName}</code> ${c?x:'<span class="badge badge-err">NOT FOUND</span>'}</p>
|
|
49
|
-
${
|
|
49
|
+
${p?`<p class="badge badge-err">Error: ${p}</p>`:""}
|
|
50
50
|
<h2>Columns</h2>
|
|
51
51
|
<table>
|
|
52
52
|
<thead><tr><th>Column</th><th>SQL Type</th><th>Nullable</th><th>PK</th><th>Status</th></tr></thead>
|
|
53
|
-
<tbody>${
|
|
53
|
+
<tbody>${$}${k}</tbody>
|
|
54
54
|
</table>
|
|
55
|
-
</div>`);O(a,v);}),
|
|
55
|
+
</div>`);O(a,v);}),h.manualSync&&(S.get(`${u}/:repoName/force-sync`,(l,a)=>{let s=I(l,u),t=b.find(f=>f.name===l.params.repoName);if(!t){O(a,N("Not Found",s,`<p>Unknown repo: ${l.params.repoName}</p>`),404);return}let d=N(`Force Sync: ${t.name}`,s,`<div class="card">
|
|
56
56
|
<p>This will read <strong>all</strong> documents from the <code>${t.name}</code> Firestore collection
|
|
57
57
|
and upsert them into the <code>${t.tableName}</code> SQL table.</p>
|
|
58
58
|
<p class="muted" style="margin:.75rem 0">This may take a while for large collections.</p>
|
|
59
59
|
<form method="POST" action="${s}/${t.name}/force-sync">
|
|
60
60
|
<button type="submit" class="btn btn-primary">Start Force Sync</button>
|
|
61
61
|
</form>
|
|
62
|
-
</div>`);O(a,d);}),S.post(`${u}/:repoName/force-sync`,async(l,a)=>{let s=I(l,u),t=b.find(
|
|
63
|
-
<p class="badge badge-err">Error: ${
|
|
64
|
-
<p>Synced ${
|
|
65
|
-
</div>`),500);return}if(j(l)){
|
|
66
|
-
|
|
67
|
-
|
|
62
|
+
</div>`);O(a,d);}),S.post(`${u}/:repoName/force-sync`,async(l,a)=>{let s=I(l,u),t=b.find(P=>P.name===l.params.repoName);if(!t){_(a,{error:`Unknown repo: ${l.params.repoName}`},404);return}let d=t.repo.ref;if(!d){_(a,{error:`No collection reference for "${t.name}"`},400);return}let f=0,c=0,p=[],C=500,w=d.limit(C),T=null;try{for(;;){let $=await(T?w.startAfter(T):w).get();if($.empty)break;for(let k of $.docs){let v=k.data(),m=String(v[t.documentKey]??k.id),A=z(v,{exclude:t.repoCfg?.exclude,columnMap:t.repoCfg?.columnMap});try{await i({operation:"UPSERT",repoName:t.name,docId:m,data:A,timestamp:new Date().toISOString()}),f++;}catch(Z){c++;let re=Z?.message??String(Z);console.error(`[ForceSync:${t.name}] doc=${m} failed:`,Z),p.length<5&&p.push(`${m}: ${re}`);}}if(T=$.docs[$.docs.length-1],$.docs.length<C)break}let P=n.get(t.name);P&&await P.flush();}catch(P){if(j(l)){_(a,{error:P?.message??String(P),synced:f,errors:c},500);return}O(a,N(`Force Sync: ${t.name}`,s,`<div class="card">
|
|
63
|
+
<p class="badge badge-err">Error: ${P?.message??String(P)}</p>
|
|
64
|
+
<p>Synced ${f} docs before failure (${c} errors).</p>
|
|
65
|
+
</div>`),500);return}if(j(l)){_(a,{repo:t.name,table:t.tableName,synced:f,errors:c,...p.length>0&&{errorSamples:p}});return}let E=p.length>0?`<details style="margin-top:1rem"><summary>First ${p.length} error(s)</summary>
|
|
66
|
+
<pre style="white-space:pre-wrap">${p.map(P=>P.replace(/[<>&]/g,x=>`&#${x.charCodeAt(0)};`)).join(`
|
|
67
|
+
|
|
68
|
+
`)}</pre></details>`:"",D=N(`Force Sync: ${t.name}`,s,`<div class="card">
|
|
69
|
+
<p class="badge ${c>0?"badge-warn":"badge-ok"}">${c>0?"Completed with errors":"Complete"}</p>
|
|
70
|
+
<p>Synced <strong>${f}</strong> documents to <code>${t.tableName}</code>.</p>
|
|
68
71
|
${c>0?`<p class="badge badge-warn">${c} error(s)</p>`:""}
|
|
69
|
-
|
|
70
|
-
|
|
72
|
+
${E}
|
|
73
|
+
</div>`);O(a,D);})),h.viewQueue&&S.get(`${u}/queues`,(l,a)=>{let s=I(l,u),t=[];for(let c of b){let p=n.get(c.name);t.push({repo:c.name,table:c.tableName,pending:p?p.size:0});}if(j(l)){_(a,{queues:t});return}let d=t.map(c=>`<tr><td>${c.repo}</td><td>${c.table}</td><td>${c.pending===0?'<span class="badge badge-ok">0</span>':`<span class="badge badge-warn">${c.pending}</span>`}</td></tr>`).join(`
|
|
74
|
+
`),f=N("Sync Queues",s,`<div class="card">
|
|
71
75
|
<table>
|
|
72
76
|
<thead><tr><th>Repository</th><th>Table</th><th>Pending</th></tr></thead>
|
|
73
77
|
<tbody>${d}</tbody>
|
|
74
78
|
</table>
|
|
75
|
-
</div>`);O(a,
|
|
76
|
-
`),console:`${d}/iam-admin/iam?project=${t}`}}):
|
|
77
|
-
<td>${
|
|
78
|
-
<td><strong>${v.name}</strong><br><span class="muted">${v.message}</span>${
|
|
79
|
+
</div>`);O(a,f);}),h.configCheck&&(S.get(`${u}/config-check`,async(l,a)=>{let s=I(l,u),t=process.env.GCLOUD_PROJECT??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCP_PROJECT??"unknown",d="https://console.cloud.google.com",f=R??"firestore-sync",c=[];try{await e.tableExists("__nonexistent_health_check__"),c.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable"});}catch(x){let $=x?.message??String(x),k=$.toLowerCase(),v=k.includes("disabled")||k.includes("has not been used")||k.includes("accessnotconfigured"),m=k.includes("permission")||$.includes("403")||k.includes("access denied"),A=k.includes("project")&&k.includes("not found"),Z=k.includes("not found")||$.includes("404");v?c.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:`${d}/apis/library/bigquery.googleapis.com?project=${t}`}}):A?c.push({name:"BigQuery Project",category:"bigquery",status:"error",message:$,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:`${d}/home/dashboard`}}):m?c.push({name:"BigQuery API",category:"bigquery",status:"error",message:`Permission denied: ${$}`,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(`
|
|
80
|
+
`),console:`${d}/iam-admin/iam?project=${t}`}}):Z?c.push({name:"BigQuery Dataset",category:"bigquery",status:"error",message:`Dataset not found: ${$}`,fix:{hint:"Create the dataset first",gcloud:`bq mk --dataset ${t}:YOUR_DATASET_ID`,console:`${d}/bigquery?project=${t}`}}):c.push({name:"BigQuery API",category:"bigquery",status:"ok",message:"BigQuery API is reachable (table lookup returned expected error)"});}for(let x of b)try{let $=await e.tableExists(x.tableName);c.push({name:`Table: ${x.tableName}`,category:"bigquery",status:$?"ok":"warn",message:$?`Table \`${x.tableName}\` exists`:`Table \`${x.tableName}\` does not exist yet`,...!$&&{fix:{hint:"Table will be auto-created on first sync if autoMigrate is enabled. Or create it manually."}}});}catch($){c.push({name:`Table: ${x.tableName}`,category:"bigquery",status:"error",message:$?.message??String($)});}if(y)for(let x of b){let $=`${f}-${x.name}`;try{let k=y.topic($);if(typeof k.exists=="function"){let[v]=await k.exists();c.push({name:`Topic: ${$}`,category:"pubsub",status:v?"ok":"error",message:v?`Topic \`${$}\` exists`:`Topic \`${$}\` does not exist`,...!v&&{fix:{gcloud:`gcloud pubsub topics create ${$} --project=${t}`,console:`${d}/cloudpubsub/topic/list?project=${t}`}}});}else c.push({name:`Topic: ${$}`,category:"pubsub",status:"warn",message:"Cannot verify topic existence (PubSub client doesn't expose .exists())",fix:{gcloud:`gcloud pubsub topics create ${$} --project=${t}`,console:`${d}/cloudpubsub/topic/list?project=${t}`,hint:"Ensure the topic exists. It is auto-created by the Firebase emulator but must exist in production."}});}catch(k){let v=k?.message??String(k),m=v.includes("disabled")||v.includes("has not been used");if(c.push({name:m?"Pub/Sub API":`Topic: ${$}`,category:"pubsub",status:"error",message:m?"Pub/Sub API is not enabled":v,fix:m?{gcloud:`gcloud services enable pubsub.googleapis.com --project=${t}`,console:`${d}/apis/library/pubsub.googleapis.com?project=${t}`}:{gcloud:`gcloud pubsub topics create ${$} --project=${t}`,console:`${d}/cloudpubsub/topic/list?project=${t}`}}),m)break}}else c.push({name:"Pub/Sub Client",category:"pubsub",status:"warn",message:"PubSub client not available for config check"});if(j(l)){let x=c.every($=>$.status==="ok");_(a,{project:t,healthy:x,checks:c});return}let p=x=>x==="ok"?'<span class="badge badge-ok">OK</span>':x==="warn"?'<span class="badge badge-warn">WARN</span>':'<span class="badge badge-err">ERROR</span>',C={bigquery:c.filter(x=>x.category==="bigquery"),pubsub:c.filter(x=>x.category==="pubsub"),firestore:c.filter(x=>x.category==="firestore")},w=(x,$)=>{if($.length===0)return "";let k=$.map(v=>{let m="";if(v.fix){let A=[];v.fix.hint&&A.push(`<p class="muted">${v.fix.hint}</p>`),v.fix.gcloud&&A.push(`<pre>$ ${v.fix.gcloud}</pre>`),v.fix.console&&A.push(`<p><a href="${v.fix.console}" target="_blank">Open GCP Console \u2192</a></p>`),m=`<div style="margin-top:.5rem">${A.join("")}</div>`;}return `<tr>
|
|
81
|
+
<td>${p(v.status)}</td>
|
|
82
|
+
<td><strong>${v.name}</strong><br><span class="muted">${v.message}</span>${m}</td>
|
|
79
83
|
</tr>`}).join(`
|
|
80
84
|
`);return `<h2>${x}</h2>
|
|
81
85
|
<table><thead><tr><th style="width:80px">Status</th><th>Check</th></tr></thead>
|
|
82
|
-
<tbody>${
|
|
86
|
+
<tbody>${k}</tbody></table>`},E=c.every(x=>x.status==="ok")?'<span class="badge badge-ok">All checks passed</span>':'<span class="badge badge-warn">Some issues found</span>',D=y?`<form method="POST" action="${s}/config-check/setup-pubsub" style="display:inline">
|
|
83
87
|
<button type="submit" class="btn btn-primary">\u2699 Setup Pub/Sub (topics + subscriptions)</button>
|
|
84
88
|
</form>
|
|
85
89
|
<p class="muted" style="margin-top:.5rem">
|
|
86
90
|
Idempotent. Creates missing topics and subscriptions with
|
|
87
|
-
<code>enableMessageOrdering=${
|
|
91
|
+
<code>enableMessageOrdering=${o.pubsubSetup?.ordering??true}</code>.
|
|
88
92
|
Existing subscriptions are kept as-is (the ordering flag is immutable).
|
|
89
|
-
</p>`:"",
|
|
90
|
-
<p>Project: <code>${t}</code> ${
|
|
93
|
+
</p>`:"",P=N("Config Check",s,`<div class="card">
|
|
94
|
+
<p>Project: <code>${t}</code> ${E}</p>
|
|
91
95
|
${w("BigQuery",C.bigquery)}
|
|
92
96
|
${w("Pub/Sub",C.pubsub)}
|
|
93
97
|
${w("Firestore",C.firestore)}
|
|
94
98
|
${D?`<hr style="margin:1.5rem 0"><h2>Actions</h2>${D}`:""}
|
|
95
|
-
</div>`);O(a,
|
|
96
|
-
`),c=d.subscriptions.map(
|
|
97
|
-
<td><code>${
|
|
98
|
-
<td><code>${
|
|
99
|
-
<td>${
|
|
100
|
-
<td>${
|
|
101
|
-
<td>${
|
|
99
|
+
</div>`);O(a,P);}),y&&S.post(`${u}/config-check/setup-pubsub`,async(l,a)=>{let s=I(l,u),t=o.pubsubSetup??{};try{let d=await U(r,{pubsub:y,topicPrefix:R??"firestore-sync",ordering:t.ordering??!0,subscriptionSuffix:t.subscriptionSuffix??"sync-sub",includeDLQ:t.includeDLQ??!0,ackDeadlineSeconds:t.ackDeadlineSeconds??60,...t.messageRetentionDuration&&{messageRetentionDuration:t.messageRetentionDuration}});if(j(l)){_(a,{ok:!0,...d});return}let f=d.topics.map(p=>`<tr><td><code>${p.name}</code></td><td>${p.created?'<span class="badge badge-ok">created</span>':'<span class="badge">already exists</span>'}</td></tr>`).join(`
|
|
100
|
+
`),c=d.subscriptions.map(p=>`<tr>
|
|
101
|
+
<td><code>${p.name}</code></td>
|
|
102
|
+
<td><code>${p.topic}</code></td>
|
|
103
|
+
<td>${p.created?'<span class="badge badge-ok">created</span>':'<span class="badge">already exists</span>'}</td>
|
|
104
|
+
<td>${p.orderingEnabled?"\u2713":"\u2717"}</td>
|
|
105
|
+
<td>${p.warning?`<span class="badge badge-warn">${p.warning}</span>`:""}</td>
|
|
102
106
|
</tr>`).join(`
|
|
103
107
|
`);O(a,N("Pub/Sub Setup",s,`<div class="card">
|
|
104
108
|
<p><span class="badge badge-ok">Setup complete</span></p>
|
|
105
109
|
<h2>Topics</h2>
|
|
106
110
|
<table><thead><tr><th>Name</th><th>Status</th></tr></thead>
|
|
107
|
-
<tbody>${
|
|
111
|
+
<tbody>${f}</tbody></table>
|
|
108
112
|
<h2>Subscriptions</h2>
|
|
109
113
|
<table><thead><tr><th>Name</th><th>Topic</th><th>Status</th><th>Ordering</th><th>Notes</th></tr></thead>
|
|
110
114
|
<tbody>${c}</tbody></table>
|
|
111
115
|
<p style="margin-top:1rem"><a class="btn" href="${s}/config-check">\u2190 Back to Config Check</a></p>
|
|
112
|
-
</div>`));}catch(d){let
|
|
116
|
+
</div>`));}catch(d){let f=d?.message??String(d);if(j(l)){_(a,{ok:false,error:f},500);return}O(a,N("Pub/Sub Setup \u2014 Error",s,`<div class="card">
|
|
113
117
|
<p><span class="badge badge-err">Setup failed</span></p>
|
|
114
|
-
<pre>${
|
|
118
|
+
<pre>${f}</pre>
|
|
115
119
|
<p><a class="btn" href="${s}/config-check">\u2190 Back</a></p>
|
|
116
|
-
</div>`),500);}})),async(l,a)=>{await S.handle(l,a);}}var
|
|
117
|
-
`);return `CREATE TABLE IF NOT EXISTS ${
|
|
120
|
+
</div>`),500);}})),async(l,a)=>{await S.handle(l,a);}}var de="firestore-sync";function ue(r,e){let n=e.ref?.path??void 0;return n?`${n}/{docId}`:(console.warn(`[SyncTriggers] Cannot determine collection path for "${r}". Skipping.`),null)}function H(r,e){let{onDocumentCreated:n,onDocumentUpdated:i,onDocumentDeleted:o}=e.deps.firestoreTriggers,g=e.deps.pubsub,y=e?.topicPrefix??de,R={},u=e?.ordering,h=!!u,b=typeof u=="function"?u:u===true?s=>s.docId:null,S=new Map;function l(s){let t=S.get(s);return t||(t=h?g.topic(s,{messageOrdering:true}):g.topic(s),S.set(s,t),t)}async function a(s,t){let d=l(s),f=b?b(t):void 0;try{await d.publishMessage(f!==void 0?{json:t,orderingKey:f}:{json:t});}catch(c){throw f!==void 0&&typeof d.resumePublishing=="function"&&d.resumePublishing(f),c}}for(let[s,t]of Object.entries(r)){let d=e?.repos?.[s],f;if(t._isGroup){if(!d?.triggerPath){console.warn(`[SyncTriggers] Skipping collection-group repo "${s}". Provide a triggerPath in the sync repos config for group collections.`);continue}f=d.triggerPath;}else f=d?.triggerPath??ue(s,t);if(!f)continue;let c=t._systemKeys?.[0]??"docId",p=`${y}-${s}`;R[`${s}_onCreate`]=n(f,async C=>{let w=C.data;if(!w)return;let T=w.data();if(!T)return;let E=String(T[c]??w.id),D=z(T,{exclude:d?.exclude,columnMap:d?.columnMap}),P={operation:"INSERT",repoName:s,docId:E,data:D,timestamp:new Date().toISOString()};await a(p,P);}),R[`${s}_onUpdate`]=i(f,async C=>{let w=C.data?.after;if(!w)return;let T=w.data();if(!T)return;let E=String(T[c]??w.id),D=z(T,{exclude:d?.exclude,columnMap:d?.columnMap}),P={operation:"UPSERT",repoName:s,docId:E,data:D,timestamp:new Date().toISOString()};await a(p,P);}),R[`${s}_onDelete`]=o(f,async C=>{let w=C.data;if(!w)return;let T=w.data(),E=String(T?.[c]??w.id),D={operation:"DELETE",repoName:s,docId:E,data:null,timestamp:new Date().toISOString()};await a(p,D);});}return R}var M=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=[],i=[];for(let o of e)o.operation==="DELETE"?i.push(o.docId):o.data&&n.push(o.data);n.length>0&&await this.adapter.upsertRows(this.tableName,n,this.primaryKey),i.length>0&&await this.adapter.deleteRows(this.tableName,this.primaryKey,i);}catch(n){this.onFlushError?await this.onFlushError(e,n).catch(i=>{console.error(`[SyncQueue] Flush error for ${this.tableName}:`,n),console.error("[SyncQueue] Error handler also failed:",i);}):(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 ee=new Set;async function le(r,e,n,i,o,g,y){if(ee.has(r))return;let R=q(n,e.dialect,{primaryKey:o,exclude:g,columnMap:y});if(!await e.tableExists(i))await e.createTable({tableName:i,columns:R});else {let h=new Set(await e.getTableColumns(i)),b=R.filter(S=>!h.has(S.name));b.length>0&&await e.addColumns(i,b);}ee.add(r);}function G(r,e){let{deps:n,adapter:i,batchSize:o=100,flushIntervalMs:g=5e3,autoMigrate:y=false,topicPrefix:R="firestore-sync",repos:u={}}=e,h=new Map;function b(a,s){let t=h.get(a);if(t)return t;let f=u[a]?.tableName??a,c=async(p,C)=>{console.error(`[SyncWorker] Flush failed for "${a}" (${p.length} events):`,C);try{let w=`${R}-${a}-dlq`,T=n.pubsub.topic(w),[E]=await T.exists();E||(await T.create(),console.info(`[SyncWorker] Created DLQ topic "${w}"`));for(let D of p)await T.publishMessage({json:D});}catch(w){console.error(`[SyncWorker] Dead-letter publish also failed for ${a}:`,w);}};return t=new M({adapter:i,tableName:f,primaryKey:s,batchSize:o,flushIntervalMs:g,onFlushError:c}),h.set(a,t),t}async function S(a){let{repoName:s}=a,t=r[s];if(!t){console.warn(`[SyncWorker] Unknown repo "${s}", skipping event`);return}let d=t._systemKeys?.[0]??t.documentKey??"docId",f=u[s],c=f?.columnMap,p=c?.[d]??d;if(y){let w=t.schema??void 0;if(w){let T=f?.tableName??s;await le(s,i,w,T,d,f?.exclude,c);}}b(s,p).enqueue(a);}function l(a){return n.pubsubHandler.onMessagePublished(a,async s=>{let t=s.data?.message?.json??s.data?.json;if(!t){console.warn("[SyncWorker] Received empty PubSub message");return}await S(t);let d=h.get(t.repoName);d&&await d.flush();})}return {handleMessage:S,createHandler:l,queues:h,async shutdown(){let a=[];for(let s of h.values())a.push(s.shutdown());await Promise.all(a);}}}var pe="firestore-sync";function te(r){if(typeof r!="function")return r;let e=r,n;return new Proxy({},{get(i,o){return n||(n=e()),n[o]},has(i,o){return n||(n=e()),o in n}})}function fe(r,e){let{deps:n,adapter:i,topicPrefix:o=pe,batchSize:g,flushIntervalMs:y,autoMigrate:R,admin:u,repos:h}=e,b=te(n.pubsub),S=te(i),l=H(r,{deps:{firestoreTriggers:n.firestoreTriggers,pubsub:b},topicPrefix:o,repos:h}),a=G(r,{deps:{pubsubHandler:n.pubsubHandler,pubsub:b},adapter:S,batchSize:g,flushIntervalMs:y,autoMigrate:R,topicPrefix:o,repos:h}),s={};for(let f of Object.keys(r))s[`sync_${f}`]=a.createHandler(`${o}-${f}`);let t=null;u&&(t=B(r,S,a.queues,a.handleMessage,u,h??{},b,o),s.adminsync=u.onRequest?u.httpsOptions?u.onRequest(u.httpsOptions,t):u.onRequest(t):t);let d={functions:{...l,...s},adminHandler:t,handleMessage:a.handleMessage,queues:a.queues,shutdown:a.shutdown};for(let f of ["adminHandler","handleMessage","queues","shutdown"])Object.defineProperty(d,f,{enumerable:false});return d}function ne(r,e){let n=e.columns.map(i=>{let o=i.isPrimaryKey?" NOT NULL":"";return ` ${r.quoteIdentifier(i.name)} ${i.sqlType}${o}`}).join(`,
|
|
121
|
+
`);return `CREATE TABLE IF NOT EXISTS ${r.quoteIdentifier(e.tableName)} (
|
|
118
122
|
${n}
|
|
119
|
-
);`}function
|
|
120
|
-
`)}function
|
|
123
|
+
);`}function ge(r,e,n){return n.map(i=>`ALTER TABLE ${r.quoteIdentifier(e)} ADD COLUMN ${r.quoteIdentifier(i.name)} ${i.sqlType};`).join(`
|
|
124
|
+
`)}function me(r,e,n){let i=[];for(let[o,g]of Object.entries(r)){let y=g.schema??g._schema??void 0;if(!y)continue;let R=n?.repos?.[o],u=R?.tableName??o,h=g._systemKeys?.[0]??g.documentKey??"docId",b=q(y,e,{primaryKey:h,exclude:R?.exclude,columnMap:R?.columnMap}),S={tableName:u,columns:b};i.push(ne(e,S));}return i.join(`
|
|
121
125
|
|
|
122
|
-
`)}async function
|
|
126
|
+
`)}async function ye(r,e,n){let i={created:[],altered:[],upToDate:[],skipped:[]};for(let[o,g]of Object.entries(r)){let y=g.schema??void 0;if(!y){i.skipped.push(o);continue}let R=n?.repos?.[o],u=R?.tableName??o,h=g._systemKeys?.[0]??g.documentKey??"docId",b=q(y,e.dialect,{primaryKey:h,exclude:R?.exclude,columnMap:R?.columnMap}),S={tableName:u,columns:b};if(!await e.tableExists(u))await e.createTable(S),i.created.push(u);else {let a=new Set(await e.getTableColumns(u)),s=b.filter(t=>!a.has(t.name));s.length>0?(await e.addColumns(u,s),i.altered.push(u)):i.upToDate.push(u);}}return i}exports.SyncQueue=M;exports.addColumnsDDL=ge;exports.autoMigrate=ye;exports.createFirestoreSync=fe;exports.createSyncTriggers=H;exports.createSyncWorker=G;exports.createTableDDL=ne;exports.createadminsyncServer=B;exports.ensureSyncInfra=U;exports.generateDDL=me;exports.serializeDocument=z;exports.serializeValue=Q;exports.zodSchemaToColumns=q;exports.zodTypeToLogical=ce;//# sourceMappingURL=index.cjs.map
|
|
123
127
|
//# sourceMappingURL=index.cjs.map
|