@pgxsinkit/client 0.1.50 → 0.1.53

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 (54) hide show
  1. package/dist/error-chain.d.ts +9 -0
  2. package/dist/error-chain.d.ts.map +1 -0
  3. package/dist/export-dump.d.ts.map +1 -1
  4. package/dist/index.d.ts +66 -13
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +284 -82
  7. package/dist/index.js.map +21 -19
  8. package/dist/local-tables.d.ts +6 -0
  9. package/dist/local-tables.d.ts.map +1 -1
  10. package/dist/schema.d.ts +18 -1
  11. package/dist/schema.d.ts.map +1 -1
  12. package/dist/shape-sync.d.ts +6 -0
  13. package/dist/shape-sync.d.ts.map +1 -1
  14. package/dist/sync/apply.d.ts +12 -1
  15. package/dist/sync/apply.d.ts.map +1 -1
  16. package/dist/sync/index.d.ts +1 -1
  17. package/dist/sync/index.d.ts.map +1 -1
  18. package/dist/sync/metadata-tables.d.ts +16 -0
  19. package/dist/sync/metadata-tables.d.ts.map +1 -1
  20. package/dist/sync/subscription-state.d.ts +10 -2
  21. package/dist/sync/subscription-state.d.ts.map +1 -1
  22. package/dist/sync/tags.d.ts +16 -4
  23. package/dist/sync/tags.d.ts.map +1 -1
  24. package/dist/sync/types.d.ts +12 -0
  25. package/dist/sync/types.d.ts.map +1 -1
  26. package/dist/worker/attach-sync-client.d.ts +4 -1
  27. package/dist/worker/attach-sync-client.d.ts.map +1 -1
  28. package/dist/worker/define-sync-worker.d.ts +41 -0
  29. package/dist/worker/define-sync-worker.d.ts.map +1 -1
  30. package/dist/worker/live-query-manager.d.ts.map +1 -1
  31. package/dist/worker/live-query-params-guard.d.ts +14 -0
  32. package/dist/worker/live-query-params-guard.d.ts.map +1 -0
  33. package/dist/worker/protocol.d.ts +17 -1
  34. package/dist/worker/protocol.d.ts.map +1 -1
  35. package/package.json +2 -2
  36. package/skills/core/SKILL.md +6 -2
  37. package/skills/operating/SKILL.md +28 -5
  38. package/src/error-chain.ts +26 -0
  39. package/src/export-dump.ts +5 -1
  40. package/src/index.ts +175 -41
  41. package/src/local-tables.ts +7 -0
  42. package/src/schema.ts +22 -4
  43. package/src/shape-sync.ts +11 -0
  44. package/src/sync/apply.ts +164 -26
  45. package/src/sync/index.ts +45 -8
  46. package/src/sync/metadata-tables.ts +41 -0
  47. package/src/sync/subscription-state.ts +29 -4
  48. package/src/sync/tags.ts +34 -9
  49. package/src/sync/types.ts +12 -0
  50. package/src/worker/attach-sync-client.ts +119 -20
  51. package/src/worker/define-sync-worker.ts +112 -2
  52. package/src/worker/live-query-manager.ts +6 -0
  53. package/src/worker/live-query-params-guard.ts +57 -0
  54. package/src/worker/protocol.ts +28 -0
package/dist/index.js CHANGED
@@ -351,6 +351,21 @@ function createIntervalConvergenceTrigger(intervalMs) {
351
351
  };
352
352
  }
353
353
 
354
+ // packages/client/src/error-chain.ts
355
+ function describeErrorChain(error, maxDepth = 5) {
356
+ const parts = [];
357
+ let current = error;
358
+ for (let depth = 0;depth < maxDepth && current != null; depth += 1) {
359
+ const message = current instanceof Error ? current.message : typeof current === "string" ? current : JSON.stringify(current);
360
+ const code = typeof current === "object" && "code" in current ? current.code : undefined;
361
+ const detail = typeof current === "object" && "detail" in current ? current.detail : undefined;
362
+ const asText = (value) => typeof value === "string" ? value : JSON.stringify(value);
363
+ parts.push([message, code != null ? `[${asText(code)}]` : undefined, detail != null ? `(${asText(detail)})` : undefined].filter(Boolean).join(" "));
364
+ current = current instanceof Error ? current.cause : undefined;
365
+ }
366
+ return parts.join(" \u2190 caused by: ");
367
+ }
368
+
354
369
  // packages/client/src/export-dump.ts
355
370
  import { PGlite } from "@electric-sql/pglite";
356
371
 
@@ -496,7 +511,7 @@ async function runThrowawayCloneDump(pglite, startPerf, options = {}) {
496
511
  const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), "memory");
497
512
  const cloneBootStartedAtMs = nowMs2() - startPerf;
498
513
  const cloneBootStartPerf = nowMs2();
499
- const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped });
514
+ const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped, relaxedDurability: true });
500
515
  const cloneBootMs = nowMs2() - cloneBootStartPerf;
501
516
  let sqlBytes;
502
517
  let pgDumpStartedAtMs;
@@ -956,6 +971,20 @@ function targetColumn(target, name) {
956
971
  }
957
972
  return column;
958
973
  }
974
+ function hasGeneratedIdentityColumn(target, colNames) {
975
+ return colNames.some((name) => {
976
+ const column = target.columnByName[name];
977
+ return column?.generatedIdentity !== undefined && column.generatedIdentity.type !== "byDefault";
978
+ });
979
+ }
980
+ function insertInto(db, target, colNames) {
981
+ const builder = db.insert(target.table);
982
+ return hasGeneratedIdentityColumn(target, colNames) ? builder.overridingSystemValue() : builder;
983
+ }
984
+ function castTypeFor(column, tableSchema) {
985
+ const base = column.isEnum ? tableSchema ? `${quoteIdentifier2(tableSchema)}.${quoteIdentifier2(column.sqlType)}` : quoteIdentifier2(column.sqlType) : column.sqlType;
986
+ return `${base}${column.isArray ? "[]" : ""}`;
987
+ }
959
988
  var MAX_INSERT_PARAMS = 32000;
960
989
  var MAX_INSERT_BYTES = 50 * 1024 * 1024;
