@lpdjs/firestore-repo-service 2.6.58 → 3.0.2

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 (40) hide show
  1. package/README.md +45 -27
  2. package/dist/{create-servers-Cp1dwiBW.d.ts → create-servers-2Hw0pkyz.d.ts} +2 -2
  3. package/dist/{create-servers-vrDTAYk3.d.cts → create-servers-ASLcxpiS.d.cts} +2 -2
  4. package/dist/index.cjs +106 -94
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +3 -3
  7. package/dist/index.d.ts +3 -3
  8. package/dist/index.js +106 -94
  9. package/dist/index.js.map +1 -1
  10. package/dist/llms-full.txt +237 -263
  11. package/dist/llms.txt +5 -4
  12. package/dist/{queue-DO0af0iY.d.ts → queue-B9jCT62h.d.cts} +8 -23
  13. package/dist/{queue-LLW6fbO6.d.cts → queue-BWi6TBmf.d.ts} +8 -23
  14. package/dist/servers/index.cjs +104 -92
  15. package/dist/servers/index.cjs.map +1 -1
  16. package/dist/servers/index.d.cts +3 -3
  17. package/dist/servers/index.d.ts +3 -3
  18. package/dist/servers/index.js +104 -92
  19. package/dist/servers/index.js.map +1 -1
  20. package/dist/sync/bigquery.cjs +5 -5
  21. package/dist/sync/bigquery.cjs.map +1 -1
  22. package/dist/sync/bigquery.d.cts +27 -2
  23. package/dist/sync/bigquery.d.ts +27 -2
  24. package/dist/sync/bigquery.js +5 -5
  25. package/dist/sync/bigquery.js.map +1 -1
  26. package/dist/sync/index.cjs +74 -54
  27. package/dist/sync/index.cjs.map +1 -1
  28. package/dist/sync/index.d.cts +62 -16
  29. package/dist/sync/index.d.ts +62 -16
  30. package/dist/sync/index.js +74 -54
  31. package/dist/sync/index.js.map +1 -1
  32. package/dist/sync/meilisearch.cjs +4 -0
  33. package/dist/sync/meilisearch.cjs.map +1 -0
  34. package/dist/sync/meilisearch.d.cts +114 -0
  35. package/dist/sync/meilisearch.d.ts +114 -0
  36. package/dist/sync/meilisearch.js +4 -0
  37. package/dist/sync/meilisearch.js.map +1 -0
  38. package/dist/{types-BaFkMwNb.d.ts → types-BRPhmKFW.d.ts} +106 -44
  39. package/dist/{types-CbNcdNkb.d.cts → types-LZ8dyfBz.d.cts} +106 -44
  40. package/package.json +19 -1