961
990
  function renderInsert(db, target, colNames, rowCount) {
@@ -964,7 +993,7 @@ function renderInsert(db, target, colNames, rowCount) {
964
993
  if (cached)
965
994
  return cached;
966
995
  const placeholderRows = Array.from({ length: rowCount }, (_, r) => Object.fromEntries(colNames.map((name, ci) => [target.propertyKeyByName[name], sql.placeholder(`${r}_${ci}`)])));
967
- const rendered = db.insert(target.table).values(placeholderRows).toSQL();
996
+ const rendered = insertInto(db, target, colNames).values(placeholderRows).toSQL();
968
997
  const value = { sqlText: rendered.sql, params: rendered.params };
969
998
  target.insertRenderCache.set(key, value);
970
999
  return value;
@@ -1082,6 +1111,16 @@ async function applyInsertsToTable({ pg, target, messages, debug }) {
1082
1111
  if (debug)
1083
1112
  console.log(`Inserted ${messages.length} rows using INSERT`);
1084
1113
  }
1114
+ function upsertConflictSpec(target, columns) {
1115
+ const pkSet = new Set(target.primaryKey);
1116
+ const nonPkColumns = columns.filter((column) => !pkSet.has(column));
1117
+ const conflictTarget = target.primaryKey.map((column) => targetColumn(target, column));
1118
+ const conflictSet = {};
1119
+ for (const column of nonPkColumns) {
1120
+ conflictSet[target.propertyKeyByName[column]] = sql`excluded.${sql.identifier(column)}`;
1121
+ }
1122
+ return { conflictTarget, conflictSet, nonPkColumns };
1123
+ }
1085
1124
  async function applyUpsertsToTable({ pg, target, messages, debug }) {
1086
1125
  const primaryKey = target.primaryKey;
1087
1126
  if (primaryKey.length === 0)
@@ -1091,19 +1130,13 @@ async function applyUpsertsToTable({ pg, target, messages, debug }) {
1091
1130
  if (!firstRow)
1092
1131
  return;
1093
1132
  const columns = Object.keys(firstRow);
1094
- const pkSet = new Set(primaryKey);
1095
- const nonPkColumns = columns.filter((column) => !pkSet.has(column));
1096
- const conflictTarget = primaryKey.map((column) => targetColumn(target, column));
1097
- const conflictSet = {};
1098
- for (const column of nonPkColumns) {
1099
- conflictSet[target.propertyKeyByName[column]] = sql`excluded.${sql.identifier(column)}`;
1100
- }
1133
+ const { conflictTarget, conflictSet, nonPkColumns } = upsertConflictSpec(target, columns);
1101
1134
  const perRow = columns.length;
1102
1135
  const rowsPerBatch = Math.max(1, Math.floor(MAX_INSERT_PARAMS / perRow));
1103
1136
  const db = drizzleOverPg(pg);
1104
1137
  for (let i = 0;i < data.length; i += rowsPerBatch) {
1105
1138
  const batch = data.slice(i, i + rowsPerBatch).map((row) => toDriverRow(target, row));
1106
- const insert = db.insert(target.table).values(batch);
1139
+ const insert = insertInto(db, target, columns).values(batch);
1107
1140
  if (nonPkColumns.length > 0) {
1108
1141
  await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet });
1109
1142
  } else {
@@ -1115,11 +1148,22 @@ async function applyUpsertsToTable({ pg, target, messages, debug }) {
1115
1148
  }
1116
1149
  function jsonRecordsetColumns(target, firstRow) {
1117
1150
  const present = (name) => Object.prototype.hasOwnProperty.call(firstRow, name);
1118
- return target.columnTypes.filter((column) => present(column.name)).map((column) => ({ name: column.name, castType: `${column.sqlType}${column.isArray ? "[]" : ""}` }));
1151
+ const { schema } = getTableConfig2(target.table);
1152
+ return target.columnTypes.filter((column) => present(column.name)).map((column) => ({ name: column.name, castType: castTypeFor(column, schema) }));
1153
+ }
1154
+ function jsonConflictClause(target, columns) {
1155
+ const pkSet = new Set(target.primaryKey);
1156
+ const nonPkColumns = columns.map((column) => column.name).filter((name) => !pkSet.has(name));
1157
+ const conflictTarget = sql.join(target.primaryKey.map((name) => sql`${sql.identifier(name)}`), sql`, `);
1158
+ if (nonPkColumns.length === 0) {
1159
+ return sql`ON CONFLICT (${conflictTarget}) DO NOTHING`;
1160
+ }
1161
+ const setList = sql.join(nonPkColumns.map((name) => sql`${sql.identifier(name)} = excluded.${sql.identifier(name)}`), sql`, `);
1162
+ return sql`ON CONFLICT (${conflictTarget}) DO UPDATE SET ${setList}`;
1119
1163
  }
1120
- async function applyMessagesToTableWithJson({ pg, target, messages, debug }) {
1164
+ async function applyMessagesToTableWithJsonImpl({ pg, target, messages, debug }, conflict) {
1121
1165
  if (debug)
1122
- console.log("applying messages with json_to_recordset");
1166
+ console.log(`applying messages with json_to_recordset${conflict ? " (upsert)" : ""}`);
1123
1167
  const data = messages.map((message) => message.value);
1124
1168
  const firstRow = data[0];
1125
1169
  if (!firstRow) {
@@ -1128,16 +1172,27 @@ async function applyMessagesToTableWithJson({ pg, target, messages, debug }) {
1128
1172
  const columns = jsonRecordsetColumns(target, firstRow);
1129
1173
  const targetTable = target.table;
1130
1174
  const recordDef = columns.map((column) => `${quoteIdentifier2(column.name)} ${column.castType}`).join(", ");
1175
+ const conflictClause = conflict ? sql` ${conflict}` : sql``;
1131
1176
  const db = drizzleOverPg(pg);
1132
1177
  const max = 1e4;
1133
1178
  for (let i = 0;i < data.length; i += max) {
1134
1179
  const batch = data.slice(i, i + max);
1135
- await db.execute(sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})`);
1180
+ await db.execute(sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})${conflictClause}`);
1136
1181
  }
1137
1182
  if (debug) {
1138
- console.log(`Inserted ${messages.length} rows using json_to_recordset`);
1183
+ console.log(`${conflict ? "Upserted" : "Inserted"} ${messages.length} rows using json_to_recordset`);
1139
1184
  }
1140
1185
  }
1186
+ async function applyMessagesToTableWithJson(options) {
1187
+ return applyMessagesToTableWithJsonImpl(options, undefined);
1188
+ }
1189
+ async function applyUpsertsToTableWithJson(options) {
1190
+ const firstRow = options.messages[0]?.value;
1191
+ if (!firstRow)
1192
+ return;
1193
+ const columns = jsonRecordsetColumns(options.target, firstRow);
1194
+ return applyMessagesToTableWithJsonImpl(options, jsonConflictClause(options.target, columns));
1195
+ }
1141
1196
  function copyColumnUdts(target) {
1142
1197
  const map = {};
1143
1198
  for (const column of target.columnTypes) {
@@ -1175,12 +1230,13 @@ async function applyMessagesToTableWithCopy({ pg, target, messages, debug }) {
1175
1230
  var JSON_RECORDSET_BATCH = 1e4;
1176
1231
  function recordsetColumnCasts(target, columnNames) {
1177
1232
  const byName = new Map(target.columnTypes.map((column) => [column.name, column]));
1233
+ const { schema } = getTableConfig2(target.table);
1178
1234
  return columnNames.map((name) => {
1179
1235
  const column = byName.get(name);
1180
1236
  if (!column) {
1181
1237
  throw new Error(`recordsetColumnCasts: no registered type for column ${JSON.stringify(name)}`);
1182
1238
  }
1183
- return { name, castType: `${column.sqlType}${column.isArray ? "[]" : ""}` };
1239
+ return { name, castType: castTypeFor(column, schema) };
1184
1240
  });
1185
1241
  }
1186
1242
  async function applyBulkDeletesToTable({ pg, target, messages, debug }) {
@@ -1244,6 +1300,7 @@ async function applyBulkUpdatesToTable({ pg, target, messages, debug }) {
1244
1300
 
1245
1301
  // packages/client/src/sync/metadata-tables.ts
1246
1302
  import { index, jsonb, pgSchema, primaryKey, text } from "drizzle-orm/pg-core";
1303
+ var SESSION_METADATA_SCHEMA = "pg_temp";
1247
1304
  function buildSubscriptionsMetadata(schema) {
1248
1305
  return schema.table("subscriptions_metadata", {
1249
1306
  key: text("key").primaryKey(),
@@ -1274,6 +1331,20 @@ function getMetadataTables(metadataSchema) {
1274
1331
  }
1275
1332
  return tables;
1276
1333
  }
1334
+ var sessionCache;
1335
+ function getSessionMetadataTables() {
1336
+ if (!sessionCache) {
1337
+ const schema = pgSchema(SESSION_METADATA_SCHEMA);
1338
+ sessionCache = {
1339
+ subscriptionsMetadata: buildSubscriptionsMetadata(schema),
1340
+ shapeRowTags: buildShapeRowTags(schema)
1341
+ };
1342
+ }
1343
+ return sessionCache;
1344
+ }
1345
+ function pickMetadataTables(metadataSchema, sessionScoped) {
1346
+ return sessionScoped ? getSessionMetadataTables() : getMetadataTables(metadataSchema);
1347
+ }
1277
1348
 
1278
1349
  // packages/client/src/sync/tags.ts
1279
1350
  var DEFAULT_METADATA_SCHEMA = "pgxsinkit";
@@ -1287,15 +1358,20 @@ function shapeRowTagsTableName(metadataSchema) {
1287
1358
  const config = getTableConfig3(getMetadataTables(metadataSchema).shapeRowTags);
1288
1359
  return `${quoteIdentifier3(config.schema ?? "public")}.${quoteIdentifier3(config.name)}`;
1289
1360
  }
1361
+ function shapeRowTagsSessionTableName() {
1362
+ const config = getTableConfig3(getSessionMetadataTables().shapeRowTags);
1363
+ return `${quoteIdentifier3(config.schema ?? "public")}.${quoteIdentifier3(config.name)}`;
1364
+ }
1290
1365
  function shapeTableId(schema, table) {
1291
1366
  return `${schema ?? "public"}.${table}`;
1292
1367
  }
1293
1368
  function buildClearShapeTagsSql(shapeTable, metadataSchema = DEFAULT_METADATA_SCHEMA) {
1294
- const table = shapeRowTagsTableName(metadataSchema);
1295
- return `DO $$ BEGIN
1296
- IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN
1369
+ const clearOne = (table) => ` IF to_regclass(${quoteSqlLiteral(table)}) IS NOT NULL THEN
1297
1370
  DELETE FROM ${table} WHERE shape_table = ${quoteSqlLiteral(shapeTable)};
1298
- END IF;
1371
+ END IF;`;
1372
+ return `DO $$ BEGIN
1373
+ ${clearOne(shapeRowTagsTableName(metadataSchema))}
1374
+ ${clearOne(shapeRowTagsSessionTableName())}
1299
1375
  END $$;`;
1300
1376
  }
1301
1377
  function serializeRowPk(value, primaryKey2) {
@@ -1336,9 +1412,10 @@ async function applyShapeTagSync({
1336
1412
  metadataSchema,
1337
1413
  shapeTable,
1338
1414
  messages,
1339
- primaryKey: primaryKey2
1415
+ primaryKey: primaryKey2,
1416
+ sessionScoped = false
1340
1417
  }) {
1341
- const { shapeRowTags } = getMetadataTables(metadataSchema);
1418
+ const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
1342
1419
  const db = drizzleOverPg(pg);
1343
1420
  for (const message of messages) {
1344
1421
  const data = message.value;
@@ -1366,9 +1443,10 @@ async function addShapeRowTags({
1366
1443
  metadataSchema,
1367
1444
  shapeTable,
1368
1445
  messages,
1369
- primaryKey: primaryKey2
1446
+ primaryKey: primaryKey2,
1447
+ sessionScoped = false
1370
1448
  }) {
1371
- const { shapeRowTags } = getMetadataTables(metadataSchema);
1449
+ const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
1372
1450
  const db = drizzleOverPg(pg);
1373
1451
  for (const message of messages) {
1374
1452
  const tags = message.headers.tags;
@@ -1385,9 +1463,10 @@ async function applyShapeMoveOut({
1385
1463
  shapeTable,
1386
1464
  target,
1387
1465
  patternSets,
1388
- debug
1466
+ debug,
1467
+ sessionScoped = false
1389
1468
  }) {
1390
- const { shapeRowTags } = getMetadataTables(metadataSchema);
1469
+ const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
1391
1470
  const db = drizzleOverPg(pg);
1392
1471
  const evictedPkJsons = new Set;
1393
1472
  for (const patterns of patternSets) {
@@ -1426,9 +1505,10 @@ async function applyShapeMoveOut({
1426
1505
  async function clearShapeTags({
1427
1506
  pg,
1428
1507
  metadataSchema,
1429
- shapeTable
1508
+ shapeTable,
1509
+ sessionScoped = false
1430
1510
  }) {
1431
- const { shapeRowTags } = getMetadataTables(metadataSchema);
1511
+ const { shapeRowTags } = pickMetadataTables(metadataSchema, sessionScoped);
1432
1512
  await drizzleOverPg(pg).delete(shapeRowTags).where(eq2(shapeRowTags.shape_table, shapeTable));
1433
1513
  }
1434
1514
 
@@ -1719,17 +1799,19 @@ function buildTableColumnSql(columns, primaryKeyColumns, localSchema) {
1719
1799
  ].join(`,
1720
1800
  `);
1721
1801
  }
1722
- function renderCreateTableSql(table) {
1802
+ function renderCreateTableSql(table, options = {}) {
1723
1803
  const config = getTableConfig4(table);
1804
+ const temp = options.temp === true;
1724
1805
  const schemaName = config.schema ?? "public";
1725
- const qualifiedTableName = qualifyIdentifier(schemaName, config.name);
1806
+ const tableRef = temp ? maybeQuoteIdentifier(config.name) : qualifyIdentifier(schemaName, config.name);
1726
1807
  const primaryKeyColumns = collectPgTablePrimaryKeyColumns(config);
1727
1808
  const columnSql = buildTableColumnSql(config.columns, primaryKeyColumns, schemaName);
1728
- const statements = [`CREATE TABLE IF NOT EXISTS ${qualifiedTableName} (
1809
+ const createKeyword = temp ? "CREATE TEMP TABLE" : "CREATE TABLE";
1810
+ const statements = [`${createKeyword} IF NOT EXISTS ${tableRef} (
1729
1811
  ${columnSql}
1730
1812
  );`];
1731
1813
  for (const index2 of config.indexes) {
1732
- statements.push(renderCreateIndexSql(qualifiedTableName, index2));
1814
+ statements.push(renderCreateIndexSql(tableRef, index2));
1733
1815
  }
1734
1816
  return statements;
1735
1817
  }
@@ -2244,6 +2326,7 @@ function resolveApplyTarget(registry, tableKey) {
2244
2326
  columnByName,
2245
2327
  propertyKeyByName,
2246
2328
  primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),
2329
+ applyMode: entry.applyMode,
2247
2330
  columnTypes: deriveSyncColumnTypes(entry),
2248
2331
  insertRenderCache: new Map
2249
2332
  };
@@ -4410,6 +4493,7 @@ async function startConfiguredSync(pg, input) {
4410
4493
  groupKey: group.groupKey,
4411
4494
  specs: group.specs,
4412
4495
  registry: input.registry,
4496
+ ...group.retention === "ephemeral" ? { sessionScoped: true } : {},
4413
4497
  ...bootStamp ? { bootStamp } : {},
4414
4498
  ...countsTowardBoot && input.dbReady ? { dbReady: input.dbReady } : {},
4415
4499
  ...input.shapeHeaders ? { headers: input.shapeHeaders } : {},
@@ -4507,6 +4591,7 @@ async function startGroupSync(pg, input) {
4507
4591
  key: input.groupKey,
4508
4592
  registry: input.registry,
4509
4593
  shapes,
4594
+ ...input.sessionScoped ? { sessionScoped: input.sessionScoped } : {},
4510
4595
  ...input.dbReady ? { dbReady: input.dbReady } : {},
4511
4596
  ...input.bootStamp ? { bootStamp: input.bootStamp } : {},
4512
4597
  ...input.onGroupInitialSync ? { onInitialSync: input.onGroupInitialSync } : {},
@@ -4857,9 +4942,10 @@ import { quoteIdentifier as quoteIdentifier6 } from "@pgxsinkit/contracts";
4857
4942
  async function getSubscriptionState({
4858
4943
  pg,
4859
4944
  metadataSchema,
4860
- subscriptionKey
4945
+ subscriptionKey,
4946
+ sessionScoped = false
4861
4947
  }) {
4862
- const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
4948
+ const { subscriptionsMetadata } = pickMetadataTables(metadataSchema, sessionScoped);
4863
4949
  const rows = await drizzleOverPg(pg).select().from(subscriptionsMetadata).where(eq6(subscriptionsMetadata.key, subscriptionKey));
4864
4950
  if (rows.length === 0) {
4865
4951
  return null;
@@ -4892,12 +4978,13 @@ async function updateSubscriptionState({
4892
4978
  subscriptionKey,
4893
4979
  shapeMetadata,
4894
4980
  lastLsn,
4895
- debug
4981
+ debug,
4982
+ sessionScoped = false
4896
4983
  }) {
4897
4984
  if (debug) {
4898
4985
  console.log("updating subscription state", subscriptionKey, shapeMetadata, lastLsn);
4899
4986
  }
4900
- const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
4987
+ const { subscriptionsMetadata } = pickMetadataTables(metadataSchema, sessionScoped);
4901
4988
  const lastLsnText = lastLsn.toString();
4902
4989
  await drizzleOverPg(pg).insert(subscriptionsMetadata).values({ key: subscriptionKey, shape_metadata: shapeMetadata, last_lsn: lastLsnText }).onConflictDoUpdate({
4903
4990
  target: subscriptionsMetadata.key,
@@ -4905,19 +4992,25 @@ async function updateSubscriptionState({
4905
4992
  });
4906
4993
  }
4907
4994
  async function deleteSubscriptionState({ pg, metadataSchema, subscriptionKey }) {
4995
+ const db = drizzleOverPg(pg);
4908
4996
  const { subscriptionsMetadata } = getMetadataTables(metadataSchema);
4909
- await drizzleOverPg(pg).delete(subscriptionsMetadata).where(eq6(subscriptionsMetadata.key, subscriptionKey));
4997
+ const session = getSessionMetadataTables();
4998
+ await db.delete(subscriptionsMetadata).where(eq6(subscriptionsMetadata.key, subscriptionKey));
4999
+ await db.delete(session.subscriptionsMetadata).where(eq6(session.subscriptionsMetadata.key, subscriptionKey));
4910
5000
  }
4911
5001
  async function migrateSubscriptionMetadataTables({
4912
5002
  pg,
4913
5003
  metadataSchema
4914
5004
  }) {
4915
5005
  const { subscriptionsMetadata, shapeRowTags } = getMetadataTables(metadataSchema);
5006
+ const session = getSessionMetadataTables();
4916
5007
  const statements = [
4917
5008
  `SET ${metadataSchema}.syncing = false;`,
4918
5009
  `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier6(metadataSchema)};`,
4919
5010
  ...renderCreateTableSql(subscriptionsMetadata),
4920
- ...renderCreateTableSql(shapeRowTags)
5011
+ ...renderCreateTableSql(shapeRowTags),
5012
+ ...renderCreateTableSql(session.subscriptionsMetadata, { temp: true }),
5013
+ ...renderCreateTableSql(session.shapeRowTags, { temp: true })
4921
5014
  ];
4922
5015
  await pg.exec(statements.join(`
4923
5016
  `));
@@ -4977,6 +5070,7 @@ async function createSyncEngine(pg, options) {
4977
5070
  key,
4978
5071
  registry,
4979
5072
  shapes,
5073
+ sessionScoped = false,
4980
5074
  initialInsertMethod,
4981
5075
  onInitialSync,
4982
5076
  onError,
@@ -5018,7 +5112,8 @@ async function createSyncEngine(pg, options) {
5018
5112
  subState = await getSubscriptionState({
5019
5113
  pg,
5020
5114
  metadataSchema,
5021
- subscriptionKey: key
5115
+ subscriptionKey: key,
5116
+ sessionScoped
5022
5117
  });
5023
5118
  if (debug && subState) {
5024
5119
  console.log("resuming from subscription state", subState);
@@ -5124,7 +5219,7 @@ async function createSyncEngine(pg, options) {
5124
5219
  } else {
5125
5220
  await drizzleOverPg(tx).execute(sql6`TRUNCATE ${target.table}`);
5126
5221
  }
5127
- await clearShapeTags({ pg: tx, metadataSchema, shapeTable });
5222
+ await clearShapeTags({ pg: tx, metadataSchema, shapeTable, sessionScoped });
5128
5223
  }
5129
5224
  const moveInMessages = moveInsToCommit.get(shapeName) ?? [];
5130
5225
  if (moveInMessages.length > 0) {
@@ -5133,7 +5228,8 @@ async function createSyncEngine(pg, options) {
5133
5228
  metadataSchema,
5134
5229
  shapeTable,
5135
5230
  messages: moveInMessages,
5136
- primaryKey: target.primaryKey
5231
+ primaryKey: target.primaryKey,
5232
+ sessionScoped
5137
5233
  });
5138
5234
  }
5139
5235
  await applyShapeTagSync({
@@ -5141,7 +5237,8 @@ async function createSyncEngine(pg, options) {
5141
5237
  metadataSchema,
5142
5238
  shapeTable,
5143
5239
  messages: initialMessages,
5144
- primaryKey: target.primaryKey
5240
+ primaryKey: target.primaryKey,
5241
+ sessionScoped
5145
5242
  });
5146
5243
  if (moveInMessages.length > 0) {
5147
5244
  await applyUpsertsToTable({
@@ -5168,12 +5265,22 @@ async function createSyncEngine(pg, options) {
5168
5265
  }
5169
5266
  messages = remainingMessages;
5170
5267
  if (initialInserts.length > 0) {
5171
- await insertMethods[shapeMethod]({
5172
- pg: tx,
5173
- target,
5174
- messages: initialInserts,
5175
- debug
5176
- });
5268
+ if (target.applyMode === "upsert") {
5269
+ const applyInitialUpserts = shapeMethod === "insert" ? applyUpsertsToTable : applyUpsertsToTableWithJson;
5270
+ await applyInitialUpserts({
5271
+ pg: tx,
5272
+ target,
5273
+ messages: initialInserts,
5274
+ debug
5275
+ });
5276
+ } else {
5277
+ await insertMethods[shapeMethod]({
5278
+ pg: tx,
5279
+ target,
5280
+ messages: initialInserts,
5281
+ debug
5282
+ });
5283
+ }
5177
5284
  useInsert.set(shapeName, true);
5178
5285
  }
5179
5286
  }
@@ -5188,7 +5295,7 @@ async function createSyncEngine(pg, options) {
5188
5295
  });
5189
5296
  }
5190
5297
  if (folded.inserts.length > 0) {
5191
- if (snapshotModeAtPeek.get(shapeName)) {
5298
+ if (snapshotModeAtPeek.get(shapeName) || target.applyMode === "upsert") {
5192
5299
  await applyUpsertsToTable({
5193
5300
  pg: tx,
5194
5301
  target,
@@ -5221,7 +5328,8 @@ async function createSyncEngine(pg, options) {
5221
5328
  shapeTable,
5222
5329
  target,
5223
5330
  patternSets,
5224
- debug
5331
+ debug,
5332
+ sessionScoped
5225
5333
  });
5226
5334
  }
5227
5335
  }
@@ -5230,6 +5338,7 @@ async function createSyncEngine(pg, options) {
5230
5338
  pg: tx,
5231
5339
  metadataSchema,
5232
5340
  subscriptionKey: key,
5341
+ sessionScoped,
5233
5342
  shapeMetadata: Object.fromEntries(Object.keys(shapes).map((shapeName) => {
5234
5343
  const stream = getShapeStream(shapeName);
5235
5344
  return [
@@ -5514,6 +5623,7 @@ async function createSyncEngine(pg, options) {
5514
5623
  }
5515
5624
  },
5516
5625
  key: options2.shapeKey,
5626
+ ...options2.sessionScoped ? { sessionScoped: options2.sessionScoped } : {},
5517
5627
  onInitialSync: options2.onInitialSync,
5518
5628
  onError: options2.onError,
5519
5629
  onSyncError: options2.onSyncError,
@@ -5535,6 +5645,7 @@ async function createSyncEngine(pg, options) {
5535
5645
  };
5536
5646
  };
5537
5647
  const deleteSubscription = async (key) => {
5648
+ await initMetadataTables();
5538
5649
  await deleteSubscriptionState({
5539
5650
  pg,
5540
5651
  metadataSchema,
@@ -5717,6 +5828,21 @@ function fingerprintLiveQuery(materialSql, params, pkColumns) {
5717
5828
  return { key, digest: shortDigest(key) };
5718
5829
  }
5719
5830
 
5831
+ // packages/client/src/worker/live-query-params-guard.ts
5832
+ function assertLiveQueryParamsSafe(sql7, params) {
5833
+ if (params.length === 0)
5834
+ return;
5835
+ const numbers = [];
5836
+ for (const match of sql7.matchAll(/\$(\d+)/g))
5837
+ numbers.push(Number(match[1]));
5838
+ const expected = params.length;
5839
+ const safe = numbers.length === expected && numbers.every((n, i) => n === i + 1);
5840
+ if (safe)
5841
+ return;
5842
+ const found = numbers.length === 0 ? "(none)" : numbers.map((n) => `$${n}`).join(", ");
5843
+ throw new Error(`[pgxsinkit] live query hits PGlite bug #1055 ` + `(https://github.com/electric-sql/pglite/issues/1055): its live-query param inlining binds $N ` + `placeholders SEQUENTIALLY (in textual order), not positionally, so anything but a strictly ` + `ascending $1..$n each used once silently mis-binds or throws. Found placeholders [${found}] for ` + `${expected} param${expected === 1 ? "" : "s"}, expected exactly [$1..$${expected}]. Renumber the ` + `placeholders to a strictly sequential $1..$${expected}, each used once \u2014 or pass the query as a ` + `Drizzle builder, which always compiles to that shape.`);
5844
+ }
5845
+
5720
5846
  // packages/client/src/worker/live-query-manager.ts
5721
5847
  var MAX_KEEP_ALIVE_MS = 2147483647;
5722
5848
  function validateLiveQueryPolicy(policy) {
@@ -5904,6 +6030,7 @@ function createLiveQueryManager(deps) {
5904
6030
  if (hint !== undefined && hint > MAX_KEEP_ALIVE_MS) {
5905
6031
  throw new TypeError(`[pgxsinkit] keepAliveMs must be <= ${MAX_KEEP_ALIVE_MS} ms (the platform setTimeout ceiling; got ${hint})`);
5906
6032
  }
6033
+ assertLiveQueryParamsSafe(spec.materialSql, spec.params);
5907
6034
  const keepAliveMs = hint ?? 0;
5908
6035
  const scope = opts?.scope;
5909
6036
  let markSetupDone;
@@ -6410,10 +6537,22 @@ async function attachSyncClient(options) {
6410
6537
  ...hydrated ? { hydrated } : {}
6411
6538
  };
6412
6539
  };
6413
- const { drizzle: drizzle5, views } = buildRegistryReadHandles(options.registry);
6414
6540
  const notSupported = (name) => () => {
6415
- throw new Error(`[pgxsinkit] ${name} is not available on a worker-attached client (ADR-0032 S2). Use the live-rows hooks / subscribeLiveRows for reads, the write API for mutations.`);
6541
+ throw new Error(`[pgxsinkit] ${name} is not available on a worker-attached client: the tab holds no local PGlite. ` + `Direct store access (client.pglite) and store-lifecycle ops (destroy/dropReadCache) have no tab-local ` + `implementation. One-shot Drizzle reads (query/queryRow/queryRaw/queryRawRow), lazy activation ` + `(ensureSynced), and the write API ARE proxied to the worker.`);
6542
+ };
6543
+ const noBridgeTransaction = () => {
6544
+ throw new Error("[pgxsinkit] client.drizzle.transaction() is not available on a worker-attached client: a read " + "transaction needs a local PGlite the tab does not have. Use one-shot reads (client.query) instead.");
6416
6545
  };
6546
+ const guardedQueryArgs = (sql7, params, rowMode, use) => {
6547
+ const options2 = rowMode ? { rowMode } : {};
6548
+ return use ? [sql7, params, options2, use] : [sql7, params, options2];
6549
+ };
6550
+ const makeBridgeExecutor = (use) => ({
6551
+ query: (sql7, params, options2) => rpc("guardedQuery", guardedQueryArgs(sql7, params, options2?.rowMode, use)),
6552
+ transaction: noBridgeTransaction
6553
+ });
6554
+ const { drizzle: drizzle5, views, drizzleFor } = buildRegistryReadHandles(options.registry, makeBridgeExecutor());
6555
+ const bridgeReadDrizzle = (use) => drizzleFor(makeBridgeExecutor(use));
6417
6556
  const groupKeyForTable = (table) => {
6418
6557
  const entry = options.registry[table];
6419
6558
  return entry?.consistencyGroup ?? entry?.shape?.shapeKey;
@@ -6421,9 +6560,7 @@ async function attachSyncClient(options) {
6421
6560
  const client = {
6422
6561
  drizzle: drizzle5,
6423
6562
  views,
6424
- pglite: new Proxy({}, {
6425
- get: notSupported("client.pglite")
6426
- }),
6563
+ pglite: undefined,
6427
6564
  tables: Object.fromEntries(Object.keys(options.registry).map((tableKey) => [
6428
6565
  tableKey,
6429
6566
  {
@@ -6454,6 +6591,7 @@ async function attachSyncClient(options) {
6454
6591
  readMutationDetails: (table) => rpc("readMutationDetails", [table]),
6455
6592
  rawQuery: (sql7, params, options2) => rpc("rawQuery", [sql7, params, options2]),
6456
6593
  rawExec: (sql7, options2) => rpc("rawExec", [sql7, options2]),
6594
+ guardedRawQuery: (sql7, params, options2, use) => rpc("guardedQuery", guardedQueryArgs(sql7, params, options2?.rowMode, use)),
6457
6595
  mutate: {
6458
6596
  create: (table, input) => rpc("create", [table, input]),
6459
6597
  update: (table, entityKey, patch) => rpc("update", [table, entityKey, patch]),
@@ -6468,12 +6606,20 @@ async function attachSyncClient(options) {
6468
6606
  subscribeLiveRows,
6469
6607
  query: (sql7, params) => rpc("rawQuery", [sql7, params])
6470
6608
  }),
6471
- query: notSupported("client.query"),
6472
- queryRow: notSupported("client.queryRow"),
6473
- queryRaw: notSupported("client.queryRaw"),
6474
- queryRawRow: notSupported("client.queryRawRow"),
6475
- ensureSynced: notSupported("client.ensureSynced"),
6476
- isSynced: notSupported("client.isSynced"),
6609
+ query: (build) => Promise.resolve(build(client)),
6610
+ queryRow: async (build) => {
6611
+ const rows = await build(client);
6612
+ return rows[0] ?? null;
6613
+ },
6614
+ queryRaw: ({ build, use }) => Promise.resolve(build({ ...client, drizzle: bridgeReadDrizzle(use) })),
6615
+ queryRawRow: async ({ build, use }) => {
6616
+ const rows = await build({ ...client, drizzle: bridgeReadDrizzle(use) });
6617
+ return rows[0] ?? null;
6618
+ },
6619
+ ensureSynced: (keys) => rpc("ensureSynced", [keys]),
6620
+ isSynced: () => {
6621
+ throw new Error("[pgxsinkit] client.isSynced is not available on a worker-attached client: it is a SYNCHRONOUS " + "activation-STARTED peek (in-process: isTableStarted), but the tab caches only per-group CATCH-UP " + "readiness (status.groups / groupReady) \u2014 an activated-but-not-caught-up group reads as not-ready \u2014 " + "so a faithful synchronous answer cannot be derived, and a synchronous method cannot be an RPC. Use " + "client.groupReady(table) for catch-up completion, and client.ensureSynced([...]) to activate a lazy relation.");
6622
+ },
6477
6623
  desync: (key) => rpc("desync", [key]),
6478
6624
  discardEphemeral: (key) => rpc("discardEphemeral", [key]),
6479
6625
  prepareQuery: async () => ({ lazyTables: [] }),
@@ -6551,6 +6697,11 @@ async function attachSyncClient(options) {
6551
6697
  postBridgeMessage(port, codec, "set-online", { online });
6552
6698
  }
6553
6699
  };
6700
+ Object.defineProperty(client, "pglite", {
6701
+ get: notSupported("client.pglite"),
6702
+ enumerable: false,
6703
+ configurable: true
6704
+ });
6554
6705
  return client;
6555
6706
  }
6556
6707
  function provisionSyncWorker(options) {
@@ -6599,6 +6750,9 @@ function rebuildError(error) {
6599
6750
  }
6600
6751
  return rebuilt;
6601
6752
  }
6753
+ // packages/client/src/worker/define-sync-worker.ts
6754
+ import { types as types2 } from "@electric-sql/pglite";
6755
+
6602
6756
  // packages/client/src/worker/token-cache.ts
6603
6757
  function createWorkerTokenCache(options) {
6604
6758
  const now2 = options.now ?? (() => Date.now());
@@ -6653,12 +6807,27 @@ function createWorkerTokenCache(options) {
6653
6807
  }
6654
6808
 
6655
6809
  // packages/client/src/worker/define-sync-worker.ts
6810
+ var identityParser = (value) => value;
6811
+ var DRIZZLE_PGLITE_IDENTITY_PARSERS = {
6812
+ [types2.TIMESTAMP]: identityParser,
6813
+ [types2.TIMESTAMPTZ]: identityParser,
6814
+ [types2.INTERVAL]: identityParser,
6815
+ [types2.DATE]: identityParser,
6816
+ 1231: identityParser,
6817
+ 1115: identityParser,
6818
+ 1185: identityParser,
6819
+ 1187: identityParser,
6820
+ 1182: identityParser
6821
+ };
6656
6822
  function defineSyncWorker(options) {
6657
6823
  validateLiveQueryPolicy(options.liveQueries);
6658
6824
  const codec = options.codec ?? identityCodec;
6659
6825
  const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30000;
6660
6826
  const convergenceIntervalMs = options.convergenceIntervalMs ?? 15000;
6661
- const createPglite = options.createPglite ?? ((storePath, backendOverride) => createClientPGlite(storePath, backendOverride ? { backendOverride } : undefined));
6827
+ const createPglite = options.createPglite ?? ((storePath, backendOverride) => createClientPGlite(storePath, {
6828
+ ...backendOverride ? { backendOverride } : {},
6829
+ ...options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {}
6830
+ }));
6662
6831
  const workerTestMarker = readTestStoreMarker(options);
6663
6832
  const ports = new Set;
6664
6833
  const liveSubs = new Map;
@@ -6807,6 +6976,9 @@ function defineSyncWorker(options) {
6807
6976
  ...provisionStamp ? { provisionStamp } : {},
6808
6977
  ...precreatedPglite ? { precreatedPglite } : {},
6809
6978
  ...options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {},
6979
+ ...options.prepareLocalDbBeforeSchema ? { prepareLocalDbBeforeSchema: options.prepareLocalDbBeforeSchema } : {},
6980
+ ...options.prepareLocalDb ? { prepareLocalDb: options.prepareLocalDb } : {},
6981
+ ...options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {},
6810
6982
  ...attach.config?.freshStore === true ? { freshStore: true } : {},
6811
6983
  getAuthToken: getWorkerAuthToken,
6812
6984
  autoSync: gatedTrigger,
@@ -6819,13 +6991,21 @@ function defineSyncWorker(options) {
6819
6991
  onQuarantine: (details) => broadcastEvent({ kind: "quarantine", details }),
6820
6992
  onReject: (details) => broadcastEvent({ kind: "reject", details }),
6821
6993
  onSchemaChange: (event) => broadcastEvent({ kind: "schema-change", event }),
6822
- onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: error.message }),
6994
+ onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: describeErrorChain(error) }),
6823
6995
  onBootReport: (report) => broadcastEvent({ kind: "boot-report", report })
6824
6996
  });
6825
6997
  return bootPromise;
6826
6998
  };
6827
6999
  const whenBooted = () => bootedPromise;
6828
7000
  const dispatchRpc = async (active, op, args) => {
7001
+ const runGuardedQueryRpc = () => {
7002
+ const [sql7, params, options2, use] = args;
7003
+ const queryOptions = {
7004
+ ...options2?.rowMode ? { rowMode: options2.rowMode } : {},
7005
+ parsers: DRIZZLE_PGLITE_IDENTITY_PARSERS
7006
+ };
7007
+ return active.guardedRawQuery(sql7, params, queryOptions, use);
7008
+ };
6829
7009
  switch (op) {
6830
7010
  case "create":
6831
7011
  return active.mutate.create(args[0], args[1]);
@@ -6869,6 +7049,8 @@ function defineSyncWorker(options) {
6869
7049
  return active.desync(args[0]);
6870
7050
  case "discardEphemeral":
6871
7051
  return active.discardEphemeral(args[0]);
7052
+ case "ensureSynced":
7053
+ return active.ensureSynced(args[0]);
6872
7054
  case "readMutationDetails":
6873
7055
  return active.readMutationDetails(args[0]);
6874
7056
  case "diagnostics":
@@ -6877,6 +7059,8 @@ function defineSyncWorker(options) {
6877
7059
  return active.rawQuery(args[0], args[1], args[2]);
6878
7060
  case "rawExec":
6879
7061
  return active.rawExec(args[0], args[1]);
7062
+ case "guardedQuery":
7063
+ return runGuardedQueryRpc();
6880
7064
  case "bootReport":
6881
7065
  return active.bootReport();
6882
7066
  case "liveQueryDiagnostics":
@@ -7216,13 +7400,15 @@ async function createClientPGlite(store, options) {
7216
7400
  const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => {
7217
7401
  return;
7218
7402
  }) : undefined;
7403
+ const relaxedDurability = options?.relaxedDurability ?? true;
7219
7404
  return await timeAsync("boot pglite.create", () => PGlite2.create(dataDir, {
7220
7405
  ...bootAssets ?? {},
7406
+ relaxedDurability,
7221
7407
  ...options?.restoreFrom ? { loadDataDir: options.restoreFrom } : {},
7222
7408
  extensions: {
7223
7409
  live
7224
7410
  }
7225
- }), { dataDir: dataDirScheme });
7411
+ }), { dataDir: dataDirScheme, relaxedDurability });
7226
7412
  }
7227
7413
  function replAdapter(client) {
7228
7414
  return {
@@ -7265,13 +7451,7 @@ async function createSyncClient(options) {
7265
7451
  if (restoreBoot && (options.pgliteInstance || options.precreatedPglite)) {
7266
7452
  throw new Error("createSyncClient: `restoreFrom` is mutually exclusive with `pgliteInstance` / `precreatedPglite` \u2014 restore boots a brand-new store from the backup (a create-time `loadDataDir` seed), so it cannot adopt a caller-owned instance. Drop the instance option, or drop `restoreFrom` (ADR-0035).");
7267
7453
  }
7268
- if (restoreBoot && (options.syncEnabled === true || options.autoSync != null)) {
7269
- syncDebug("boot restore forces offline \u2014 ignoring the online sync option for this restore boot", {
7270
- syncEnabled: options.syncEnabled === true,
7271
- autoSync: options.autoSync != null
7272
- });
7273
- }
7274
- const syncEnabled = restoreBoot ? false : options.syncEnabled ?? true;
7454
+ let syncEnabled = restoreBoot ? false : options.syncEnabled ?? true;
7275
7455
  const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;
7276
7456
  const storeKind = restoreBoot ? "restored" : options.freshStore === true ? "fresh" : "warm";
7277
7457
  const bootReportBuilder = createBootReportBuilder({
@@ -7294,6 +7474,7 @@ async function createSyncClient(options) {
7294
7474
  const createClientOptions = {
7295
7475
  ...options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {},
7296
7476
  ...backendOverride ? { backendOverride } : {},
7477
+ ...options.relaxedDurability != null ? { relaxedDurability: options.relaxedDurability } : {},
7297
7478
  ...restoreBoot ? { restoreFrom: options.restoreFrom } : {}
7298
7479
  };
7299
7480
  const fallbackStorePath = options.storePath ?? "pgxsinkit-overlay-v1";
@@ -7383,7 +7564,7 @@ async function createSyncClient(options) {
7383
7564
  onSyncError: (error) => {
7384
7565
  status.phase = "degraded";
7385
7566
  degradedReason = "commit";
7386
- status.lastError = error.message;
7567
+ status.lastError = describeErrorChain(error);
7387
7568
  options.onStatusChange?.(status);
7388
7569
  options.onSyncError?.(error);
7389
7570
  },
@@ -7394,7 +7575,7 @@ async function createSyncClient(options) {
7394
7575
  return;
7395
7576
  status.phase = "degraded";
7396
7577
  degradedReason = "stream";
7397
- status.lastError = error.message;
7578
+ status.lastError = describeErrorChain(error);
7398
7579
  options.onStatusChange?.(status);
7399
7580
  },
7400
7581
  onSyncActivity: () => {
@@ -7481,6 +7662,13 @@ async function createSyncClient(options) {
7481
7662
  };
7482
7663
  if (restoreBoot) {
7483
7664
  await runBootRecoveryStage();
7665
+ const recoveredQuarantined = (await mutationRuntime.readMutationStats()).quarantinedCount;
7666
+ if (recoveredQuarantined === 0 && options.syncEnabled !== false) {
7667
+ syncEnabled = options.syncEnabled ?? true;
7668
+ syncDebug("boot restore comes online \u2014 recovered journal was clean (nothing to quarantine)");
7669
+ } else if (recoveredQuarantined > 0) {
7670
+ syncDebug("boot restore stays offline \u2014 recovered journal mutations were quarantined; release/discard them and a subsequent normal boot brings sync online", { quarantinedCount: recoveredQuarantined, syncEnabledOption: options.syncEnabled ?? null });
7671
+ }
7484
7672
  await runReconcileStage();
7485
7673
  } else {
7486
7674
  await runReconcileStage();
@@ -7560,7 +7748,7 @@ async function createSyncClient(options) {
7560
7748
  }
7561
7749
  resolveSyncWired();
7562
7750
  };
7563
- if (options.autoSync && !restoreBoot) {
7751
+ if (options.autoSync && (!restoreBoot || syncEnabled)) {
7564
7752
  convergenceDriver = createConvergenceDriver({
7565
7753
  client: {
7566
7754
  flush: () => mutationRuntime.flush(),
@@ -7821,12 +8009,19 @@ async function createSyncClient(options) {
7821
8009
  });
7822
8010
  return { lazyTables };
7823
8011
  };
7824
- const runGuardedQuery = async (build, use) => {
8012
+ const gateAndGuardRead = async (sql7, use) => {
7825
8013
  await localReadReady;
8014
+ await prepareQuery({ sql: sql7, ...use ? { use } : {} });
8015
+ };
8016
+ const runGuardedQuery = async (build, use) => {
7826
8017
  const builder = build(client);
7827
- await prepareQuery({ sql: builder.toSQL().sql, ...use ? { use } : {} });
8018
+ await gateAndGuardRead(builder.toSQL().sql, use);
7828
8019
  return builder;
7829
8020
  };
8021
+ const guardedRawQuery = async (sql7, params, options2, use) => {
8022
+ await gateAndGuardRead(sql7, use);
8023
+ return pglite.query(sql7, params, options2);
8024
+ };
7830
8025
  const liveManager = createLiveQueryManager({
7831
8026
  live: pglite.live,
7832
8027
  ...options.liveQueries ? { policy: options.liveQueries } : {}
@@ -7922,6 +8117,7 @@ async function createSyncClient(options) {
7922
8117
  mutations: undefined,
7923
8118
  rawQuery: (sql7, params, options2) => pglite.query(sql7, params, options2),
7924
8119
  rawExec: (sql7, options2) => pglite.exec(sql7, options2),
8120
+ guardedRawQuery,
7925
8121
  query: (build) => runGuardedQuery(build),
7926
8122
  queryRow: async (build) => {
7927
8123
  const rows = await runGuardedQuery(build);
@@ -8037,7 +8233,7 @@ async function createSyncClient(options) {
8037
8233
  }
8038
8234
  pendingActivations = null;
8039
8235
  status.phase = "degraded";
8040
- status.lastError = error instanceof Error ? error.message : String(error);
8236
+ status.lastError = describeErrorChain(error);
8041
8237
  options.onStatusChange?.(status);
8042
8238
  rejectWriteReady(error);
8043
8239
  rejectReady(error);
@@ -8072,13 +8268,19 @@ function buildSchema(registry) {
8072
8268
  function buildViews(registry) {
8073
8269
  return Object.fromEntries(Object.entries(registry).flatMap(([key, entry]) => entry.view != null ? [[key, entry.view]] : []));
8074
8270
  }
8075
- function buildRegistryReadHandles(registry) {
8076
- const stubClient = {};
8271
+ function buildRegistryReadHandles(registry, client = {}) {
8272
+ const drizzleFor = buildRegistryDrizzleFactory(registry);
8077
8273
  return {
8078
- drizzle: createDrizzleDatabase(stubClient, buildSchema(registry)),
8079
- views: buildViews(registry)
8274
+ drizzle: drizzleFor(client),
8275
+ views: buildViews(registry),
8276
+ drizzleFor
8080
8277
  };
8081
8278
  }
8279
+ function buildRegistryDrizzleFactory(registry) {
8280
+ const relations = defineRelations(buildSchema(registry));
8281
+ const createDatabase = drizzle5;
8282
+ return (client) => createDatabase({ client, relations });
8283
+ }
8082
8284
  function buildSyncConfigFromRegistry(registry, electricUrl) {
8083
8285
  return {
8084
8286
  electricUrl,
@@ -8166,4 +8368,4 @@ export {
8166
8368
  BRIDGE_CHANNEL
8167
8369
  };
8168
8370
 
8169
- //# debugId=804640A8064D585A64756E2164756E21
8371
+ //# debugId=AF8FCBA60459DB4564756E2164756E21