@@ -1,8 +1,8 @@
1
- 'use strict';var E=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var m="__sync_version";function h(s){let t=s.toUpperCase();switch(t){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return t}}var p=class{constructor(){this.name="bigquery";}mapType(t){switch(t){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(t){return "`"+t.replace(/`/g,"``")+"`"}},C=new p,u=null;function I(){return u||(u=E("@google-cloud/bigquery-storage"),u)}function f(s){let t;return typeof s=="bigint"?t=s:typeof s=="number"||typeof s=="string"?t=BigInt(s):t=0n,t<0n&&(t=0n),t.toString(16).padStart(16,"0")}function N(s){if(!s||typeof s!="object")return false;let t=s;return t.code===4||t.code===10||t.code===13||t.code===14}async function R(s,t=6,e=200){let n=0;for(;;)try{return await s()}catch(r){if(n++,!N(r)||n>t)throw r;let i=e*Math.pow(2,n),a=Math.random()*i;await new Promise(c=>setTimeout(c,a));}}var g=class g{constructor(t){this.writers=new Map;this.bigquery=t.bigquery,this.projectId=t.projectId,this.datasetId=t.datasetId,this.maxStaleness=t.maxStaleness===void 0?"INTERVAL 15 MINUTE":t.maxStaleness,this.writerClient=t.writerClient;}get dialect(){return C}async tableExists(t){let[e]=await this.dataset.table(t).exists();return e}async getTableColumns(t){let[e]=await this.dataset.table(t).getMetadata();return (e.schema?.fields??[]).map(r=>r.name)}async getTableColumnsWithTypes(t){let[e]=await this.dataset.table(t).getMetadata(),n=e.schema?.fields??[],r=new Map;for(let i of n)r.set(i.name,h(i.type));return r}async createTable(t){let e=o=>this.dialect.quoteIdentifier(o),n=t.columns.find(o=>o.isPrimaryKey)?.name;if(!n)throw new Error(`BigQueryAdapter requires a primary key on table \`${t.tableName}\` (Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`);let r=t.columns.map(o=>{let d=o.isPrimaryKey?" NOT NULL":"";return ` ${e(o.name)} ${o.sqlType}${d}`}).join(`,
2
- `),i=[];this.maxStaleness!==null&&i.push(`max_staleness = ${this.maxStaleness}`);let a=i.length>0?`
3
- OPTIONS(${i.join(", ")})`:"",c=`CREATE TABLE IF NOT EXISTS ${this.fqn(t.tableName)} (
1
+ 'use strict';var O=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var g="__sync_version";var v={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 w(i){let e=i,t=e._zod?.def?.type;if(t)return v[t]??`Zod${t.charAt(0).toUpperCase()}${t.slice(1)}`;let n=e._def?.typeName;return n||""}function R(i){let e=i;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function b(i){let e=i;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 P=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function M(i){let e=i,t=false;for(;;){let n=w(e);if(!P.has(n))break;(n==="ZodOptional"||n==="ZodNullable")&&(t=true);let r=R(e);if(!r)break;e=r;}return {inner:e,nullable:t}}var D={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function _(i,e,t,n,r,s,o,d){for(let[a,p]of Object.entries(i)){let u=t?`${t}__${a}`:a;if(r.has(a)||r.has(u))continue;let{inner:l,nullable:y}=M(p),f=w(l),h=n||y;if(f==="ZodObject"){let x=b(l);_(x,e,u,h,r,s,o,d);continue}let c=D[f]??"json",N=u===o||a===o,q=s[u]??s[a]??u;d.push({name:q,sqlType:e.mapType(c),nullable:N?false:h,isPrimaryKey:N});}}function C(i,e,t={}){let{primaryKey:n,exclude:r=[],columnMap:s={}}=t,o=new Set(r),d=b(i),a=[];return _(d,e,"",false,o,s,n,a),a.some(p=>p.name===g)||a.push({name:g,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),a}function T(i){let e=i.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function z(i,e){let t=T(i),n=T(e);return t===n?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[t]?.includes(n)??false}var E=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,"``")+"`"}},k=new E,S=null;function L(){return S||(S=O("@google-cloud/bigquery-storage"),S)}function I(i){let e;return typeof i=="bigint"?e=i:typeof i=="number"||typeof i=="string"?e=BigInt(i):e=0n,e<0n&&(e=0n),e.toString(16).padStart(16,"0")}function B(i){if(!i||typeof i!="object")return false;let e=i;return e.code===4||e.code===10||e.code===13||e.code===14}async function j(i,e=6,t=200){let n=0;for(;;)try{return await i()}catch(r){if(n++,!B(r)||n>e)throw r;let s=t*Math.pow(2,n),o=Math.random()*s;await new Promise(d=>setTimeout(d,o));}}var Z=class extends Error{constructor(t,n,r,s){super(`Schema drift detected on \`${t}\`: column \`${n}\` has type ${r} 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=n;this.existingType=r;this.desiredType=s;this.name="SchemaTypeMismatchError";}},m=class m{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 k}async targetExists(e){return this.tableExists(e)}async upsert(e,t,n){return this.upsertRows(e,t,n)}async delete(e,t,n){return this.deleteRows(e,t,n)}async ensureTarget(e){if(!e.schema)return;let{targetName:t,primaryKey:n,schema:r,exclude:s,columnMap:o}=e,d=C(r,this.dialect,{primaryKey:n,exclude:s,columnMap:o});if(!await this.tableExists(t))await this.createTable({tableName:t,columns:d});else {let p=await this.getTableColumnsWithTypes(t),u=[];for(let l of d){let y=p.get(l.name);if(y===void 0){u.push(l);continue}if(!z(y,l.sqlType))throw new Z(t,l.name,y,l.sqlType)}u.length>0&&(await this.addColumns(t,u),await this.onSchemaChange?.(t));}}async healthCheck(e){let{targetName:t,primaryKey:n,schema:r,repoConfig:s}=e;if(!r)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 d=await this.getTableColumns(t),a=C(r,this.dialect,{primaryKey:n,exclude:s?.exclude,columnMap:s?.columnMap}),p=new Set(d),u=new Set(a.map(c=>c.name)),l=a.filter(c=>!p.has(c.name)),y=d.filter(c=>!u.has(c)),f=a.filter(c=>p.has(c.name)),h=l.length===0;return {healthy:h,targetName:t,targetExists:!0,error:h?null:`Missing columns: ${l.map(c=>c.name).join(", ")}`,details:{expected:a.map(c=>({name:c.name,type:c.sqlType,nullable:c.nullable,isPrimaryKey:c.isPrimaryKey})),actual:d,matched:f.map(c=>c.name),missing:l.map(c=>({name:c.name,type:c.sqlType})),extra:y}}}catch(o){return {healthy:false,targetName:t,targetExists:false,error:o?.message??String(o)}}}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(r=>r.name)}async getTableColumnsWithTypes(e){let[t]=await this.dataset.table(e).getMetadata(),n=t.schema?.fields??[],r=new Map;for(let s of n)r.set(s.name,T(s.type));return r}async createTable(e){let t=a=>this.dialect.quoteIdentifier(a),n=e.columns.find(a=>a.isPrimaryKey)?.name;if(!n)throw new Error(`BigQueryAdapter requires a primary key on table \`${e.tableName}\` (Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`);let r=e.columns.map(a=>{let p=a.isPrimaryKey?" NOT NULL":"";return ` ${t(a.name)} ${a.sqlType}${p}`}).join(`,
2
+ `),s=[];this.maxStaleness!==null&&s.push(`max_staleness = ${this.maxStaleness}`);let o=s.length>0?`
3
+ OPTIONS(${s.join(", ")})`:"",d=`CREATE TABLE IF NOT EXISTS ${this.fqn(e.tableName)} (
4
4
  ${r},
5
- PRIMARY KEY (${e(n)}) NOT ENFORCED
5
+ PRIMARY KEY (${t(n)}) NOT ENFORCED
6
6
  )
7
- CLUSTER BY ${e(n)}${a};`;await this.bigquery.query({query:c});}async addColumns(t,e){let n=r=>this.dialect.quoteIdentifier(r);for(let r of e){let i=`ALTER TABLE ${this.fqn(t)} ADD COLUMN ${n(r.name)} ${r.sqlType};`;await this.bigquery.query({query:i});}}async executeRaw(t){await this.bigquery.query({query:t});}onSchemaChange(t){let e=this.writers.get(t);if(e){try{e.writer.close();}catch{}this.writers.delete(t);}}async insertRows(t,e){if(e.length===0)return;let n=await this.getOrCreateWriter(t),r=this.writers.get(t)?.timestampColumns,i=e.map(a=>({...this.normalizeRow(a,r),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:f(a[m])}));await this.appendWithRetry(t,n,i);}async upsertRows(t,e,n){if(e.length===0)return;let r=await this.getOrCreateWriter(t,n),i=this.writers.get(t)?.timestampColumns,a=e.map(c=>({...this.normalizeRow(c,i),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:f(c[m])}));await this.appendWithRetry(t,r,a);}async deleteRows(t,e,n){if(n.length===0)return;let r=await this.getOrCreateWriter(t,e),i=n.map(a=>({[e]:a,_CHANGE_TYPE:"DELETE",_CHANGE_SEQUENCE_NUMBER:"ffffffffffffffff"}));await this.appendWithRetry(t,r,i);}get dataset(){return this.bigquery.dataset(this.datasetId)}fqn(t){let e=n=>n.replace(/`/g,"``");return `\`${e(this.datasetId)}.${e(t)}\``}static toEpochMicros(t){let e=t.getTime();return (BigInt(e)*1000n).toString()}normalizeRow(t,e){let n={};for(let[r,i]of Object.entries(t))if(i!==void 0)if(i instanceof Date)n[r]=g.toEpochMicros(i);else if(typeof i=="string"&&this.shouldCoerceTimestamp(r,i,e)){let a=new Date(i);Number.isNaN(a.getTime())?n[r]=i:n[r]=g.toEpochMicros(a);}else typeof i=="object"&&i!==null?n[r]=JSON.stringify(i):typeof i=="bigint"?n[r]=i.toString():n[r]=i;return n}shouldCoerceTimestamp(t,e,n){return n?n.has(t):g.ISO_TIMESTAMP_RE.test(e)}async appendWithRetry(t,e,n){await R(async()=>{try{await e.appendRows(n).getResult();}catch(r){throw this.onSchemaChange(t),r}});}async getOrCreateWriter(t,e){let n=this.writers.get(t);if(n)if(e&&n.primaryKey!==e)this.onSchemaChange(t);else return n.writer;let r=I();this.writerClient||(this.writerClient=new r.managedwriter.WriterClient({projectId:this.projectId}));let[i]=await this.dataset.table(t).getMetadata(),a={fields:i.schema?.fields??[]};e||(e=i.tableConstraints?.primaryKey?.columns?.[0]??a.fields[0]?.name);let c=r.adapt.convertBigQuerySchemaToStorageTableSchema(a),o=r.adapt.convertStorageSchemaToProto2Descriptor(c,"Row",r.adapt.withChangeType(),r.adapt.withChangeSequenceNumber()),d=new Set(a.fields.filter(l=>["TIMESTAMP","DATETIME","DATE"].includes(String(l.type??"").toUpperCase())).map(l=>l.name)),T=`projects/${this.projectId}/datasets/${this.datasetId}/tables/${t}`,S=await this.writerClient.createStreamConnection({streamId:r.managedwriter.DefaultStream,destinationTable:T}),y=new r.managedwriter.JSONWriter({connection:S,protoDescriptor:o});return this.writers.set(t,{writer:y,primaryKey:e??"",timestampColumns:d}),y}async close(){for(let{writer:t}of this.writers.values())try{t.close();}catch{}if(this.writers.clear(),this.writerClient&&typeof this.writerClient.close=="function")try{this.writerClient.close();}catch{}}};g.ISO_TIMESTAMP_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;var w=g;exports.BigQueryAdapter=w;exports.bigqueryDialect=C;//# sourceMappingURL=bigquery.cjs.map
7
+ CLUSTER BY ${t(n)}${o};`;await this.bigquery.query({query:d});}async addColumns(e,t){let n=r=>this.dialect.quoteIdentifier(r);for(let r of t){let s=`ALTER TABLE ${this.fqn(e)} ADD COLUMN ${n(r.name)} ${r.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 n=await this.getOrCreateWriter(e),r=this.writers.get(e)?.timestampColumns,s=t.map(o=>({...this.normalizeRow(o,r),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:I(o[g])}));await this.appendWithRetry(e,n,s);}async upsertRows(e,t,n){if(t.length===0)return;let r=await this.getOrCreateWriter(e,n),s=this.writers.get(e)?.timestampColumns,o=t.map(d=>({...this.normalizeRow(d,s),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:I(d[g])}));await this.appendWithRetry(e,r,o);}async deleteRows(e,t,n){if(n.length===0)return;let r=await this.getOrCreateWriter(e,t),s=n.map(o=>({[t]:o,_CHANGE_TYPE:"DELETE",_CHANGE_SEQUENCE_NUMBER:"ffffffffffffffff"}));await this.appendWithRetry(e,r,s);}get dataset(){return this.bigquery.dataset(this.datasetId)}fqn(e){let t=n=>n.replace(/`/g,"``");return `\`${t(this.datasetId)}.${t(e)}\``}static toEpochMicros(e){let t=e.getTime();return (BigInt(t)*1000n).toString()}normalizeRow(e,t){let n={};for(let[r,s]of Object.entries(e))if(s!==void 0)if(s instanceof Date)n[r]=m.toEpochMicros(s);else if(typeof s=="string"&&this.shouldCoerceTimestamp(r,s,t)){let o=new Date(s);Number.isNaN(o.getTime())?n[r]=s:n[r]=m.toEpochMicros(o);}else typeof s=="object"&&s!==null?n[r]=JSON.stringify(s):typeof s=="bigint"?n[r]=s.toString():n[r]=s;return n}shouldCoerceTimestamp(e,t,n){return n?n.has(e):m.ISO_TIMESTAMP_RE.test(t)}async appendWithRetry(e,t,n){await j(async()=>{try{await t.appendRows(n).getResult();}catch(r){throw this.onSchemaChange(e),r}});}async getOrCreateWriter(e,t){let n=this.writers.get(e);if(n)if(t&&n.primaryKey!==t)this.onSchemaChange(e);else return n.writer;let r=L();this.writerClient||(this.writerClient=new r.managedwriter.WriterClient({projectId:this.projectId}));let[s]=await this.dataset.table(e).getMetadata(),o={fields:s.schema?.fields??[]};t||(t=s.tableConstraints?.primaryKey?.columns?.[0]??o.fields[0]?.name);let d=r.adapt.convertBigQuerySchemaToStorageTableSchema(o),a=r.adapt.convertStorageSchemaToProto2Descriptor(d,"Row",r.adapt.withChangeType(),r.adapt.withChangeSequenceNumber()),p=new Set(o.fields.filter(f=>["TIMESTAMP","DATETIME","DATE"].includes(String(f.type??"").toUpperCase())).map(f=>f.name)),u=`projects/${this.projectId}/datasets/${this.datasetId}/tables/${e}`,l=await this.writerClient.createStreamConnection({streamId:r.managedwriter.DefaultStream,destinationTable:u}),y=new r.managedwriter.JSONWriter({connection:l,protoDescriptor:a});return this.writers.set(e,{writer:y,primaryKey:t??"",timestampColumns:p}),y}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{}}};m.ISO_TIMESTAMP_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;var A=m;exports.BigQueryAdapter=A;exports.SchemaTypeMismatchError=Z;exports.bigqueryDialect=k;//# sourceMappingURL=bigquery.cjs.map
8
8
  //# sourceMappingURL=bigquery.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sync/constants.ts","../../src/sync/adapters/bigquery-types.ts","../../src/sync/adapters/bigquery.ts"],"names":["SYNC_VERSION_COLUMN","normalizeBigQueryType","type","upper","BigQueryDialect","logical","id","bigqueryDialect","storageNsCache","loadStorageNs","formatChangeSequenceNumber","version","n","isRetryableStorageError","err","e","withRetry","fn","maxRetries","baseMs","attempt","cap","delay","res","_BigQueryAdapter","options","tableName","exists","metadata","f","fields","result","table","qi","pk","c","cols","notNull","opts","optionsClause","ddl","columns","stmt","sql","cached","rows","writer","timestampColumns","cdc","row","primaryKey","ids","esc","s","d","ms","out","k","v","column","value","ns","bqSchema","storageSchema","protoDescriptor","destinationTable","connection","BigQueryAdapter"],"mappings":"sQAaO,IAAMA,CAAAA,CAAsB,iBCG5B,SAASC,CAAAA,CAAsBC,EAAsB,CAC1D,IAAMC,CAAAA,CAAQD,CAAAA,CAAK,WAAA,EAAY,CAC/B,OAAQC,CAAAA,EACN,KAAK,SAAA,CACH,OAAO,QACT,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AA,EAAa,IAAA,CAAK,SAAS,WAAWvC,CAAS,CAAA,CAAA,CAM5FwC,EAAa,MAAM,IAAA,CAAK,aAAa,sBAAA,CAAuB,CAChE,QAAA,CAAUL,CAAAA,CAAG,cAAc,aAAA,CAC3B,gBAAA,CAAAI,CACF,CAAC,EAEKnB,CAAAA,CAAS,IAAIe,CAAAA,CAAG,aAAA,CAAc,WAAW,CAC7C,UAAA,CAAAK,EACA,eAAA,CAAAF,CACF,CAAC,CAAA,CAED,OAAA,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAItC,EAAW,CAC1B,MAAA,CAAAoB,CAAAA,CACA,UAAA,CAAYI,GAAc,EAAA,CAC1B,gBAAA,CAAAH,CACF,CAAC,EACMD,CACT,CAGA,MAAM,KAAA,EAAuB,CAC3B,OAAW,CAAE,MAAA,CAAAA,CAAO,CAAA,GAAK,KAAK,OAAA,CAAQ,MAAA,EAAO,CAC3C,GAAI,CACFA,CAAAA,CAAO,KAAA,GACT,CAAA,KAAQ,CAER,CAGF,GADA,KAAK,OAAA,CAAQ,KAAA,GACT,IAAA,CAAK,YAAA,EAAgB,OAAO,IAAA,CAAK,aAAa,KAAA,EAAU,UAAA,CAC1D,GAAI,CACF,IAAA,CAAK,aAAa,KAAA,GACpB,CAAA,KAAQ,CAER,CAEJ,CACF,CAAA,CAvXatB,EA2La,gBAAA,CACtB,sCAAA,KA5LS2C,CAAAA,CAAN3C","file":"bigquery.cjs","sourcesContent":["/**\n * Internal constants shared between the worker, queue, schema mapper and\n * SQL adapters.\n */\n\n/**\n * Name of the SQL column that stores the publish-time `version` of each\n * sync event. Used by the worker to discard out-of-order PubSub deliveries\n * (the MERGE only updates rows when the incoming version is strictly\n * greater than the stored one).\n *\n * Two underscores prefix avoids collisions with user-defined fields.\n */\nexport const SYNC_VERSION_COLUMN = \"__sync_version\";\n","/**\n * BigQuery type-name utilities used by the {@link BigQueryAdapter}.\n *\n * - {@link normalizeBigQueryType} canonicalises BigQuery type strings so that\n * `INTEGER`/`INT64`, `FLOAT`/`FLOAT64`, `BOOLEAN`/`BOOL`, etc. compare\n * equal during schema-drift detection.\n * - {@link isBigQueryTypeCompatible} returns whether a desired type can\n * safely keep an existing column of another type — only widenings that\n * BigQuery accepts via `ALTER COLUMN SET DATA TYPE` are allowed.\n */\n\n/**\n * Canonicalise a BigQuery type name returned by `getMetadata().schema`\n * (which may use legacy aliases like `INTEGER` or `FLOAT`) so that it can\n * be compared against the type produced by `BigQueryDialect.mapType()`.\n */\nexport function normalizeBigQueryType(type: string): string {\n const upper = type.toUpperCase();\n switch (upper) {\n case \"INTEGER\":\n return \"INT64\";\n case \"FLOAT\":\n return \"FLOAT64\";\n case \"BOOLEAN\":\n return \"BOOL\";\n default:\n return upper;\n }\n}\n\n/**\n * Whether `desired` is the same as, or a safe widening of, `existing`.\n * The widenings mirror what BigQuery allows via\n * `ALTER COLUMN x SET DATA TYPE …` — see\n * https://cloud.google.com/bigquery/docs/managing-table-schemas#change_column_types\n */\nexport function isBigQueryTypeCompatible(\n existing: string,\n desired: string,\n): boolean {\n const a = normalizeBigQueryType(existing);\n const b = normalizeBigQueryType(desired);\n if (a === b) return true;\n\n const widenings: Record<string, string[]> = {\n INT64: [\"NUMERIC\", \"BIGNUMERIC\", \"FLOAT64\"],\n NUMERIC: [\"BIGNUMERIC\", \"FLOAT64\"],\n DATE: [\"DATETIME\", \"TIMESTAMP\"],\n DATETIME: [\"TIMESTAMP\"],\n };\n return widenings[a]?.includes(b) ?? false;\n}\n","/**\n * BigQuery adapter — streams Firestore changes to BigQuery via the\n * **Storage Write API** in CDC (Change Data Capture) mode.\n *\n * Why CDC over the legacy MERGE approach:\n *\n * - **No DML concurrency limit.** MERGE/DELETE DML is bounded by ≈ 2\n * concurrent statements per table; busy collections triggered\n * `Could not serialize access … due to concurrent update` errors.\n * The Storage Write API has no such bound, so multiple Cloud Function\n * instances can flush in parallel without conflicts.\n * - **Cheaper at scale.** Storage Write is roughly ~50% cheaper than\n * legacy streaming inserts, and free for the first 2 TiB / month.\n * - **Same idempotency model.** Each row carries `_CHANGE_SEQUENCE_NUMBER`\n * built from the existing `__sync_version` column, so out-of-order\n * PubSub deliveries are merged correctly by BigQuery.\n *\n * Requirements:\n *\n * - Destination tables **must** declare a `PRIMARY KEY (...) NOT ENFORCED`\n * constraint and be clustered on that key. {@link BigQueryAdapter.createTable}\n * handles both for tables managed by this library.\n * - Tables should be created with `OPTIONS(max_staleness = INTERVAL …)`\n * so the CDC merge runs in the background instead of on every read\n * — see {@link BigQueryAdapterOptions.maxStaleness}.\n * - Service account needs `bigquery.tables.updateData` (e.g. via the\n * `roles/bigquery.dataEditor` role).\n *\n * @example\n * ```ts\n * import { BigQuery } from \"@google-cloud/bigquery\";\n * import { BigQueryAdapter } from \"@lpdjs/firestore-repo-service/sync/bigquery\";\n *\n * const adapter = new BigQueryAdapter({\n * projectId: \"my-project\",\n * datasetId: \"firestore_sync\",\n * bigquery: new BigQuery({ projectId: \"my-project\" }),\n * maxStaleness: \"INTERVAL 15 MINUTE\",\n * });\n * ```\n */\n\nimport type { BigQuery } from \"@google-cloud/bigquery\";\nimport { SYNC_VERSION_COLUMN } from \"../constants\";\nimport type {\n LogicalType,\n SqlAdapter,\n SqlColumn,\n SqlDialect,\n SqlTableDef,\n} from \"../types\";\nimport { normalizeBigQueryType } from \"./bigquery-types\";\n\n// ---------------------------------------------------------------------------\n// Dialect\n// ---------------------------------------------------------------------------\n\n/** BigQuery SQL dialect mapping. */\nclass BigQueryDialect implements SqlDialect {\n readonly name = \"bigquery\";\n\n mapType(logical: LogicalType): string {\n switch (logical) {\n case \"string\":\n return \"STRING\";\n case \"number\":\n return \"FLOAT64\";\n case \"bigint\":\n return \"INT64\";\n case \"boolean\":\n return \"BOOL\";\n case \"timestamp\":\n return \"TIMESTAMP\";\n case \"json\":\n return \"JSON\";\n case \"text\":\n return \"STRING\";\n }\n }\n\n quoteIdentifier(id: string): string {\n // BigQuery escapes identifiers with backticks; a literal backtick inside\n // an identifier must be doubled. Without this, an identifier containing a\n // backtick (e.g. a column name propagated from a Firestore document key)\n // would break out of the quoting and enable DDL injection.\n return \"`\" + id.replace(/`/g, \"``\") + \"`\";\n }\n}\n\n/** Shared BigQuery dialect singleton. */\nexport const bigqueryDialect: SqlDialect = new BigQueryDialect();\n\n// ---------------------------------------------------------------------------\n// Storage Write API loader (kept loose so `@google-cloud/bigquery-storage`\n// stays an OPTIONAL peer dep)\n// ---------------------------------------------------------------------------\n\ntype StorageNs = {\n managedwriter: {\n WriterClient: new (opts?: any) => any;\n JSONWriter: new (params: { connection: any; protoDescriptor: any }) => any;\n DefaultStream: any;\n };\n adapt: {\n convertBigQuerySchemaToStorageTableSchema(schema: any): any;\n convertStorageSchemaToProto2Descriptor(\n schema: any,\n scope: string,\n ...opts: any[]\n ): any;\n withChangeType(): any;\n withChangeSequenceNumber(): any;\n };\n};\n\nlet storageNsCache: StorageNs | null = null;\nfunction loadStorageNs(): StorageNs {\n if (storageNsCache) return storageNsCache;\n // Lazy require so the library does not pull `@google-cloud/bigquery-storage`\n // unless this adapter is actually instantiated.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@google-cloud/bigquery-storage\");\n storageNsCache = mod as StorageNs;\n return storageNsCache;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Format `__sync_version` (Firestore commit timestamp in microseconds since\n * epoch) as the 16-character hex string required by `_CHANGE_SEQUENCE_NUMBER`.\n *\n * BigQuery compares sequence numbers lexicographically, so a fixed-width hex\n * representation is mandatory for correct ordering.\n */\nfunction formatChangeSequenceNumber(version: unknown): string {\n let n: bigint;\n if (typeof version === \"bigint\") n = version;\n else if (typeof version === \"number\") n = BigInt(version);\n else if (typeof version === \"string\") n = BigInt(version);\n else n = 0n;\n if (n < 0n) n = 0n;\n return n.toString(16).padStart(16, \"0\");\n}\n\n/**\n * Returns true when the Storage Write append failed with a transient gRPC\n * status (UNAVAILABLE, DEADLINE_EXCEEDED, INTERNAL, ABORTED). Caller can\n * safely retry these.\n */\nfunction isRetryableStorageError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { code?: number };\n // gRPC codes: 4=DEADLINE_EXCEEDED, 10=ABORTED, 13=INTERNAL, 14=UNAVAILABLE\n return e.code === 4 || e.code === 10 || e.code === 13 || e.code === 14;\n}\n\nasync function withRetry<T>(\n fn: () => Promise<T>,\n maxRetries = 6,\n baseMs = 200,\n): Promise<T> {\n let attempt = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n return await fn();\n } catch (err) {\n attempt++;\n if (!isRetryableStorageError(err) || attempt > maxRetries) throw err;\n const cap = baseMs * Math.pow(2, attempt);\n const delay = Math.random() * cap;\n await new Promise((res) => setTimeout(res, delay));\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal structural shape of `@google-cloud/bigquery`'s `BigQuery` client\n * actually used by the adapter (`.dataset(...)` and `.query(...)`).\n *\n * Why structural and not just `BigQuery`: TypeScript treats classes with\n * private fields nominally. When a consumer's `node_modules` ends up with\n * a *second* copy of `@google-cloud/bigquery` (very common in workspace\n * setups, peer-dep dedup misses, monorepo nesting), the `BigQuery` they\n * import is *technically* a different type than the one this library's\n * `BigQuery` references — even though they are runtime-identical — and\n * assignment fails with `Types have separate declarations of a private\n * property '_universeDomain'`.\n *\n * Accepting a structural superset sidesteps the duplicate-install issue\n * without giving up type safety on the methods we actually call.\n */\nexport interface BigQueryLike {\n dataset(datasetId: string): {\n table(tableName: string): any;\n [key: string]: any;\n };\n query(options: { query: string; params?: unknown[] } | string): Promise<any>;\n}\n\nexport interface BigQueryAdapterOptions {\n /** GCP project id that owns the dataset. */\n projectId: string;\n /** BigQuery dataset id. */\n datasetId: string;\n /**\n * BigQuery client used for DDL operations (createTable, addColumns,\n * getMetadata, executeRaw). Storage Write only handles inserts.\n *\n * Typed as the structural {@link BigQueryLike} (a superset satisfied by\n * `BigQuery` from `@google-cloud/bigquery`) to avoid TypeScript nominal\n * mismatches when the consumer's project ends up with two copies of\n * `@google-cloud/bigquery` in different `node_modules`. Pass\n * `new BigQuery({...})` from your own install — it satisfies this shape\n * structurally.\n */\n bigquery: BigQueryLike | BigQuery;\n /**\n * Optional pre-built Storage Write `WriterClient`. When omitted a new\n * one is created lazily on first use.\n */\n writerClient?: any;\n /**\n * Value passed to `OPTIONS(max_staleness = ...)` on `createTable`.\n *\n * **Why this matters**: in BigQuery CDC mode, Storage Write API rows\n * land in a delta buffer. They become visible to queries only after a\n * MERGE applies them to the base table. Two paths exist:\n *\n * - **Background MERGE** — runs periodically in the background, paid\n * for as part of CDC pricing, and never blocks your readers.\n * - **Read-time MERGE** — every `SELECT` query merges the delta on the\n * fly before returning. Always-fresh reads but every query pays for\n * the merge work.\n *\n * `max_staleness` is the tolerated lag between a write and what reads\n * see. Setting it tells BigQuery: \"background MERGE is fine if reads\n * are at most this stale\". When the threshold is exceeded, the next\n * read triggers a one-shot merge.\n *\n * **The default `INTERVAL 0` means \"always read-time merge\"** — every\n * query forces a full merge of pending CDC writes. That makes reads\n * dramatically slower and more expensive on busy tables, so this\n * library defaults to a 15 minute window in production.\n *\n * Recommended:\n * - `INTERVAL 15 MINUTE` in production (good cost/freshness trade-off).\n * - `INTERVAL 1 MINUTE` in dev for quick visibility.\n * - Set to `null` to omit the option entirely (only do this when you\n * know what you are doing — you'll likely hit slow & expensive reads).\n *\n * @default \"INTERVAL 15 MINUTE\"\n */\n maxStaleness?: string | null;\n}\n\n/**\n * BigQuery implementation of {@link SqlAdapter} using the Storage Write API\n * in CDC mode. See module-level docstring for the rationale.\n */\nexport class BigQueryAdapter implements SqlAdapter {\n private readonly bigquery: BigQueryLike;\n private readonly projectId: string;\n private readonly datasetId: string;\n private readonly maxStaleness: string | null;\n private writerClient: any;\n /** Cache of `{ writer, primaryKey }` per table name. */\n private readonly writers = new Map<\n string,\n { writer: any; primaryKey: string; timestampColumns?: Set<string> }\n >();\n\n constructor(options: BigQueryAdapterOptions) {\n this.bigquery = options.bigquery;\n this.projectId = options.projectId;\n this.datasetId = options.datasetId;\n this.maxStaleness =\n options.maxStaleness === undefined\n ? \"INTERVAL 15 MINUTE\"\n : options.maxStaleness;\n this.writerClient = options.writerClient;\n }\n\n get dialect(): SqlDialect {\n return bigqueryDialect;\n }\n\n // -------- DDL (delegated to @google-cloud/bigquery) ----------------------\n\n async tableExists(tableName: string): Promise<boolean> {\n const [exists] = await this.dataset.table(tableName).exists();\n return exists;\n }\n\n async getTableColumns(tableName: string): Promise<string[]> {\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const fields: Array<{ name: string }> = metadata.schema?.fields ?? [];\n return fields.map((f) => f.name);\n }\n\n async getTableColumnsWithTypes(\n tableName: string,\n ): Promise<Map<string, string>> {\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const fields: Array<{ name: string; type: string }> =\n metadata.schema?.fields ?? [];\n const result = new Map<string, string>();\n for (const f of fields) {\n result.set(f.name, normalizeBigQueryType(f.type));\n }\n return result;\n }\n\n async createTable(table: SqlTableDef): Promise<void> {\n const qi = (id: string) => this.dialect.quoteIdentifier(id);\n const pk = table.columns.find((c) => c.isPrimaryKey)?.name;\n if (!pk) {\n throw new Error(\n `BigQueryAdapter requires a primary key on table \\`${table.tableName}\\` ` +\n `(Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`,\n );\n }\n const cols = table.columns\n .map((c) => {\n const notNull = c.isPrimaryKey ? \" NOT NULL\" : \"\";\n return ` ${qi(c.name)} ${c.sqlType}${notNull}`;\n })\n .join(\",\\n\");\n\n const opts: string[] = [];\n if (this.maxStaleness !== null) {\n opts.push(`max_staleness = ${this.maxStaleness}`);\n }\n const optionsClause =\n opts.length > 0 ? `\\nOPTIONS(${opts.join(\", \")})` : \"\";\n\n const ddl =\n `CREATE TABLE IF NOT EXISTS ${this.fqn(table.tableName)} (\\n${cols},\\n` +\n ` PRIMARY KEY (${qi(pk)}) NOT ENFORCED\\n)` +\n `\\nCLUSTER BY ${qi(pk)}` +\n `${optionsClause};`;\n\n await this.bigquery.query({ query: ddl });\n }\n\n async addColumns(tableName: string, columns: SqlColumn[]): Promise<void> {\n const qi = (id: string) => this.dialect.quoteIdentifier(id);\n for (const c of columns) {\n const stmt = `ALTER TABLE ${this.fqn(tableName)} ADD COLUMN ${qi(c.name)} ${c.sqlType};`;\n await this.bigquery.query({ query: stmt });\n }\n }\n\n async executeRaw(sql: string): Promise<void> {\n await this.bigquery.query({ query: sql });\n }\n\n /**\n * Invalidate the cached writer for a table. Called by the worker after\n * `addColumns` so the next append rebuilds the proto descriptor against\n * the new schema.\n */\n onSchemaChange(tableName: string): void {\n const cached = this.writers.get(tableName);\n if (cached) {\n try {\n cached.writer.close();\n } catch {\n // ignore — connection may already be torn down\n }\n this.writers.delete(tableName);\n }\n }\n\n // -------- Inserts (Storage Write API) -----------------------------------\n\n async insertRows(\n tableName: string,\n rows: Record<string, unknown>[],\n ): Promise<void> {\n if (rows.length === 0) return;\n // Plain inserts have no PK matching, but in CDC mode every row needs a\n // _CHANGE_TYPE. We treat them as UPSERT.\n const writer = await this.getOrCreateWriter(tableName);\n const timestampColumns = this.writers.get(tableName)?.timestampColumns;\n const cdc = rows.map((row) => ({\n ...this.normalizeRow(row, timestampColumns),\n _CHANGE_TYPE: \"UPSERT\",\n _CHANGE_SEQUENCE_NUMBER: formatChangeSequenceNumber(\n row[SYNC_VERSION_COLUMN],\n ),\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n async upsertRows(\n tableName: string,\n rows: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (rows.length === 0) return;\n const writer = await this.getOrCreateWriter(tableName, primaryKey);\n const timestampColumns = this.writers.get(tableName)?.timestampColumns;\n const cdc = rows.map((row) => ({\n ...this.normalizeRow(row, timestampColumns),\n _CHANGE_TYPE: \"UPSERT\",\n _CHANGE_SEQUENCE_NUMBER: formatChangeSequenceNumber(\n row[SYNC_VERSION_COLUMN],\n ),\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n async deleteRows(\n tableName: string,\n primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const writer = await this.getOrCreateWriter(tableName, primaryKey);\n // Storage Write CDC requires a value for every NOT-NULL column (the PK)\n // and a `_CHANGE_TYPE`. Other columns may be omitted; missing values are\n // interpreted as NULL. We pass the maximum sequence number so the DELETE\n // wins over any concurrent UPSERT for the same key — tombstones from the\n // queue carry no `__sync_version` of their own.\n const cdc = ids.map((id) => ({\n [primaryKey]: id,\n _CHANGE_TYPE: \"DELETE\",\n _CHANGE_SEQUENCE_NUMBER: \"ffffffffffffffff\",\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n // -------- Internal helpers ----------------------------------------------\n\n private get dataset() {\n return this.bigquery.dataset(this.datasetId);\n }\n\n private fqn(tableName: string): string {\n // Escape backticks in both identifier parts to prevent DDL/DML injection\n // (BigQuery doubles backticks to embed a literal one).\n const esc = (s: string) => s.replace(/`/g, \"``\");\n return `\\`${esc(this.datasetId)}.${esc(tableName)}\\``;\n }\n\n /** ISO 8601 timestamp pattern (e.g. 2026-03-29T20:59:27.394Z) */\n private static readonly ISO_TIMESTAMP_RE =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/;\n\n /**\n * Convert a Date or epoch-millis number into the epoch-microseconds string\n * required by the Storage Write API for TIMESTAMP columns.\n *\n * The JSONWriter encodes through protobuf and a TIMESTAMP field is an\n * `int64`. Passing an ISO string would make `Long.fromString` throw\n * `interior hyphen` on the `-` characters.\n */\n private static toEpochMicros(d: Date): string {\n const ms = d.getTime();\n return (BigInt(ms) * 1000n).toString();\n }\n\n /** Convert JS values into shapes accepted by JSONWriter. */\n private normalizeRow(\n row: Record<string, unknown>,\n timestampColumns?: Set<string>,\n ): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(row)) {\n if (v === undefined) continue;\n if (v instanceof Date) {\n // TIMESTAMP column → int64 epoch micros (as string to preserve precision)\n out[k] = BigQueryAdapter.toEpochMicros(v);\n } else if (\n typeof v === \"string\" &&\n this.shouldCoerceTimestamp(k, v, timestampColumns)\n ) {\n // ISO timestamp produced upstream by `serializeDocument` (Firestore\n // Timestamp → ISO string) — convert to epoch micros for protobuf.\n const d = new Date(v);\n if (!Number.isNaN(d.getTime())) {\n out[k] = BigQueryAdapter.toEpochMicros(d);\n } else {\n out[k] = v;\n }\n } else if (typeof v === \"object\" && v !== null) {\n // JSON columns: serialise nested objects/arrays\n out[k] = JSON.stringify(v);\n } else if (typeof v === \"bigint\") {\n out[k] = v.toString();\n } else {\n out[k] = v;\n }\n }\n return out;\n }\n\n /**\n * Decide whether a string value should be coerced to an epoch-micros\n * timestamp.\n *\n * When the destination table's column types are known (writer already\n * built from table metadata), coerce **only** when the column is actually\n * TIMESTAMP/DATETIME/DATE. This prevents a business string that merely\n * looks like an ISO date (a log line, a slug, a formatted id) from being\n * silently rewritten — and avoids type-mismatch write errors on STRING\n * columns (issue #15).\n *\n * When column types are unavailable (e.g. a writer injected directly, or\n * metadata not yet fetched), fall back to the ISO-shape heuristic so\n * behaviour is unchanged.\n */\n private shouldCoerceTimestamp(\n column: string,\n value: string,\n timestampColumns?: Set<string>,\n ): boolean {\n if (timestampColumns) return timestampColumns.has(column);\n return BigQueryAdapter.ISO_TIMESTAMP_RE.test(value);\n }\n\n private async appendWithRetry(\n tableName: string,\n writer: any,\n rows: Record<string, unknown>[],\n ): Promise<void> {\n await withRetry(async () => {\n try {\n const pending = writer.appendRows(rows);\n await pending.getResult();\n } catch (err) {\n // On certain errors (schema drift, broken connection) drop the\n // cached writer so the next call rebuilds it.\n this.onSchemaChange(tableName);\n throw err;\n }\n });\n }\n\n private async getOrCreateWriter(\n tableName: string,\n primaryKey?: string,\n ): Promise<any> {\n const cached = this.writers.get(tableName);\n if (cached) {\n if (primaryKey && cached.primaryKey !== primaryKey) {\n // PK changed — invalidate and rebuild\n this.onSchemaChange(tableName);\n } else {\n return cached.writer;\n }\n }\n\n const ns = loadStorageNs();\n if (!this.writerClient) {\n this.writerClient = new ns.managedwriter.WriterClient({\n projectId: this.projectId,\n });\n }\n\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const bqSchema = { fields: metadata.schema?.fields ?? [] };\n if (!primaryKey) {\n // Try to recover PK from table constraints if available\n const tableConstraintsPK =\n metadata.tableConstraints?.primaryKey?.columns?.[0];\n primaryKey = tableConstraintsPK ?? bqSchema.fields[0]?.name;\n }\n\n const storageSchema =\n ns.adapt.convertBigQuerySchemaToStorageTableSchema(bqSchema);\n const protoDescriptor = ns.adapt.convertStorageSchemaToProto2Descriptor(\n storageSchema,\n \"Row\",\n ns.adapt.withChangeType(),\n ns.adapt.withChangeSequenceNumber(),\n );\n\n // Track which columns are actually TIMESTAMP-like so `normalizeRow` only\n // coerces ISO-looking strings when the destination column expects a\n // timestamp — a business string that merely *looks* like an ISO date must\n // not be silently converted to epoch micros (see issue #15).\n const timestampColumns = new Set<string>(\n (bqSchema.fields as Array<{ name: string; type?: string }>)\n .filter((f) =>\n [\"TIMESTAMP\", \"DATETIME\", \"DATE\"].includes(\n String(f.type ?? \"\").toUpperCase(),\n ),\n )\n .map((f) => f.name),\n );\n\n const destinationTable = `projects/${this.projectId}/datasets/${this.datasetId}/tables/${tableName}`;\n // Pass `DefaultStream` as `streamId` (not `streamType`): the `_default`\n // stream is implicit on every table, so the client must short-circuit to\n // `${destinationTable}/streams/_default` instead of calling\n // `createWriteStream({ type: DEFAULT })` which BigQuery rejects with\n // `Unable to create a stream with type TYPE_UNSPECIFIED`.\n const connection = await this.writerClient.createStreamConnection({\n streamId: ns.managedwriter.DefaultStream,\n destinationTable,\n });\n\n const writer = new ns.managedwriter.JSONWriter({\n connection,\n protoDescriptor,\n });\n\n this.writers.set(tableName, {\n writer,\n primaryKey: primaryKey ?? \"\",\n timestampColumns,\n });\n return writer;\n }\n\n /** Close all open writer connections. Useful for graceful shutdown. */\n async close(): Promise<void> {\n for (const { writer } of this.writers.values()) {\n try {\n writer.close();\n } catch {\n /* ignore */\n }\n }\n this.writers.clear();\n if (this.writerClient && typeof this.writerClient.close === \"function\") {\n try {\n this.writerClient.close();\n } catch {\n /* ignore */\n }\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/sync/constants.ts","../../src/shared/zod-compat.ts","../../src/sync/schema-mapper.ts","../../src/sync/adapters/bigquery-types.ts","../../src/sync/adapters/bigquery.ts"],"names":["SYNC_VERSION_COLUMN","TYPE_MAP","getTypeName","schema","s","v4Type","v3Type","getInnerType","getShape","WRAPPER_TYPES","unwrap","current","nullable","name","inner","LOGICAL_MAP","flattenSchema","shape","dialect","prefix","parentNullable","excludeSet","columnMap","primaryKey","columns","field","fieldSchema","fullKey","typeName","isNullable","nestedShape","logical","isPK","colName","zodSchemaToColumns","options","exclude","c","normalizeBigQueryType","type","upper","isBigQueryTypeCompatible","existing","desired","a","b","BigQueryDialect","id","bigqueryDialect","storageNsCache","loadStorageNs","formatChangeSequenceNumber","version","n","isRetryableStorageError","err","withRetry","fn","maxRetries","baseMs","attempt","cap","delay","res","SchemaTypeMismatchError","tableName","column","existingType","desiredType","_BigQueryAdapter","targetName","items","ids","missing","col","repoConfig","actualCols","expectedCols","actualSet","expectedSet","extra","matched","healthy","e","exists","metadata","f","fields","result","table","qi","pk","cols","notNull","opts","optionsClause","ddl","stmt","sql","cached","rows","writer","timestampColumns","cdc","row","esc","d","ms","out","k","v","value","ns","bqSchema","storageSchema","protoDescriptor","destinationTable","connection","BigQueryAdapter"],"mappings":"aAaO,IAAA,CAAA,CAAA,CAAA,CAAA,EAAA,OAAA,OAAA,CAAA,GAAA,CAAA,OAAA,CAAA,OAAA,KAAA,CAAA,GAAA,CAAA,IAAA,KAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,OAAA,OAAA,CAAA,GAAA,CAAA,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KAAK,OAAA,CAAQ,MAAA,EAAO,CAC3C,GAAI,CACFA,CAAAA,CAAO,KAAA,GACT,CAAA,KAAQ,CAER,CAGF,GADA,KAAK,OAAA,CAAQ,KAAA,GACT,IAAA,CAAK,YAAA,EAAgB,OAAO,IAAA,CAAK,aAAa,KAAA,EAAU,UAAA,CAC1D,GAAI,CACF,IAAA,CAAK,aAAa,KAAA,GACpB,CAAA,KAAQ,CAER,CAEJ,CACF,EA5fahC,EAgUa,gBAAA,CACtB,sCAAA,KAjUSiD,CAAAA,CAANjD","file":"bigquery.cjs","sourcesContent":["/**\n * Internal constants shared between the worker, queue, schema mapper and\n * SQL adapters.\n */\n\n/**\n * Name of the SQL column that stores the publish-time `version` of each\n * sync event. Used by the worker to discard out-of-order PubSub deliveries\n * (the MERGE only updates rows when the incoming version is strictly\n * greater than the stored one).\n *\n * Two underscores prefix avoids collisions with user-defined fields.\n */\nexport const SYNC_VERSION_COLUMN = \"__sync_version\";\n","/**\n * Zod introspection utilities — compatible with Zod 4.\n *\n * Centralizes all internal `_zod.def` accesses so the rest of the codebase\n * never touches Zod internals directly. If a future Zod version changes\n * the internal layout, only this file needs updating.\n */\n\nimport type { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Type-name resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Canonical Zod type names used in the codebase.\n * These match the **Zod 3** naming convention (e.g. \"ZodString\") that the\n * form-gen / admin handlers already rely on, so we don't need to rewrite\n * every `case \"ZodString\":` branch.\n */\ntype ZodTypeName =\n | \"ZodString\"\n | \"ZodNumber\"\n | \"ZodBigInt\"\n | \"ZodBoolean\"\n | \"ZodDate\"\n | \"ZodEnum\"\n | \"ZodNativeEnum\"\n | \"ZodLiteral\"\n | \"ZodObject\"\n | \"ZodArray\"\n | \"ZodOptional\"\n | \"ZodNullable\"\n | \"ZodDefault\"\n | \"ZodCoerce\"\n | \"ZodUnion\"\n | \"ZodUndefined\"\n | \"ZodUnknown\"\n | \"ZodAny\"\n | \"ZodRecord\"\n | string;\n\n/**\n * Map from Zod 4 `_zod.def.type` (lowercase) → Zod 3 `_def.typeName` format.\n * Any key not in this map is capitalised as `Zod${Capitalised}`.\n */\nconst TYPE_MAP: Record<string, ZodTypeName> = {\n string: \"ZodString\",\n number: \"ZodNumber\",\n bigint: \"ZodBigInt\",\n boolean: \"ZodBoolean\",\n date: \"ZodDate\",\n enum: \"ZodEnum\",\n nativeEnum: \"ZodNativeEnum\",\n literal: \"ZodLiteral\",\n object: \"ZodObject\",\n array: \"ZodArray\",\n optional: \"ZodOptional\",\n nullable: \"ZodNullable\",\n default: \"ZodDefault\",\n coerce: \"ZodCoerce\",\n union: \"ZodUnion\",\n undefined: \"ZodUndefined\",\n unknown: \"ZodUnknown\",\n any: \"ZodAny\",\n record: \"ZodRecord\",\n};\n\n/**\n * Get the canonical type name of a Zod schema.\n *\n * Works with both Zod 3 (`_def.typeName`) and Zod 4 (`_zod.def.type`).\n * Returns names in Zod-3 style (\"ZodString\", \"ZodObject\" …) for\n * backward-compatible switch/case usage.\n */\nexport function getTypeName(schema: z.ZodType): ZodTypeName {\n const s = schema as any;\n\n // Zod 4 path\n const v4Type: string | undefined = s._zod?.def?.type;\n if (v4Type)\n return (\n TYPE_MAP[v4Type] ??\n `Zod${v4Type.charAt(0).toUpperCase()}${v4Type.slice(1)}`\n );\n\n // Zod 3 fallback\n const v3Type: string | undefined = s._def?.typeName;\n if (v3Type) return v3Type;\n\n return \"\";\n}\n\n// ---------------------------------------------------------------------------\n// Unwrapping wrappers (Optional / Nullable / Default)\n// ---------------------------------------------------------------------------\n\n/**\n * Get the inner schema from a wrapper type (Optional / Nullable / Default).\n */\nexport function getInnerType(schema: z.ZodType): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: _zod.def.innerType\n if (s._zod?.def?.innerType) return s._zod.def.innerType;\n\n // Zod 3 compat: _def.innerType\n if (s._def?.innerType) return s._def.innerType;\n\n return undefined;\n}\n\n/**\n * Get the **source** schema of an effect / transform / pipe wrapper, i.e. the\n * schema describing what the user actually provides:\n * - Zod 3 `ZodEffects` (`.transform()` / `.refine()` / `.preprocess()`) →\n * `_def.schema`;\n * - Zod 4 `ZodPipe` (the shape `.transform()` compiles to) → the `in` side.\n *\n * Lets form/field introspection see through `z.string().transform(...)` (which\n * should still render as a text input) instead of falling back to a JSON\n * textarea. Returns `undefined` when the schema is not an effect/pipe.\n */\nexport function getEffectInnerType(schema: z.ZodType): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: pipe — prefer the input side (what the user types).\n const pipeIn = s._zod?.def?.in;\n if (pipeIn) return pipeIn as z.ZodType;\n\n // Zod 3: ZodEffects wraps the base schema under `_def.schema`.\n if (s._def?.schema) return s._def.schema as z.ZodType;\n\n return undefined;\n}\n\n/**\n * Get the **element schema** from a `ZodArray`.\n * Returns `undefined` for non-array schemas.\n */\nexport function getArrayElementType(\n schema: z.ZodType,\n): z.ZodType | undefined {\n const s = schema as any;\n\n // Zod 4: _zod.def.element\n if (s._zod?.def?.element) return s._zod.def.element;\n\n // Zod 3: _def.type (ZodArray stores element schema in _def.type)\n if (s._def?.type) return s._def.type;\n\n return undefined;\n}\n\n/**\n * Returns the list of **required** (non-optional) top-level keys of a ZodObject.\n * A key is required when its schema is NOT wrapped in ZodOptional.\n * ZodNullable / ZodDefault fields are still considered required — they must be present.\n */\nexport function getRequiredSchemaKeys(schema: z.ZodObject<any>): string[] {\n const required: string[] = [];\n for (const [key, fieldSchema] of Object.entries(schema.shape)) {\n const typeName = getTypeName(fieldSchema as z.ZodType);\n if (typeName !== \"ZodOptional\") {\n required.push(key);\n }\n }\n return required;\n}\n\n/**\n * Get the default value for a ZodDefault schema.\n * In Zod 3 this was `_def.defaultValue()` (function). In Zod 4 it's a direct value.\n */\nexport function getDefaultValue(schema: z.ZodType): unknown {\n const s = schema as any;\n\n // Zod 4\n if (s._zod?.def?.defaultValue !== undefined) return s._zod.def.defaultValue;\n\n // Zod 3 compat\n const v = s._def?.defaultValue;\n if (typeof v === \"function\") return v();\n return v;\n}\n\n// ---------------------------------------------------------------------------\n// Object shape\n// ---------------------------------------------------------------------------\n\n/**\n * Get the shape of a ZodObject schema (Record<string, ZodType>).\n * Handles both Zod 3 (`_def.shape()` function) and Zod 4 (`.shape` property).\n */\nexport function getShape(schema: z.ZodType): Record<string, z.ZodType> {\n const s = schema as any;\n\n // Direct `.shape` property (Zod 3 & 4 for ZodObject instances)\n if (s.shape && typeof s.shape === \"object\") return s.shape;\n\n // Zod 4: _zod.def.shape\n if (s._zod?.def?.shape && typeof s._zod.def.shape === \"object\")\n return s._zod.def.shape;\n\n // Zod 3 fallback: _def.shape() or _def.shape\n if (s._def?.shape) {\n return typeof s._def.shape === \"function\" ? s._def.shape() : s._def.shape;\n }\n\n return {};\n}\n\n// ---------------------------------------------------------------------------\n// Enum / Literal values\n// ---------------------------------------------------------------------------\n\n/**\n * Get the values of a ZodEnum schema as a string[].\n */\nexport function getEnumValues(schema: z.ZodType): string[] {\n const s = schema as any;\n\n // Zod 4: `.options` or `_zod.def.entries`\n if (Array.isArray(s.options)) return s.options;\n if (s._zod?.def?.entries)\n return Object.values(s._zod.def.entries) as string[];\n\n // Zod 3: `_def.values`\n if (Array.isArray(s._def?.values)) return s._def.values;\n\n return [];\n}\n\n/**\n * Get the value object of a ZodNativeEnum schema.\n */\nexport function getNativeEnumValues(\n schema: z.ZodType,\n): Record<string, unknown> {\n const s = schema as any;\n\n // Zod 4: `_zod.def.entries` or `.enum`\n if (s._zod?.def?.entries) return s._zod.def.entries;\n if (s.enum && typeof s.enum === \"object\") return s.enum;\n\n // Zod 3: `_def.values`\n if (s._def?.values && typeof s._def.values === \"object\") return s._def.values;\n\n return {};\n}\n\n/**\n * Get the value of a ZodLiteral schema.\n */\nexport function getLiteralValue(schema: z.ZodType): unknown {\n const s = schema as any;\n\n // Zod 4: `_zod.def.values[0]`\n if (Array.isArray(s._zod?.def?.values)) return s._zod.def.values[0];\n\n // Zod 3: `_def.value`\n return s._def?.value;\n}\n\n/**\n * Get the member schemas of a ZodUnion (or ZodDiscriminatedUnion).\n * Works with both Zod 3 (`_def.options`) and Zod 4 (`.options` /\n * `_zod.def.options`). Returns an empty array when none can be resolved.\n */\nexport function getUnionOptions(schema: z.ZodType): z.ZodType[] {\n const s = schema as any;\n\n // Zod 4\n if (Array.isArray(s.options)) return s.options as z.ZodType[];\n if (Array.isArray(s._zod?.def?.options))\n return s._zod.def.options as z.ZodType[];\n\n // Zod 3\n if (Array.isArray(s._def?.options)) return s._def.options as z.ZodType[];\n\n return [];\n}\n\n// ---------------------------------------------------------------------------\n// String checks\n// ---------------------------------------------------------------------------\n\n/**\n * Get relevant \"check kinds\" from a ZodString schema.\n * Returns an array of kind strings: \"email\", \"url\", etc.\n */\nexport function getStringChecks(schema: z.ZodType): string[] {\n const s = schema as any;\n const kinds: string[] = [];\n\n // Zod 4: checks with `.format` field\n const v4Checks: any[] | undefined = s._zod?.def?.checks;\n if (Array.isArray(v4Checks)) {\n for (const c of v4Checks) {\n if (c.format) kinds.push(c.format);\n }\n if (kinds.length > 0) return kinds;\n }\n\n // Zod 3: _def.checks with `.kind` field\n const v3Checks: any[] | undefined = s._def?.checks;\n if (Array.isArray(v3Checks)) {\n for (const c of v3Checks) {\n if (c.kind) kinds.push(c.kind);\n }\n }\n\n return kinds;\n}\n","import { z } from \"zod\";\nimport {\n getTypeName,\n getInnerType,\n getShape,\n} from \"../shared/zod-compat\";\nimport { SYNC_VERSION_COLUMN } from \"./constants\";\nimport type { SqlColumn, SqlDialect, LogicalType } from \"./types\";\n\nconst WRAPPER_TYPES = new Set([\"ZodOptional\", \"ZodNullable\", \"ZodDefault\"]);\n\nfunction unwrap(schema: z.ZodType): { inner: z.ZodType; nullable: boolean } {\n let current = schema;\n let nullable = false;\n\n for (;;) {\n const name = getTypeName(current);\n if (!WRAPPER_TYPES.has(name)) break;\n if (name === \"ZodOptional\" || name === \"ZodNullable\") nullable = true;\n const inner = getInnerType(current);\n if (!inner) break;\n current = inner;\n }\n\n return { inner: current, nullable };\n}\n\nconst LOGICAL_MAP: Record<string, LogicalType> = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBigInt: \"bigint\",\n ZodBoolean: \"boolean\",\n ZodDate: \"timestamp\",\n ZodEnum: \"string\",\n ZodNativeEnum: \"string\",\n ZodLiteral: \"string\",\n};\n\nexport function zodTypeToLogical(schema: z.ZodType): LogicalType {\n const { inner } = unwrap(schema);\n return LOGICAL_MAP[getTypeName(inner)] ?? \"json\";\n}\n\nexport interface ZodSchemaToColumnsOptions {\n primaryKey?: string;\n exclude?: string[];\n columnMap?: Record<string, string>;\n}\n\n/**\n * Recursively flatten a Zod object schema into flat SQL columns.\n * Nested objects produce `parent_child` column names.\n * Arrays and non-object complex types become JSON columns.\n */\nfunction flattenSchema(\n shape: Record<string, z.ZodType>,\n dialect: SqlDialect,\n prefix: string,\n parentNullable: boolean,\n excludeSet: Set<string>,\n columnMap: Record<string, string>,\n primaryKey: string | undefined,\n columns: SqlColumn[],\n): void {\n for (const [field, fieldSchema] of Object.entries(shape)) {\n const fullKey = prefix ? `${prefix}__${field}` : field;\n\n // Exclude check on the original (dotless) path and the flattened key\n if (excludeSet.has(field) || excludeSet.has(fullKey)) continue;\n\n const { inner, nullable } = unwrap(fieldSchema);\n const typeName = getTypeName(inner);\n const isNullable = parentNullable || nullable;\n\n // Nested object → recurse to flatten\n if (typeName === \"ZodObject\") {\n const nestedShape = getShape(inner as z.ZodObject<any>);\n flattenSchema(\n nestedShape,\n dialect,\n fullKey,\n isNullable,\n excludeSet,\n columnMap,\n primaryKey,\n columns,\n );\n continue;\n }\n\n // Arrays and other complex types → JSON\n const logical = LOGICAL_MAP[typeName] ?? \"json\";\n const isPK = fullKey === primaryKey || field === primaryKey;\n const colName = columnMap[fullKey] ?? columnMap[field] ?? fullKey;\n\n columns.push({\n name: colName,\n sqlType: dialect.mapType(logical),\n nullable: isPK ? false : isNullable,\n isPrimaryKey: isPK,\n });\n }\n}\n\n/**\n * Convert a Zod object schema into an array of {@link SqlColumn} definitions\n * suitable for SQL table creation.\n *\n * Nested ZodObject fields are recursively flattened into separate columns\n * with underscore-separated names (e.g. `address.street` → `address_street`).\n * Arrays become JSON columns.\n */\nexport function zodSchemaToColumns(\n schema: z.ZodObject<any>,\n dialect: SqlDialect,\n options: ZodSchemaToColumnsOptions = {},\n): SqlColumn[] {\n const { primaryKey, exclude = [], columnMap = {} } = options;\n const excludeSet = new Set(exclude);\n const shape = getShape(schema);\n const columns: SqlColumn[] = [];\n\n flattenSchema(shape, dialect, \"\", false, excludeSet, columnMap, primaryKey, columns);\n\n // Internal version column used by the worker to discard out-of-order\n // PubSub deliveries (added unconditionally — never excluded).\n if (!columns.some((c) => c.name === SYNC_VERSION_COLUMN)) {\n columns.push({\n name: SYNC_VERSION_COLUMN,\n sqlType: dialect.mapType(\"bigint\"),\n nullable: true,\n isPrimaryKey: false,\n description: \"Monotonic publish version (Date.now() ms). Internal.\",\n });\n }\n\n return columns;\n}\n","/**\n * BigQuery type-name utilities used by the {@link BigQueryAdapter}.\n *\n * - {@link normalizeBigQueryType} canonicalises BigQuery type strings so that\n * `INTEGER`/`INT64`, `FLOAT`/`FLOAT64`, `BOOLEAN`/`BOOL`, etc. compare\n * equal during schema-drift detection.\n * - {@link isBigQueryTypeCompatible} returns whether a desired type can\n * safely keep an existing column of another type — only widenings that\n * BigQuery accepts via `ALTER COLUMN SET DATA TYPE` are allowed.\n */\n\n/**\n * Canonicalise a BigQuery type name returned by `getMetadata().schema`\n * (which may use legacy aliases like `INTEGER` or `FLOAT`) so that it can\n * be compared against the type produced by `BigQueryDialect.mapType()`.\n */\nexport function normalizeBigQueryType(type: string): string {\n const upper = type.toUpperCase();\n switch (upper) {\n case \"INTEGER\":\n return \"INT64\";\n case \"FLOAT\":\n return \"FLOAT64\";\n case \"BOOLEAN\":\n return \"BOOL\";\n default:\n return upper;\n }\n}\n\n/**\n * Whether `desired` is the same as, or a safe widening of, `existing`.\n * The widenings mirror what BigQuery allows via\n * `ALTER COLUMN x SET DATA TYPE …` — see\n * https://cloud.google.com/bigquery/docs/managing-table-schemas#change_column_types\n */\nexport function isBigQueryTypeCompatible(\n existing: string,\n desired: string,\n): boolean {\n const a = normalizeBigQueryType(existing);\n const b = normalizeBigQueryType(desired);\n if (a === b) return true;\n\n const widenings: Record<string, string[]> = {\n INT64: [\"NUMERIC\", \"BIGNUMERIC\", \"FLOAT64\"],\n NUMERIC: [\"BIGNUMERIC\", \"FLOAT64\"],\n DATE: [\"DATETIME\", \"TIMESTAMP\"],\n DATETIME: [\"TIMESTAMP\"],\n };\n return widenings[a]?.includes(b) ?? false;\n}\n","/**\n * BigQuery adapter — streams Firestore changes to BigQuery via the\n * **Storage Write API** in CDC (Change Data Capture) mode.\n *\n * Why CDC over the legacy MERGE approach:\n *\n * - **No DML concurrency limit.** MERGE/DELETE DML is bounded by ≈ 2\n * concurrent statements per table; busy collections triggered\n * `Could not serialize access … due to concurrent update` errors.\n * The Storage Write API has no such bound, so multiple Cloud Function\n * instances can flush in parallel without conflicts.\n * - **Cheaper at scale.** Storage Write is roughly ~50% cheaper than\n * legacy streaming inserts, and free for the first 2 TiB / month.\n * - **Same idempotency model.** Each row carries `_CHANGE_SEQUENCE_NUMBER`\n * built from the existing `__sync_version` column, so out-of-order\n * PubSub deliveries are merged correctly by BigQuery.\n *\n * Requirements:\n *\n * - Destination tables **must** declare a `PRIMARY KEY (...) NOT ENFORCED`\n * constraint and be clustered on that key. {@link BigQueryAdapter.createTable}\n * handles both for tables managed by this library.\n * - Tables should be created with `OPTIONS(max_staleness = INTERVAL …)`\n * so the CDC merge runs in the background instead of on every read\n * — see {@link BigQueryAdapterOptions.maxStaleness}.\n * - Service account needs `bigquery.tables.updateData` (e.g. via the\n * `roles/bigquery.dataEditor` role).\n *\n * @example\n * ```ts\n * import { BigQuery } from \"@google-cloud/bigquery\";\n * import { BigQueryAdapter } from \"@lpdjs/firestore-repo-service/sync/bigquery\";\n *\n * const adapter = new BigQueryAdapter({\n * projectId: \"my-project\",\n * datasetId: \"firestore_sync\",\n * bigquery: new BigQuery({ projectId: \"my-project\" }),\n * maxStaleness: \"INTERVAL 15 MINUTE\",\n * });\n * ```\n */\n\nimport type { BigQuery } from \"@google-cloud/bigquery\";\nimport type { z } from \"zod\";\nimport { SYNC_VERSION_COLUMN } from \"../constants\";\nimport { zodSchemaToColumns } from \"../schema-mapper\";\nimport type {\n LogicalType,\n RepoSyncConfig,\n SqlAdapter,\n SqlColumn,\n SqlDialect,\n SqlTableDef,\n SyncHealthResult,\n} from \"../types\";\nimport {\n isBigQueryTypeCompatible,\n normalizeBigQueryType,\n} from \"./bigquery-types\";\n\n// ---------------------------------------------------------------------------\n// Dialect\n// ---------------------------------------------------------------------------\n\n/** BigQuery SQL dialect mapping. */\nclass BigQueryDialect implements SqlDialect {\n readonly name = \"bigquery\";\n\n mapType(logical: LogicalType): string {\n switch (logical) {\n case \"string\":\n return \"STRING\";\n case \"number\":\n return \"FLOAT64\";\n case \"bigint\":\n return \"INT64\";\n case \"boolean\":\n return \"BOOL\";\n case \"timestamp\":\n return \"TIMESTAMP\";\n case \"json\":\n return \"JSON\";\n case \"text\":\n return \"STRING\";\n }\n }\n\n quoteIdentifier(id: string): string {\n // BigQuery escapes identifiers with backticks; a literal backtick inside\n // an identifier must be doubled. Without this, an identifier containing a\n // backtick (e.g. a column name propagated from a Firestore document key)\n // would break out of the quoting and enable DDL injection.\n return \"`\" + id.replace(/`/g, \"``\") + \"`\";\n }\n}\n\n/** Shared BigQuery dialect singleton. */\nexport const bigqueryDialect: SqlDialect = new BigQueryDialect();\n\n// ---------------------------------------------------------------------------\n// Storage Write API loader (kept loose so `@google-cloud/bigquery-storage`\n// stays an OPTIONAL peer dep)\n// ---------------------------------------------------------------------------\n\ntype StorageNs = {\n managedwriter: {\n WriterClient: new (opts?: any) => any;\n JSONWriter: new (params: { connection: any; protoDescriptor: any }) => any;\n DefaultStream: any;\n };\n adapt: {\n convertBigQuerySchemaToStorageTableSchema(schema: any): any;\n convertStorageSchemaToProto2Descriptor(\n schema: any,\n scope: string,\n ...opts: any[]\n ): any;\n withChangeType(): any;\n withChangeSequenceNumber(): any;\n };\n};\n\nlet storageNsCache: StorageNs | null = null;\nfunction loadStorageNs(): StorageNs {\n if (storageNsCache) return storageNsCache;\n // Lazy require so the library does not pull `@google-cloud/bigquery-storage`\n // unless this adapter is actually instantiated.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = require(\"@google-cloud/bigquery-storage\");\n storageNsCache = mod as StorageNs;\n return storageNsCache;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Format `__sync_version` (Firestore commit timestamp in microseconds since\n * epoch) as the 16-character hex string required by `_CHANGE_SEQUENCE_NUMBER`.\n *\n * BigQuery compares sequence numbers lexicographically, so a fixed-width hex\n * representation is mandatory for correct ordering.\n */\nfunction formatChangeSequenceNumber(version: unknown): string {\n let n: bigint;\n if (typeof version === \"bigint\") n = version;\n else if (typeof version === \"number\") n = BigInt(version);\n else if (typeof version === \"string\") n = BigInt(version);\n else n = 0n;\n if (n < 0n) n = 0n;\n return n.toString(16).padStart(16, \"0\");\n}\n\n/**\n * Returns true when the Storage Write append failed with a transient gRPC\n * status (UNAVAILABLE, DEADLINE_EXCEEDED, INTERNAL, ABORTED). Caller can\n * safely retry these.\n */\nfunction isRetryableStorageError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { code?: number };\n // gRPC codes: 4=DEADLINE_EXCEEDED, 10=ABORTED, 13=INTERNAL, 14=UNAVAILABLE\n return e.code === 4 || e.code === 10 || e.code === 13 || e.code === 14;\n}\n\nasync function withRetry<T>(\n fn: () => Promise<T>,\n maxRetries = 6,\n baseMs = 200,\n): Promise<T> {\n let attempt = 0;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n return await fn();\n } catch (err) {\n attempt++;\n if (!isRetryableStorageError(err) || attempt > maxRetries) throw err;\n const cap = baseMs * Math.pow(2, attempt);\n const delay = Math.random() * cap;\n await new Promise((res) => setTimeout(res, delay));\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal structural shape of `@google-cloud/bigquery`'s `BigQuery` client\n * actually used by the adapter (`.dataset(...)` and `.query(...)`).\n *\n * Why structural and not just `BigQuery`: TypeScript treats classes with\n * private fields nominally. When a consumer's `node_modules` ends up with\n * a *second* copy of `@google-cloud/bigquery` (very common in workspace\n * setups, peer-dep dedup misses, monorepo nesting), the `BigQuery` they\n * import is *technically* a different type than the one this library's\n * `BigQuery` references — even though they are runtime-identical — and\n * assignment fails with `Types have separate declarations of a private\n * property '_universeDomain'`.\n *\n * Accepting a structural superset sidesteps the duplicate-install issue\n * without giving up type safety on the methods we actually call.\n */\nexport interface BigQueryLike {\n dataset(datasetId: string): {\n table(tableName: string): any;\n [key: string]: any;\n };\n query(options: { query: string; params?: unknown[] } | string): Promise<any>;\n}\n\nexport interface BigQueryAdapterOptions {\n /** GCP project id that owns the dataset. */\n projectId: string;\n /** BigQuery dataset id. */\n datasetId: string;\n /**\n * BigQuery client used for DDL operations (createTable, addColumns,\n * getMetadata, executeRaw). Storage Write only handles inserts.\n *\n * Typed as the structural {@link BigQueryLike} (a superset satisfied by\n * `BigQuery` from `@google-cloud/bigquery`) to avoid TypeScript nominal\n * mismatches when the consumer's project ends up with two copies of\n * `@google-cloud/bigquery` in different `node_modules`. Pass\n * `new BigQuery({...})` from your own install — it satisfies this shape\n * structurally.\n */\n bigquery: BigQueryLike | BigQuery;\n /**\n * Optional pre-built Storage Write `WriterClient`. When omitted a new\n * one is created lazily on first use.\n */\n writerClient?: any;\n /**\n * Value passed to `OPTIONS(max_staleness = ...)` on `createTable`.\n *\n * **Why this matters**: in BigQuery CDC mode, Storage Write API rows\n * land in a delta buffer. They become visible to queries only after a\n * MERGE applies them to the base table. Two paths exist:\n *\n * - **Background MERGE** — runs periodically in the background, paid\n * for as part of CDC pricing, and never blocks your readers.\n * - **Read-time MERGE** — every `SELECT` query merges the delta on the\n * fly before returning. Always-fresh reads but every query pays for\n * the merge work.\n *\n * `max_staleness` is the tolerated lag between a write and what reads\n * see. Setting it tells BigQuery: \"background MERGE is fine if reads\n * are at most this stale\". When the threshold is exceeded, the next\n * read triggers a one-shot merge.\n *\n * **The default `INTERVAL 0` means \"always read-time merge\"** — every\n * query forces a full merge of pending CDC writes. That makes reads\n * dramatically slower and more expensive on busy tables, so this\n * library defaults to a 15 minute window in production.\n *\n * Recommended:\n * - `INTERVAL 15 MINUTE` in production (good cost/freshness trade-off).\n * - `INTERVAL 1 MINUTE` in dev for quick visibility.\n * - Set to `null` to omit the option entirely (only do this when you\n * know what you are doing — you'll likely hit slow & expensive reads).\n *\n * @default \"INTERVAL 15 MINUTE\"\n */\n maxStaleness?: string | null;\n}\n\nexport class SchemaTypeMismatchError extends Error {\n constructor(\n readonly tableName: string,\n readonly column: string,\n readonly existingType: string,\n readonly desiredType: string,\n ) {\n super(\n `Schema drift detected on \\`${tableName}\\`: column \\`${column}\\` has ` +\n `type ${existingType} in BigQuery but the current Zod schema maps ` +\n `it to ${desiredType}. BigQuery cannot safely convert between these ` +\n `types — to resolve, either (a) keep the BigQuery type and add a ` +\n `transform in your repo to coerce values, (b) rename the field in ` +\n `your Zod schema (creates a new column), or (c) drop & recreate ` +\n `the table.`,\n );\n this.name = \"SchemaTypeMismatchError\";\n }\n}\n\n/**\n * BigQuery implementation of {@link SqlAdapter} using the Storage Write API\n * in CDC mode. See module-level docstring for the rationale.\n */\nexport class BigQueryAdapter implements SqlAdapter {\n readonly name = \"bigquery\";\n private readonly bigquery: BigQueryLike;\n private readonly projectId: string;\n private readonly datasetId: string;\n private readonly maxStaleness: string | null;\n private writerClient: any;\n /** Cache of `{ writer, primaryKey }` per table name. */\n private readonly writers = new Map<\n string,\n { writer: any; primaryKey: string; timestampColumns?: Set<string> }\n >();\n\n constructor(options: BigQueryAdapterOptions) {\n this.bigquery = options.bigquery;\n this.projectId = options.projectId;\n this.datasetId = options.datasetId;\n this.maxStaleness =\n options.maxStaleness === undefined\n ? \"INTERVAL 15 MINUTE\"\n : options.maxStaleness;\n this.writerClient = options.writerClient;\n }\n\n get dialect(): SqlDialect {\n return bigqueryDialect;\n }\n\n // -------- SyncAdapter implementation ------------------------------------\n\n async targetExists(targetName: string): Promise<boolean> {\n return this.tableExists(targetName);\n }\n\n async upsert(\n targetName: string,\n items: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n return this.upsertRows(targetName, items, primaryKey);\n }\n\n async delete(\n targetName: string,\n primaryKey: string,\n ids: string[],\n ): Promise<void> {\n return this.deleteRows(targetName, primaryKey, ids);\n }\n\n async ensureTarget(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n exclude?: string[];\n columnMap?: Record<string, string>;\n }): Promise<void> {\n if (!options.schema) return;\n const { targetName, primaryKey, schema, exclude, columnMap } = options;\n const columns = zodSchemaToColumns(schema, this.dialect, {\n primaryKey,\n exclude,\n columnMap,\n });\n const exists = await this.tableExists(targetName);\n if (!exists) {\n await this.createTable({ tableName: targetName, columns });\n } else {\n const existing = await this.getTableColumnsWithTypes(targetName);\n const missing: typeof columns = [];\n for (const col of columns) {\n const existingType = existing.get(col.name);\n if (existingType === undefined) {\n missing.push(col);\n continue;\n }\n if (!isBigQueryTypeCompatible(existingType, col.sqlType)) {\n throw new SchemaTypeMismatchError(\n targetName,\n col.name,\n existingType,\n col.sqlType,\n );\n }\n }\n if (missing.length > 0) {\n await this.addColumns(targetName, missing);\n await this.onSchemaChange?.(targetName);\n }\n }\n }\n\n async healthCheck(options: {\n targetName: string;\n primaryKey: string;\n schema?: z.ZodObject<any>;\n repoConfig?: RepoSyncConfig<string>;\n }): Promise<SyncHealthResult> {\n const { targetName, primaryKey, schema, repoConfig } = options;\n if (!schema) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: \"No Zod schema attached to repository\",\n };\n }\n try {\n const exists = await this.tableExists(targetName);\n if (!exists) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: `Table \\`${targetName}\\` does not exist`,\n };\n }\n const actualCols = await this.getTableColumns(targetName);\n const expectedCols = zodSchemaToColumns(schema, this.dialect, {\n primaryKey,\n exclude: repoConfig?.exclude,\n columnMap: repoConfig?.columnMap as Record<string, string> | undefined,\n });\n const actualSet = new Set(actualCols);\n const expectedSet = new Set(expectedCols.map((c) => c.name));\n const missing = expectedCols.filter((c) => !actualSet.has(c.name));\n const extra = actualCols.filter((c) => !expectedSet.has(c));\n const matched = expectedCols.filter((c) => actualSet.has(c.name));\n const healthy = missing.length === 0;\n\n return {\n healthy,\n targetName,\n targetExists: true,\n error: healthy\n ? null\n : `Missing columns: ${missing.map((c) => c.name).join(\", \")}`,\n details: {\n expected: expectedCols.map((c) => ({\n name: c.name,\n type: c.sqlType,\n nullable: c.nullable,\n isPrimaryKey: c.isPrimaryKey,\n })),\n actual: actualCols,\n matched: matched.map((c) => c.name),\n missing: missing.map((c) => ({ name: c.name, type: c.sqlType })),\n extra,\n },\n };\n } catch (e: any) {\n return {\n healthy: false,\n targetName,\n targetExists: false,\n error: e?.message ?? String(e),\n };\n }\n }\n\n // -------- DDL (delegated to @google-cloud/bigquery) ----------------------\n\n async tableExists(tableName: string): Promise<boolean> {\n const [exists] = await this.dataset.table(tableName).exists();\n return exists;\n }\n\n async getTableColumns(tableName: string): Promise<string[]> {\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const fields: Array<{ name: string }> = metadata.schema?.fields ?? [];\n return fields.map((f) => f.name);\n }\n\n async getTableColumnsWithTypes(\n tableName: string,\n ): Promise<Map<string, string>> {\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const fields: Array<{ name: string; type: string }> =\n metadata.schema?.fields ?? [];\n const result = new Map<string, string>();\n for (const f of fields) {\n result.set(f.name, normalizeBigQueryType(f.type));\n }\n return result;\n }\n\n async createTable(table: SqlTableDef): Promise<void> {\n const qi = (id: string) => this.dialect.quoteIdentifier(id);\n const pk = table.columns.find((c) => c.isPrimaryKey)?.name;\n if (!pk) {\n throw new Error(\n `BigQueryAdapter requires a primary key on table \\`${table.tableName}\\` ` +\n `(Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`,\n );\n }\n const cols = table.columns\n .map((c) => {\n const notNull = c.isPrimaryKey ? \" NOT NULL\" : \"\";\n return ` ${qi(c.name)} ${c.sqlType}${notNull}`;\n })\n .join(\",\\n\");\n\n const opts: string[] = [];\n if (this.maxStaleness !== null) {\n opts.push(`max_staleness = ${this.maxStaleness}`);\n }\n const optionsClause =\n opts.length > 0 ? `\\nOPTIONS(${opts.join(\", \")})` : \"\";\n\n const ddl =\n `CREATE TABLE IF NOT EXISTS ${this.fqn(table.tableName)} (\\n${cols},\\n` +\n ` PRIMARY KEY (${qi(pk)}) NOT ENFORCED\\n)` +\n `\\nCLUSTER BY ${qi(pk)}` +\n `${optionsClause};`;\n\n await this.bigquery.query({ query: ddl });\n }\n\n async addColumns(tableName: string, columns: SqlColumn[]): Promise<void> {\n const qi = (id: string) => this.dialect.quoteIdentifier(id);\n for (const c of columns) {\n const stmt = `ALTER TABLE ${this.fqn(tableName)} ADD COLUMN ${qi(c.name)} ${c.sqlType};`;\n await this.bigquery.query({ query: stmt });\n }\n }\n\n async executeRaw(sql: string): Promise<void> {\n await this.bigquery.query({ query: sql });\n }\n\n /**\n * Invalidate the cached writer for a table. Called by the worker after\n * `addColumns` so the next append rebuilds the proto descriptor against\n * the new schema.\n */\n onSchemaChange(tableName: string): void {\n const cached = this.writers.get(tableName);\n if (cached) {\n try {\n cached.writer.close();\n } catch {\n // ignore — connection may already be torn down\n }\n this.writers.delete(tableName);\n }\n }\n\n // -------- Inserts (Storage Write API) -----------------------------------\n\n async insertRows(\n tableName: string,\n rows: Record<string, unknown>[],\n ): Promise<void> {\n if (rows.length === 0) return;\n // Plain inserts have no PK matching, but in CDC mode every row needs a\n // _CHANGE_TYPE. We treat them as UPSERT.\n const writer = await this.getOrCreateWriter(tableName);\n const timestampColumns = this.writers.get(tableName)?.timestampColumns;\n const cdc = rows.map((row) => ({\n ...this.normalizeRow(row, timestampColumns),\n _CHANGE_TYPE: \"UPSERT\",\n _CHANGE_SEQUENCE_NUMBER: formatChangeSequenceNumber(\n row[SYNC_VERSION_COLUMN],\n ),\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n async upsertRows(\n tableName: string,\n rows: Record<string, unknown>[],\n primaryKey: string,\n ): Promise<void> {\n if (rows.length === 0) return;\n const writer = await this.getOrCreateWriter(tableName, primaryKey);\n const timestampColumns = this.writers.get(tableName)?.timestampColumns;\n const cdc = rows.map((row) => ({\n ...this.normalizeRow(row, timestampColumns),\n _CHANGE_TYPE: \"UPSERT\",\n _CHANGE_SEQUENCE_NUMBER: formatChangeSequenceNumber(\n row[SYNC_VERSION_COLUMN],\n ),\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n async deleteRows(\n tableName: string,\n primaryKey: string,\n ids: string[],\n ): Promise<void> {\n if (ids.length === 0) return;\n const writer = await this.getOrCreateWriter(tableName, primaryKey);\n // Storage Write CDC requires a value for every NOT-NULL column (the PK)\n // and a `_CHANGE_TYPE`. Other columns may be omitted; missing values are\n // interpreted as NULL. We pass the maximum sequence number so the DELETE\n // wins over any concurrent UPSERT for the same key — tombstones from the\n // queue carry no `__sync_version` of their own.\n const cdc = ids.map((id) => ({\n [primaryKey]: id,\n _CHANGE_TYPE: \"DELETE\",\n _CHANGE_SEQUENCE_NUMBER: \"ffffffffffffffff\",\n }));\n await this.appendWithRetry(tableName, writer, cdc);\n }\n\n // -------- Internal helpers ----------------------------------------------\n\n private get dataset() {\n return this.bigquery.dataset(this.datasetId);\n }\n\n private fqn(tableName: string): string {\n // Escape backticks in both identifier parts to prevent DDL/DML injection\n // (BigQuery doubles backticks to embed a literal one).\n const esc = (s: string) => s.replace(/`/g, \"``\");\n return `\\`${esc(this.datasetId)}.${esc(tableName)}\\``;\n }\n\n /** ISO 8601 timestamp pattern (e.g. 2026-03-29T20:59:27.394Z) */\n private static readonly ISO_TIMESTAMP_RE =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/;\n\n /**\n * Convert a Date or epoch-millis number into the epoch-microseconds string\n * required by the Storage Write API for TIMESTAMP columns.\n *\n * The JSONWriter encodes through protobuf and a TIMESTAMP field is an\n * `int64`. Passing an ISO string would make `Long.fromString` throw\n * `interior hyphen` on the `-` characters.\n */\n private static toEpochMicros(d: Date): string {\n const ms = d.getTime();\n return (BigInt(ms) * 1000n).toString();\n }\n\n /** Convert JS values into shapes accepted by JSONWriter. */\n private normalizeRow(\n row: Record<string, unknown>,\n timestampColumns?: Set<string>,\n ): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(row)) {\n if (v === undefined) continue;\n if (v instanceof Date) {\n // TIMESTAMP column → int64 epoch micros (as string to preserve precision)\n out[k] = BigQueryAdapter.toEpochMicros(v);\n } else if (\n typeof v === \"string\" &&\n this.shouldCoerceTimestamp(k, v, timestampColumns)\n ) {\n // ISO timestamp produced upstream by `serializeDocument` (Firestore\n // Timestamp → ISO string) — convert to epoch micros for protobuf.\n const d = new Date(v);\n if (!Number.isNaN(d.getTime())) {\n out[k] = BigQueryAdapter.toEpochMicros(d);\n } else {\n out[k] = v;\n }\n } else if (typeof v === \"object\" && v !== null) {\n // JSON columns: serialise nested objects/arrays\n out[k] = JSON.stringify(v);\n } else if (typeof v === \"bigint\") {\n out[k] = v.toString();\n } else {\n out[k] = v;\n }\n }\n return out;\n }\n\n /**\n * Decide whether a string value should be coerced to an epoch-micros\n * timestamp.\n *\n * When the destination table's column types are known (writer already\n * built from table metadata), coerce **only** when the column is actually\n * TIMESTAMP/DATETIME/DATE. This prevents a business string that merely\n * looks like an ISO date (a log line, a slug, a formatted id) from being\n * silently rewritten — and avoids type-mismatch write errors on STRING\n * columns (issue #15).\n *\n * When column types are unavailable (e.g. a writer injected directly, or\n * metadata not yet fetched), fall back to the ISO-shape heuristic so\n * behaviour is unchanged.\n */\n private shouldCoerceTimestamp(\n column: string,\n value: string,\n timestampColumns?: Set<string>,\n ): boolean {\n if (timestampColumns) return timestampColumns.has(column);\n return BigQueryAdapter.ISO_TIMESTAMP_RE.test(value);\n }\n\n private async appendWithRetry(\n tableName: string,\n writer: any,\n rows: Record<string, unknown>[],\n ): Promise<void> {\n await withRetry(async () => {\n try {\n const pending = writer.appendRows(rows);\n await pending.getResult();\n } catch (err) {\n // On certain errors (schema drift, broken connection) drop the\n // cached writer so the next call rebuilds it.\n this.onSchemaChange(tableName);\n throw err;\n }\n });\n }\n\n private async getOrCreateWriter(\n tableName: string,\n primaryKey?: string,\n ): Promise<any> {\n const cached = this.writers.get(tableName);\n if (cached) {\n if (primaryKey && cached.primaryKey !== primaryKey) {\n // PK changed — invalidate and rebuild\n this.onSchemaChange(tableName);\n } else {\n return cached.writer;\n }\n }\n\n const ns = loadStorageNs();\n if (!this.writerClient) {\n this.writerClient = new ns.managedwriter.WriterClient({\n projectId: this.projectId,\n });\n }\n\n const [metadata] = await this.dataset.table(tableName).getMetadata();\n const bqSchema = { fields: metadata.schema?.fields ?? [] };\n if (!primaryKey) {\n // Try to recover PK from table constraints if available\n const tableConstraintsPK =\n metadata.tableConstraints?.primaryKey?.columns?.[0];\n primaryKey = tableConstraintsPK ?? bqSchema.fields[0]?.name;\n }\n\n const storageSchema =\n ns.adapt.convertBigQuerySchemaToStorageTableSchema(bqSchema);\n const protoDescriptor = ns.adapt.convertStorageSchemaToProto2Descriptor(\n storageSchema,\n \"Row\",\n ns.adapt.withChangeType(),\n ns.adapt.withChangeSequenceNumber(),\n );\n\n // Track which columns are actually TIMESTAMP-like so `normalizeRow` only\n // coerces ISO-looking strings when the destination column expects a\n // timestamp — a business string that merely *looks* like an ISO date must\n // not be silently converted to epoch micros (see issue #15).\n const timestampColumns = new Set<string>(\n (bqSchema.fields as Array<{ name: string; type?: string }>)\n .filter((f) =>\n [\"TIMESTAMP\", \"DATETIME\", \"DATE\"].includes(\n String(f.type ?? \"\").toUpperCase(),\n ),\n )\n .map((f) => f.name),\n );\n\n const destinationTable = `projects/${this.projectId}/datasets/${this.datasetId}/tables/${tableName}`;\n // Pass `DefaultStream` as `streamId` (not `streamType`): the `_default`\n // stream is implicit on every table, so the client must short-circuit to\n // `${destinationTable}/streams/_default` instead of calling\n // `createWriteStream({ type: DEFAULT })` which BigQuery rejects with\n // `Unable to create a stream with type TYPE_UNSPECIFIED`.\n const connection = await this.writerClient.createStreamConnection({\n streamId: ns.managedwriter.DefaultStream,\n destinationTable,\n });\n\n const writer = new ns.managedwriter.JSONWriter({\n connection,\n protoDescriptor,\n });\n\n this.writers.set(tableName, {\n writer,\n primaryKey: primaryKey ?? \"\",\n timestampColumns,\n });\n return writer;\n }\n\n /** Close all open writer connections. Useful for graceful shutdown. */\n async close(): Promise<void> {\n for (const { writer } of this.writers.values()) {\n try {\n writer.close();\n } catch {\n /* ignore */\n }\n }\n this.writers.clear();\n if (this.writerClient && typeof this.writerClient.close === \"function\") {\n try {\n this.writerClient.close();\n } catch {\n /* ignore */\n }\n }\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { BigQuery } from '@google-cloud/bigquery';
2
- import { b as SqlDialect, a as SqlAdapter, c as SqlTableDef, d as SqlColumn } from '../types-CbNcdNkb.cjs';
2
+ import { z } from 'zod';
3
+ import { b as SqlAdapter, c as SqlDialect, R as RepoSyncConfig, d as SyncHealthResult, e as SqlTableDef, f as SqlColumn } from '../types-LZ8dyfBz.cjs';
3
4
  import '../firebase-auth-Ds5P0kXT.cjs';
4
5
  import 'firebase-functions/v2/firestore';
5
6
  import 'firebase-functions/v2/https';
@@ -130,11 +131,19 @@ interface BigQueryAdapterOptions {
130
131
  */
131
132
  maxStaleness?: string | null;
132
133
  }
134
+ declare class SchemaTypeMismatchError extends Error {
135
+ readonly tableName: string;
136
+ readonly column: string;
137
+ readonly existingType: string;
138
+ readonly desiredType: string;
139
+ constructor(tableName: string, column: string, existingType: string, desiredType: string);
140
+ }
133
141
  /**
134
142
  * BigQuery implementation of {@link SqlAdapter} using the Storage Write API
135
143
  * in CDC mode. See module-level docstring for the rationale.
136
144
  */
137
145
  declare class BigQueryAdapter implements SqlAdapter {
146
+ readonly name = "bigquery";
138
147
  private readonly bigquery;
139
148
  private readonly projectId;
140
149
  private readonly datasetId;
@@ -144,6 +153,22 @@ declare class BigQueryAdapter implements SqlAdapter {
144
153
  private readonly writers;
145
154
  constructor(options: BigQueryAdapterOptions);
146
155
  get dialect(): SqlDialect;
156
+ targetExists(targetName: string): Promise<boolean>;
157
+ upsert(targetName: string, items: Record<string, unknown>[], primaryKey: string): Promise<void>;
158
+ delete(targetName: string, primaryKey: string, ids: string[]): Promise<void>;
159
+ ensureTarget(options: {
160
+ targetName: string;
161
+ primaryKey: string;
162
+ schema?: z.ZodObject<any>;
163
+ exclude?: string[];
164
+ columnMap?: Record<string, string>;
165
+ }): Promise<void>;
166
+ healthCheck(options: {
167
+ targetName: string;
168
+ primaryKey: string;
169
+ schema?: z.ZodObject<any>;
170
+ repoConfig?: RepoSyncConfig<string>;
171
+ }): Promise<SyncHealthResult>;
147
172
  tableExists(tableName: string): Promise<boolean>;
148
173
  getTableColumns(tableName: string): Promise<string[]>;
149
174
  getTableColumnsWithTypes(tableName: string): Promise<Map<string, string>>;
@@ -196,4 +221,4 @@ declare class BigQueryAdapter implements SqlAdapter {
196
221
  close(): Promise<void>;
197
222
  }
198
223
 
199
- export { BigQueryAdapter, type BigQueryAdapterOptions, type BigQueryLike, bigqueryDialect };
224
+ export { BigQueryAdapter, type BigQueryAdapterOptions, type BigQueryLike, SchemaTypeMismatchError, bigqueryDialect };
@@ -1,5 +1,6 @@
1
1
  import { BigQuery } from '@google-cloud/bigquery';
2
- import { b as SqlDialect, a as SqlAdapter, c as SqlTableDef, d as SqlColumn } from '../types-BaFkMwNb.js';
2
+ import { z } from 'zod';
3
+ import { b as SqlAdapter, c as SqlDialect, R as RepoSyncConfig, d as SyncHealthResult, e as SqlTableDef, f as SqlColumn } from '../types-BRPhmKFW.js';
3
4
  import '../firebase-auth-Ds5P0kXT.js';
4
5
  import 'firebase-functions/v2/firestore';
5
6
  import 'firebase-functions/v2/https';
@@ -130,11 +131,19 @@ interface BigQueryAdapterOptions {
130
131
  */
131
132
  maxStaleness?: string | null;
132
133
  }
134
+ declare class SchemaTypeMismatchError extends Error {
135
+ readonly tableName: string;
136
+ readonly column: string;
137
+ readonly existingType: string;
138
+ readonly desiredType: string;
139
+ constructor(tableName: string, column: string, existingType: string, desiredType: string);
140
+ }
133
141
  /**
134
142
  * BigQuery implementation of {@link SqlAdapter} using the Storage Write API
135
143
  * in CDC mode. See module-level docstring for the rationale.
136
144
  */
137
145
  declare class BigQueryAdapter implements SqlAdapter {
146
+ readonly name = "bigquery";
138
147
  private readonly bigquery;
139
148
  private readonly projectId;
140
149
  private readonly datasetId;
@@ -144,6 +153,22 @@ declare class BigQueryAdapter implements SqlAdapter {
144
153
  private readonly writers;
145
154
  constructor(options: BigQueryAdapterOptions);
146
155
  get dialect(): SqlDialect;
156
+ targetExists(targetName: string): Promise<boolean>;
157
+ upsert(targetName: string, items: Record<string, unknown>[], primaryKey: string): Promise<void>;
158
+ delete(targetName: string, primaryKey: string, ids: string[]): Promise<void>;
159
+ ensureTarget(options: {
160
+ targetName: string;
161
+ primaryKey: string;
162
+ schema?: z.ZodObject<any>;
163
+ exclude?: string[];
164
+ columnMap?: Record<string, string>;
165
+ }): Promise<void>;
166
+ healthCheck(options: {
167
+ targetName: string;
168
+ primaryKey: string;
169
+ schema?: z.ZodObject<any>;
170
+ repoConfig?: RepoSyncConfig<string>;
171
+ }): Promise<SyncHealthResult>;
147
172
  tableExists(tableName: string): Promise<boolean>;
148
173
  getTableColumns(tableName: string): Promise<string[]>;
149
174
  getTableColumnsWithTypes(tableName: string): Promise<Map<string, string>>;
@@ -196,4 +221,4 @@ declare class BigQueryAdapter implements SqlAdapter {
196
221
  close(): Promise<void>;
197
222
  }
198
223
 
199
- export { BigQueryAdapter, type BigQueryAdapterOptions, type BigQueryLike, bigqueryDialect };
224
+ export { BigQueryAdapter, type BigQueryAdapterOptions, type BigQueryLike, SchemaTypeMismatchError, bigqueryDialect };
@@ -1,8 +1,8 @@
1
- var E=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var m="__sync_version";function h(s){let t=s.toUpperCase();switch(t){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return t}}var p=class{constructor(){this.name="bigquery";}mapType(t){switch(t){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(t){return "`"+t.replace(/`/g,"``")+"`"}},C=new p,u=null;function I(){return u||(u=E("@google-cloud/bigquery-storage"),u)}function f(s){let t;return typeof s=="bigint"?t=s:typeof s=="number"||typeof s=="string"?t=BigInt(s):t=0n,t<0n&&(t=0n),t.toString(16).padStart(16,"0")}function N(s){if(!s||typeof s!="object")return false;let t=s;return t.code===4||t.code===10||t.code===13||t.code===14}async function R(s,t=6,e=200){let n=0;for(;;)try{return await s()}catch(r){if(n++,!N(r)||n>t)throw r;let i=e*Math.pow(2,n),a=Math.random()*i;await new Promise(c=>setTimeout(c,a));}}var g=class g{constructor(t){this.writers=new Map;this.bigquery=t.bigquery,this.projectId=t.projectId,this.datasetId=t.datasetId,this.maxStaleness=t.maxStaleness===void 0?"INTERVAL 15 MINUTE":t.maxStaleness,this.writerClient=t.writerClient;}get dialect(){return C}async tableExists(t){let[e]=await this.dataset.table(t).exists();return e}async getTableColumns(t){let[e]=await this.dataset.table(t).getMetadata();return (e.schema?.fields??[]).map(r=>r.name)}async getTableColumnsWithTypes(t){let[e]=await this.dataset.table(t).getMetadata(),n=e.schema?.fields??[],r=new Map;for(let i of n)r.set(i.name,h(i.type));return r}async createTable(t){let e=o=>this.dialect.quoteIdentifier(o),n=t.columns.find(o=>o.isPrimaryKey)?.name;if(!n)throw new Error(`BigQueryAdapter requires a primary key on table \`${t.tableName}\` (Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`);let r=t.columns.map(o=>{let d=o.isPrimaryKey?" NOT NULL":"";return ` ${e(o.name)} ${o.sqlType}${d}`}).join(`,
2
- `),i=[];this.maxStaleness!==null&&i.push(`max_staleness = ${this.maxStaleness}`);let a=i.length>0?`
3
- OPTIONS(${i.join(", ")})`:"",c=`CREATE TABLE IF NOT EXISTS ${this.fqn(t.tableName)} (
1
+ var O=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var g="__sync_version";var v={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 w(i){let e=i,t=e._zod?.def?.type;if(t)return v[t]??`Zod${t.charAt(0).toUpperCase()}${t.slice(1)}`;let n=e._def?.typeName;return n||""}function R(i){let e=i;if(e._zod?.def?.innerType)return e._zod.def.innerType;if(e._def?.innerType)return e._def.innerType}function b(i){let e=i;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 P=new Set(["ZodOptional","ZodNullable","ZodDefault"]);function M(i){let e=i,t=false;for(;;){let n=w(e);if(!P.has(n))break;(n==="ZodOptional"||n==="ZodNullable")&&(t=true);let r=R(e);if(!r)break;e=r;}return {inner:e,nullable:t}}var D={ZodString:"string",ZodNumber:"number",ZodBigInt:"bigint",ZodBoolean:"boolean",ZodDate:"timestamp",ZodEnum:"string",ZodNativeEnum:"string",ZodLiteral:"string"};function _(i,e,t,n,r,s,o,d){for(let[a,p]of Object.entries(i)){let u=t?`${t}__${a}`:a;if(r.has(a)||r.has(u))continue;let{inner:l,nullable:y}=M(p),f=w(l),h=n||y;if(f==="ZodObject"){let x=b(l);_(x,e,u,h,r,s,o,d);continue}let c=D[f]??"json",N=u===o||a===o,q=s[u]??s[a]??u;d.push({name:q,sqlType:e.mapType(c),nullable:N?false:h,isPrimaryKey:N});}}function C(i,e,t={}){let{primaryKey:n,exclude:r=[],columnMap:s={}}=t,o=new Set(r),d=b(i),a=[];return _(d,e,"",false,o,s,n,a),a.some(p=>p.name===g)||a.push({name:g,sqlType:e.mapType("bigint"),nullable:true,isPrimaryKey:false,description:"Monotonic publish version (Date.now() ms). Internal."}),a}function T(i){let e=i.toUpperCase();switch(e){case "INTEGER":return "INT64";case "FLOAT":return "FLOAT64";case "BOOLEAN":return "BOOL";default:return e}}function z(i,e){let t=T(i),n=T(e);return t===n?true:{INT64:["NUMERIC","BIGNUMERIC","FLOAT64"],NUMERIC:["BIGNUMERIC","FLOAT64"],DATE:["DATETIME","TIMESTAMP"],DATETIME:["TIMESTAMP"]}[t]?.includes(n)??false}var E=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,"``")+"`"}},k=new E,S=null;function L(){return S||(S=O("@google-cloud/bigquery-storage"),S)}function I(i){let e;return typeof i=="bigint"?e=i:typeof i=="number"||typeof i=="string"?e=BigInt(i):e=0n,e<0n&&(e=0n),e.toString(16).padStart(16,"0")}function B(i){if(!i||typeof i!="object")return false;let e=i;return e.code===4||e.code===10||e.code===13||e.code===14}async function j(i,e=6,t=200){let n=0;for(;;)try{return await i()}catch(r){if(n++,!B(r)||n>e)throw r;let s=t*Math.pow(2,n),o=Math.random()*s;await new Promise(d=>setTimeout(d,o));}}var Z=class extends Error{constructor(t,n,r,s){super(`Schema drift detected on \`${t}\`: column \`${n}\` has type ${r} 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=n;this.existingType=r;this.desiredType=s;this.name="SchemaTypeMismatchError";}},m=class m{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 k}async targetExists(e){return this.tableExists(e)}async upsert(e,t,n){return this.upsertRows(e,t,n)}async delete(e,t,n){return this.deleteRows(e,t,n)}async ensureTarget(e){if(!e.schema)return;let{targetName:t,primaryKey:n,schema:r,exclude:s,columnMap:o}=e,d=C(r,this.dialect,{primaryKey:n,exclude:s,columnMap:o});if(!await this.tableExists(t))await this.createTable({tableName:t,columns:d});else {let p=await this.getTableColumnsWithTypes(t),u=[];for(let l of d){let y=p.get(l.name);if(y===void 0){u.push(l);continue}if(!z(y,l.sqlType))throw new Z(t,l.name,y,l.sqlType)}u.length>0&&(await this.addColumns(t,u),await this.onSchemaChange?.(t));}}async healthCheck(e){let{targetName:t,primaryKey:n,schema:r,repoConfig:s}=e;if(!r)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 d=await this.getTableColumns(t),a=C(r,this.dialect,{primaryKey:n,exclude:s?.exclude,columnMap:s?.columnMap}),p=new Set(d),u=new Set(a.map(c=>c.name)),l=a.filter(c=>!p.has(c.name)),y=d.filter(c=>!u.has(c)),f=a.filter(c=>p.has(c.name)),h=l.length===0;return {healthy:h,targetName:t,targetExists:!0,error:h?null:`Missing columns: ${l.map(c=>c.name).join(", ")}`,details:{expected:a.map(c=>({name:c.name,type:c.sqlType,nullable:c.nullable,isPrimaryKey:c.isPrimaryKey})),actual:d,matched:f.map(c=>c.name),missing:l.map(c=>({name:c.name,type:c.sqlType})),extra:y}}}catch(o){return {healthy:false,targetName:t,targetExists:false,error:o?.message??String(o)}}}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(r=>r.name)}async getTableColumnsWithTypes(e){let[t]=await this.dataset.table(e).getMetadata(),n=t.schema?.fields??[],r=new Map;for(let s of n)r.set(s.name,T(s.type));return r}async createTable(e){let t=a=>this.dialect.quoteIdentifier(a),n=e.columns.find(a=>a.isPrimaryKey)?.name;if(!n)throw new Error(`BigQueryAdapter requires a primary key on table \`${e.tableName}\` (Storage Write CDC mode needs PRIMARY KEY NOT ENFORCED).`);let r=e.columns.map(a=>{let p=a.isPrimaryKey?" NOT NULL":"";return ` ${t(a.name)} ${a.sqlType}${p}`}).join(`,
2
+ `),s=[];this.maxStaleness!==null&&s.push(`max_staleness = ${this.maxStaleness}`);let o=s.length>0?`
3
+ OPTIONS(${s.join(", ")})`:"",d=`CREATE TABLE IF NOT EXISTS ${this.fqn(e.tableName)} (
4
4
  ${r},
5
- PRIMARY KEY (${e(n)}) NOT ENFORCED
5
+ PRIMARY KEY (${t(n)}) NOT ENFORCED
6
6
  )
7
- CLUSTER BY ${e(n)}${a};`;await this.bigquery.query({query:c});}async addColumns(t,e){let n=r=>this.dialect.quoteIdentifier(r);for(let r of e){let i=`ALTER TABLE ${this.fqn(t)} ADD COLUMN ${n(r.name)} ${r.sqlType};`;await this.bigquery.query({query:i});}}async executeRaw(t){await this.bigquery.query({query:t});}onSchemaChange(t){let e=this.writers.get(t);if(e){try{e.writer.close();}catch{}this.writers.delete(t);}}async insertRows(t,e){if(e.length===0)return;let n=await this.getOrCreateWriter(t),r=this.writers.get(t)?.timestampColumns,i=e.map(a=>({...this.normalizeRow(a,r),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:f(a[m])}));await this.appendWithRetry(t,n,i);}async upsertRows(t,e,n){if(e.length===0)return;let r=await this.getOrCreateWriter(t,n),i=this.writers.get(t)?.timestampColumns,a=e.map(c=>({...this.normalizeRow(c,i),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:f(c[m])}));await this.appendWithRetry(t,r,a);}async deleteRows(t,e,n){if(n.length===0)return;let r=await this.getOrCreateWriter(t,e),i=n.map(a=>({[e]:a,_CHANGE_TYPE:"DELETE",_CHANGE_SEQUENCE_NUMBER:"ffffffffffffffff"}));await this.appendWithRetry(t,r,i);}get dataset(){return this.bigquery.dataset(this.datasetId)}fqn(t){let e=n=>n.replace(/`/g,"``");return `\`${e(this.datasetId)}.${e(t)}\``}static toEpochMicros(t){let e=t.getTime();return (BigInt(e)*1000n).toString()}normalizeRow(t,e){let n={};for(let[r,i]of Object.entries(t))if(i!==void 0)if(i instanceof Date)n[r]=g.toEpochMicros(i);else if(typeof i=="string"&&this.shouldCoerceTimestamp(r,i,e)){let a=new Date(i);Number.isNaN(a.getTime())?n[r]=i:n[r]=g.toEpochMicros(a);}else typeof i=="object"&&i!==null?n[r]=JSON.stringify(i):typeof i=="bigint"?n[r]=i.toString():n[r]=i;return n}shouldCoerceTimestamp(t,e,n){return n?n.has(t):g.ISO_TIMESTAMP_RE.test(e)}async appendWithRetry(t,e,n){await R(async()=>{try{await e.appendRows(n).getResult();}catch(r){throw this.onSchemaChange(t),r}});}async getOrCreateWriter(t,e){let n=this.writers.get(t);if(n)if(e&&n.primaryKey!==e)this.onSchemaChange(t);else return n.writer;let r=I();this.writerClient||(this.writerClient=new r.managedwriter.WriterClient({projectId:this.projectId}));let[i]=await this.dataset.table(t).getMetadata(),a={fields:i.schema?.fields??[]};e||(e=i.tableConstraints?.primaryKey?.columns?.[0]??a.fields[0]?.name);let c=r.adapt.convertBigQuerySchemaToStorageTableSchema(a),o=r.adapt.convertStorageSchemaToProto2Descriptor(c,"Row",r.adapt.withChangeType(),r.adapt.withChangeSequenceNumber()),d=new Set(a.fields.filter(l=>["TIMESTAMP","DATETIME","DATE"].includes(String(l.type??"").toUpperCase())).map(l=>l.name)),T=`projects/${this.projectId}/datasets/${this.datasetId}/tables/${t}`,S=await this.writerClient.createStreamConnection({streamId:r.managedwriter.DefaultStream,destinationTable:T}),y=new r.managedwriter.JSONWriter({connection:S,protoDescriptor:o});return this.writers.set(t,{writer:y,primaryKey:e??"",timestampColumns:d}),y}async close(){for(let{writer:t}of this.writers.values())try{t.close();}catch{}if(this.writers.clear(),this.writerClient&&typeof this.writerClient.close=="function")try{this.writerClient.close();}catch{}}};g.ISO_TIMESTAMP_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;var w=g;export{w as BigQueryAdapter,C as bigqueryDialect};//# sourceMappingURL=bigquery.js.map
7
+ CLUSTER BY ${t(n)}${o};`;await this.bigquery.query({query:d});}async addColumns(e,t){let n=r=>this.dialect.quoteIdentifier(r);for(let r of t){let s=`ALTER TABLE ${this.fqn(e)} ADD COLUMN ${n(r.name)} ${r.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 n=await this.getOrCreateWriter(e),r=this.writers.get(e)?.timestampColumns,s=t.map(o=>({...this.normalizeRow(o,r),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:I(o[g])}));await this.appendWithRetry(e,n,s);}async upsertRows(e,t,n){if(t.length===0)return;let r=await this.getOrCreateWriter(e,n),s=this.writers.get(e)?.timestampColumns,o=t.map(d=>({...this.normalizeRow(d,s),_CHANGE_TYPE:"UPSERT",_CHANGE_SEQUENCE_NUMBER:I(d[g])}));await this.appendWithRetry(e,r,o);}async deleteRows(e,t,n){if(n.length===0)return;let r=await this.getOrCreateWriter(e,t),s=n.map(o=>({[t]:o,_CHANGE_TYPE:"DELETE",_CHANGE_SEQUENCE_NUMBER:"ffffffffffffffff"}));await this.appendWithRetry(e,r,s);}get dataset(){return this.bigquery.dataset(this.datasetId)}fqn(e){let t=n=>n.replace(/`/g,"``");return `\`${t(this.datasetId)}.${t(e)}\``}static toEpochMicros(e){let t=e.getTime();return (BigInt(t)*1000n).toString()}normalizeRow(e,t){let n={};for(let[r,s]of Object.entries(e))if(s!==void 0)if(s instanceof Date)n[r]=m.toEpochMicros(s);else if(typeof s=="string"&&this.shouldCoerceTimestamp(r,s,t)){let o=new Date(s);Number.isNaN(o.getTime())?n[r]=s:n[r]=m.toEpochMicros(o);}else typeof s=="object"&&s!==null?n[r]=JSON.stringify(s):typeof s=="bigint"?n[r]=s.toString():n[r]=s;return n}shouldCoerceTimestamp(e,t,n){return n?n.has(e):m.ISO_TIMESTAMP_RE.test(t)}async appendWithRetry(e,t,n){await j(async()=>{try{await t.appendRows(n).getResult();}catch(r){throw this.onSchemaChange(e),r}});}async getOrCreateWriter(e,t){let n=this.writers.get(e);if(n)if(t&&n.primaryKey!==t)this.onSchemaChange(e);else return n.writer;let r=L();this.writerClient||(this.writerClient=new r.managedwriter.WriterClient({projectId:this.projectId}));let[s]=await this.dataset.table(e).getMetadata(),o={fields:s.schema?.fields??[]};t||(t=s.tableConstraints?.primaryKey?.columns?.[0]??o.fields[0]?.name);let d=r.adapt.convertBigQuerySchemaToStorageTableSchema(o),a=r.adapt.convertStorageSchemaToProto2Descriptor(d,"Row",r.adapt.withChangeType(),r.adapt.withChangeSequenceNumber()),p=new Set(o.fields.filter(f=>["TIMESTAMP","DATETIME","DATE"].includes(String(f.type??"").toUpperCase())).map(f=>f.name)),u=`projects/${this.projectId}/datasets/${this.datasetId}/tables/${e}`,l=await this.writerClient.createStreamConnection({streamId:r.managedwriter.DefaultStream,destinationTable:u}),y=new r.managedwriter.JSONWriter({connection:l,protoDescriptor:a});return this.writers.set(e,{writer:y,primaryKey:t??"",timestampColumns:p}),y}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{}}};m.ISO_TIMESTAMP_RE=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;var A=m;export{A as BigQueryAdapter,Z as SchemaTypeMismatchError,k as bigqueryDialect};//# sourceMappingURL=bigquery.js.map
8
8
  //# sourceMappingURL=bigquery.js.map