@pgxsinkit/client 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -16,131 +16,6 @@ var __export = (target, all) => {
16
16
  var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
17
  var __require = import.meta.require;
18
18
 
19
- // packages/client/src/store-lifecycle.ts
20
- async function runCommitmentBarrier(effects) {
21
- await effects.strictSyncReturns();
22
- await effects.publishSentinel();
23
- await effects.setPhase("opfs-committed");
24
- }
25
- async function beginFreshCandidate(effects) {
26
- await effects.writeCandidateRecord();
27
- await effects.createStoreDirectory();
28
- }
29
- async function resumeDeletion(effects) {
30
- await effects.deleteSentinel();
31
- await effects.deleteBackendStore();
32
- await effects.deleteMetaRecord();
33
- }
34
- async function runDestruction(effects) {
35
- await effects.setPhase("deleting");
36
- await resumeDeletion(effects);
37
- }
38
- function classifyAdoptionRecovery(obs) {
39
- return obs.sentinelPresent ? { action: "complete-adoption" } : { action: "teardown-and-restart" };
40
- }
41
- async function completeAdoption(effects) {
42
- await effects.setPhase("opfs-committed");
43
- await effects.deleteIdbPredecessor();
44
- }
45
- function journalOwesNothing(counts) {
46
- return counts.pending + counts.sending + counts.failed + counts.quarantined + counts.conflicted === 0;
47
- }
48
-
49
- // packages/client/src/adoption.ts
50
- async function awaitAdoptionGate(ready, deadlineMs) {
51
- let timer;
52
- const deadline = new Promise((_, reject) => {
53
- timer = setTimeout(() => reject(new Error("[pgxsinkit] adoption gate unmet: the eager Consistency groups did not complete their initial " + `catch-up within ${deadlineMs}ms (offline, unauthorized, or the server was unreachable). The idb ` + "store stays authoritative.")), deadlineMs);
54
- });
55
- try {
56
- await Promise.race([ready, deadline]);
57
- } finally {
58
- if (timer !== undefined)
59
- clearTimeout(timer);
60
- }
61
- }
62
- function buildAdoptionEffects(options) {
63
- let candidate;
64
- return {
65
- bootIdbPreExpose: () => options.readIdbJournal(),
66
- async strictSyncAndCloseIdb() {},
67
- setPhase: (phase) => options.setPhase(phase),
68
- async buildCandidateThroughGate() {
69
- candidate = await options.buildCandidate();
70
- await awaitAdoptionGate(candidate.ready, options.gateDeadlineMs ?? DEFAULT_ADOPTION_GATE_DEADLINE_MS);
71
- },
72
- async commitCandidate() {
73
- const active = candidate;
74
- if (active === undefined)
75
- throw new Error("[pgxsinkit] adoption: commit called before the candidate was built");
76
- await runCommitmentBarrier({
77
- strictSyncReturns: () => active.strictSync(),
78
- publishSentinel: () => options.publishSentinel(),
79
- setPhase: (phase) => options.setPhase(phase)
80
- });
81
- await active.close().catch(() => {
82
- return;
83
- });
84
- candidate = undefined;
85
- },
86
- deleteIdbPredecessor: () => options.deleteIdbPredecessor(),
87
- async teardownCandidate() {
88
- if (candidate !== undefined) {
89
- await candidate.close().catch(() => {
90
- return;
91
- });
92
- candidate = undefined;
93
- }
94
- await options.deleteSentinel();
95
- await options.deleteStoreDirectory();
96
- }
97
- };
98
- }
99
- function errorText(error) {
100
- return error instanceof Error ? error.message : String(error);
101
- }
102
- async function runTransition(effects) {
103
- const counts = await effects.bootIdbPreExpose();
104
- if (!journalOwesNothing(counts))
105
- return { adopted: false, reason: "journal-owed" };
106
- await effects.strictSyncAndCloseIdb();
107
- await effects.setPhase("adopting");
108
- try {
109
- await effects.buildCandidateThroughGate();
110
- } catch (error) {
111
- await effects.teardownCandidate();
112
- await effects.setPhase("idb-authoritative");
113
- return { adopted: false, reason: "gate-failed", error: errorText(error) };
114
- }
115
- try {
116
- await effects.commitCandidate();
117
- } catch (error) {
118
- await effects.teardownCandidate();
119
- await effects.setPhase("idb-authoritative");
120
- return { adopted: false, reason: "barrier-failed", error: errorText(error) };
121
- }
122
- try {
123
- await effects.deleteIdbPredecessor();
124
- } catch (error) {
125
- return { adopted: true, predecessorCleanupPending: errorText(error) };
126
- }
127
- return { adopted: true };
128
- }
129
- function runAdoptionTransition(declaration, effects) {
130
- if (declaration !== "server-reconstructible") {
131
- return Promise.resolve({ adopted: false, reason: "not-declared" });
132
- }
133
- return runTransition(effects);
134
- }
135
- function runManualAdoption(effects) {
136
- return runTransition(effects);
137
- }
138
- function adoptionEligible(declaration, verdict, hasOpfsSyncAccess) {
139
- return declaration === "server-reconstructible" && hasOpfsSyncAccess && verdict.action === "boot-idb-authoritative";
140
- }
141
- var DEFAULT_ADOPTION_GATE_DEADLINE_MS = 30000;
142
- var init_adoption = () => {};
143
-
144
19
  // packages/client/src/debug.ts
145
20
  function setSyncDebugSink(sink) {
146
21
  syncDebugSink = sink;
@@ -4971,6 +4846,26 @@ var init_shape_sync = __esm(() => {
4971
4846
  init_sync_auth();
4972
4847
  });
4973
4848
 
4849
+ // packages/client/src/store-lifecycle.ts
4850
+ async function runCommitmentBarrier(effects) {
4851
+ await effects.strictSyncReturns();
4852
+ await effects.publishSentinel();
4853
+ await effects.setPhase("opfs-committed");
4854
+ }
4855
+ async function beginFreshCandidate(effects) {
4856
+ await effects.writeCandidateRecord();
4857
+ await effects.createStoreDirectory();
4858
+ }
4859
+ async function resumeDeletion(effects) {
4860
+ await effects.deleteSentinel();
4861
+ await effects.deleteBackendStore();
4862
+ await effects.deleteMetaRecord();
4863
+ }
4864
+ async function runDestruction(effects) {
4865
+ await effects.setPhase("deleting");
4866
+ await resumeDeletion(effects);
4867
+ }
4868
+
4974
4869
  // packages/client/src/store-meta.ts
4975
4870
  var exports_store_meta = {};
4976
4871
  __export(exports_store_meta, {
@@ -4990,8 +4885,6 @@ function classifyStoreBoot(obs) {
4990
4885
  switch (record.phase) {
4991
4886
  case "deleting":
4992
4887
  return { action: "resume-deletion" };
4993
- case "adopting":
4994
- return { action: "adoption-recovery" };
4995
4888
  case "opfs-committed":
4996
4889
  return { action: "open-committed" };
4997
4890
  case "opfs-candidate":
@@ -5181,7 +5074,6 @@ var init_store_meta = __esm(() => {
5181
5074
  VALID_PHASES = new Set([
5182
5075
  "idb-authoritative",
5183
5076
  "opfs-candidate",
5184
- "adopting",
5185
5077
  "opfs-committed",
5186
5078
  "deleting"
5187
5079
  ]);
@@ -5232,17 +5124,34 @@ function resolveHasIndexedDb(meta) {
5232
5124
  return meta.indexedDB != null;
5233
5125
  return typeof globalThis.indexedDB !== "undefined";
5234
5126
  }
5235
- async function recoverDeniedBootDeletion(storePath, deps) {
5127
+ function committedStoreUnreachableFromWire(detail) {
5128
+ if (typeof detail !== "object" || detail === null)
5129
+ return;
5130
+ const candidate = detail;
5131
+ if (candidate.code !== COMMITTED_STORE_UNREACHABLE_CODE)
5132
+ return;
5133
+ if (typeof candidate.storePath !== "string")
5134
+ return;
5135
+ return new CommittedStoreUnreachableError(candidate.storePath);
5136
+ }
5137
+ async function resolveDeniedBootAuthority(storePath, deps) {
5236
5138
  const meta = deps?.meta;
5237
5139
  const record = await readStoreMetaRecord(storePath, meta);
5238
- if (record === META_STORE_UNAVAILABLE || record?.phase !== "deleting")
5140
+ if (record === META_STORE_UNAVAILABLE)
5141
+ return false;
5142
+ const phase = record?.phase;
5143
+ if (phase === "opfs-committed")
5144
+ throw new CommittedStoreUnreachableError(storePath);
5145
+ if (phase !== "deleting" && phase !== "opfs-candidate")
5239
5146
  return false;
5240
5147
  const effects = createOpfsEffects(storePath, deps?.opfs);
5241
5148
  if (await effects.observeCommitmentNamespace() === "unobservable") {
5242
- throw new Error(`[pgxsinkit] cannot resume deletion for ${JSON.stringify(storePath)}: the OPFS commitment namespace is ` + "unobservable in this scope, so sentinel removal cannot be confirmed.");
5149
+ throw new Error(`[pgxsinkit] cannot settle ${JSON.stringify(storePath)} for an IDB boot (record phase ` + `${JSON.stringify(phase)}): the OPFS commitment namespace is unobservable in this scope, so sentinel ` + "removal cannot be confirmed.");
5243
5150
  }
5244
- await deleteIdbDatabase(storePath, meta);
5151
+ if (phase === "deleting")
5152
+ await deleteIdbDatabase(storePath, meta);
5245
5153
  await effects.deleteSentinel();
5154
+ await effects.deleteStoreDirectory();
5246
5155
  await writeStoreMetaRecord(storePath, { phase: "idb-authoritative", updatedAt: Date.now() }, meta);
5247
5156
  return true;
5248
5157
  }
@@ -5280,6 +5189,10 @@ async function resolveStoreBoot(storePath, opts) {
5280
5189
  const metaResult = await readStoreMetaRecord(storePath, meta);
5281
5190
  const metaUnavailable = metaResult === META_STORE_UNAVAILABLE;
5282
5191
  const record = metaUnavailable ? undefined : metaResult;
5192
+ const committedFastVerdict = record?.phase === "opfs-committed" ? classifyStoreBoot({ record, opfs: "unobservable", idbStoreExists: false }) : undefined;
5193
+ if (committedFastVerdict?.action === "open-committed") {
5194
+ return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict: committedFastVerdict };
5195
+ }
5283
5196
  const opfsObservation = await effects.observeCommitmentNamespace();
5284
5197
  const idbPresent = metaUnavailable ? false : await idbExists(storePath);
5285
5198
  const verdict = classifyStoreBoot({ record, opfs: opfsObservation, idbStoreExists: idbPresent });
@@ -5298,35 +5211,17 @@ async function resolveStoreBoot(storePath, opts) {
5298
5211
  case "delete-candidate-and-rebuild":
5299
5212
  await effects.deleteSentinel();
5300
5213
  await effects.deleteStoreDirectory();
5301
- return finishVirginCreate(verdict);
5214
+ await deleteStoreMetaRecord(storePath, meta);
5215
+ continue;
5302
5216
  case "repair-record-then-open-committed":
5303
5217
  await writePhase("opfs-committed");
5304
- if (idbPresent)
5305
- await deleteIdbDatabase(storePath, meta);
5306
5218
  return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict };
5307
5219
  case "open-committed":
5308
- if (idbPresent)
5309
- await deleteIdbDatabase(storePath, meta);
5310
5220
  return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict };
5311
5221
  case "boot-idb-authoritative":
5312
5222
  if (record == null)
5313
5223
  await writePhase("idb-authoritative");
5314
5224
  return { dataDir: idbDataDir, storageBackend: "idbfs", verdict };
5315
- case "adoption-recovery": {
5316
- const sentinelPresent = opfsObservation !== "unobservable" && opfsObservation.sentinelPresent;
5317
- const recovery = classifyAdoptionRecovery({ sentinelPresent });
5318
- if (recovery.action === "complete-adoption") {
5319
- await completeAdoption({
5320
- setPhase: writePhase,
5321
- deleteIdbPredecessor: () => deleteIdbDatabase(storePath, meta)
5322
- });
5323
- return { dataDir: opfsDataDir, storageBackend: "opfs-repacked", verdict };
5324
- }
5325
- await effects.deleteSentinel();
5326
- await effects.deleteStoreDirectory();
5327
- await writePhase("idb-authoritative");
5328
- return { dataDir: idbDataDir, storageBackend: "idbfs", verdict };
5329
- }
5330
5225
  case "virgin-create":
5331
5226
  return finishVirginCreate(verdict);
5332
5227
  default: {
@@ -5337,11 +5232,22 @@ async function resolveStoreBoot(storePath, opts) {
5337
5232
  }
5338
5233
  throw new Error("[pgxsinkit] store boot did not settle after resuming a deletion (bounded re-classification exhausted).");
5339
5234
  }
5340
- var MAX_DELETION_RECLASSIFY = 4;
5235
+ var MAX_DELETION_RECLASSIFY = 4, COMMITTED_STORE_UNREACHABLE_CODE = "committed-store-unreachable", CommittedStoreUnreachableError;
5341
5236
  var init_store_boot = __esm(() => {
5342
5237
  init_opfs_effects();
5343
5238
  init_store_meta();
5344
5239
  init_store_path();
5240
+ CommittedStoreUnreachableError = class CommittedStoreUnreachableError extends Error {
5241
+ code = COMMITTED_STORE_UNREACHABLE_CODE;
5242
+ storePath;
5243
+ detail;
5244
+ constructor(storePath) {
5245
+ super(`[pgxsinkit] refusing to boot ${JSON.stringify(storePath)} here: its store meta record says the store is ` + "COMMITTED to the OPFS backend, and this boot's engine home holds no OPFS sync-access grant \u2014 so it " + "cannot open that store. Booting the IndexedDB store at the same path would mint an EMPTY sibling: the " + "app would look wiped and offline writes would fork into a store no OPFS-capable boot ever opens. " + "Either boot from an engine home that HOLDS a grant (worker mode's elected engine worker, or the " + "SharedWorker-direct home), or destroy the store first \u2014 call " + `\`destroyStoreArtifacts(${JSON.stringify(storePath)})\` (exported from \`@pgxsinkit/client\`), which is ` + "path-addressed and needs no grant: it deletes BOTH backends plus the commitment sentinel and the meta " + "record (quiesce any live worker for the path first, `quiesceStoreWorker`) \u2014 and let the next boot " + "rebuild it (ADR-0049 invariant 3; ADR-0050 never a silently different storage mode).");
5246
+ this.name = "CommittedStoreUnreachableError";
5247
+ this.storePath = storePath;
5248
+ this.detail = { code: COMMITTED_STORE_UNREACHABLE_CODE, storePath };
5249
+ }
5250
+ };
5345
5251
  });
5346
5252
 
5347
5253
  // packages/client/src/sync/nudge.ts
@@ -6950,6 +6856,7 @@ function shouldApplyControlMessage(current, message) {
6950
6856
  return true;
6951
6857
  case "engine-ready":
6952
6858
  case "connect-port":
6859
+ case "connect-port-ack":
6953
6860
  case "control-ping":
6954
6861
  case "control-ack":
6955
6862
  case "overdue-dispatch":
@@ -7008,6 +6915,7 @@ var init_engine_control = __esm(() => {
7008
6915
  TAGGED_CONTROL_TYPES = new Set([
7009
6916
  "engine-ready",
7010
6917
  "connect-port",
6918
+ "connect-port-ack",
7011
6919
  "control-ping",
7012
6920
  "control-ack",
7013
6921
  "overdue-dispatch",
@@ -7040,6 +6948,7 @@ function createEngineRouter(options) {
7040
6948
  const { swInstanceId, executionLimit } = options;
7041
6949
  const probeMissThreshold = options.probeMissThreshold ?? 3;
7042
6950
  const probeIntervalMs = options.probeIntervalMs ?? 2000;
6951
+ const connectAckTimeoutMs = options.connectAckTimeoutMs ?? 3000;
7043
6952
  const createPipe = options.createPipe ?? (() => new MessageChannel);
7044
6953
  const timers = options.timers ?? {
7045
6954
  setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
@@ -7050,7 +6959,11 @@ function createEngineRouter(options) {
7050
6959
  let lastMinted;
7051
6960
  let controlPort;
7052
6961
  let controlListener;
6962
+ let controlCloseListener;
7053
6963
  let engineReady = false;
6964
+ let teardownForwarded;
6965
+ let connectAckHandle;
6966
+ const executionLimitEnabled = executionLimit?.maxDispatchMs !== undefined;
7054
6967
  let probeRunning = false;
7055
6968
  let probeHandle;
7056
6969
  let missCount = 0;
@@ -7067,6 +6980,23 @@ function createEngineRouter(options) {
7067
6980
  const { port1, port2 } = createPipe();
7068
6981
  controlPort.postMessage(wrapControlEnvelope({ type: "connect-port", identity: currentIdentity }), [port1]);
7069
6982
  tab.port.postMessage(wrapControlEnvelope({ type: "connect-port", identity: currentIdentity }), [port2]);
6983
+ if (executionLimitEnabled)
6984
+ armConnectAckWindow(currentIdentity);
6985
+ }
6986
+ function clearConnectAckWindow() {
6987
+ if (connectAckHandle !== undefined) {
6988
+ timers.clearTimeout(connectAckHandle);
6989
+ connectAckHandle = undefined;
6990
+ }
6991
+ }
6992
+ function armConnectAckWindow(armedFor) {
6993
+ clearConnectAckWindow();
6994
+ connectAckHandle = timers.setTimeout(() => {
6995
+ connectAckHandle = undefined;
6996
+ if (currentIdentity === undefined || !engineIdentityEquals(currentIdentity, armedFor))
6997
+ return;
6998
+ startProbe();
6999
+ }, connectAckTimeoutMs);
7070
7000
  }
7071
7001
  function resetProbe() {
7072
7002
  probeRunning = false;
@@ -7079,11 +7009,18 @@ function createEngineRouter(options) {
7079
7009
  }
7080
7010
  function clearEngine() {
7081
7011
  resetProbe();
7082
- if (controlPort !== undefined && controlListener !== undefined) {
7083
- controlPort.removeEventListener("message", controlListener);
7012
+ clearConnectAckWindow();
7013
+ if (controlPort !== undefined) {
7014
+ if (controlListener !== undefined)
7015
+ controlPort.removeEventListener("message", controlListener);
7016
+ if (controlCloseListener !== undefined) {
7017
+ controlPort.removeEventListener?.("close", controlCloseListener);
7018
+ }
7084
7019
  }
7085
7020
  controlPort = undefined;
7086
7021
  controlListener = undefined;
7022
+ controlCloseListener = undefined;
7023
+ teardownForwarded = undefined;
7087
7024
  currentIdentity = undefined;
7088
7025
  engineReady = false;
7089
7026
  }
@@ -7101,16 +7038,18 @@ function createEngineRouter(options) {
7101
7038
  resetProbe();
7102
7039
  return;
7103
7040
  }
7041
+ if (pendingPingId !== undefined) {
7042
+ missCount += 1;
7043
+ if (missCount >= probeMissThreshold) {
7044
+ resetProbe();
7045
+ retireCurrentEngine();
7046
+ return;
7047
+ }
7048
+ }
7104
7049
  const pingId = ++pingSeq;
7105
7050
  pendingPingId = pingId;
7106
7051
  controlPort.postMessage(wrapControlEnvelope({ type: "control-ping", identity: currentIdentity, pingId }));
7107
- missCount += 1;
7108
- if (missCount >= probeMissThreshold) {
7109
- resetProbe();
7110
- retireCurrentEngine();
7111
- } else {
7112
- scheduleProbe();
7113
- }
7052
+ scheduleProbe();
7114
7053
  }, probeIntervalMs);
7115
7054
  }
7116
7055
  function startProbe() {
@@ -7118,8 +7057,20 @@ function createEngineRouter(options) {
7118
7057
  return;
7119
7058
  probeRunning = true;
7120
7059
  missCount = 0;
7060
+ pendingPingId = undefined;
7121
7061
  scheduleProbe();
7122
7062
  }
7063
+ function onControlPortClose(port, announced) {
7064
+ if (controlPort !== port)
7065
+ return;
7066
+ if (currentIdentity === undefined || !engineIdentityEquals(currentIdentity, announced))
7067
+ return;
7068
+ if (teardownForwarded !== undefined && engineIdentityEquals(teardownForwarded, announced)) {
7069
+ clearEngine();
7070
+ return;
7071
+ }
7072
+ retireCurrentEngine();
7073
+ }
7123
7074
  function onControlMessage(data) {
7124
7075
  const message = readControlEnvelope(data);
7125
7076
  if (message === undefined)
@@ -7132,6 +7083,10 @@ function createEngineRouter(options) {
7132
7083
  deliverPipe(tab);
7133
7084
  }
7134
7085
  return;
7086
+ case "connect-port-ack":
7087
+ if (shouldApplyControlMessage(currentIdentity, message))
7088
+ clearConnectAckWindow();
7089
+ return;
7135
7090
  case "control-ack":
7136
7091
  if (shouldApplyControlMessage(currentIdentity, message) && message.pingId === pendingPingId) {
7137
7092
  resetProbe();
@@ -7161,6 +7116,7 @@ function createEngineRouter(options) {
7161
7116
  case "engine-teardown":
7162
7117
  if (!shouldApplyControlMessage(currentIdentity, message))
7163
7118
  return;
7119
+ teardownForwarded = message.identity;
7164
7120
  controlPort?.postMessage(wrapControlEnvelope(message));
7165
7121
  return;
7166
7122
  case "tab-detach":
@@ -7206,6 +7162,12 @@ function createEngineRouter(options) {
7206
7162
  controlPort = port;
7207
7163
  controlListener = (event) => onControlMessage(event.data);
7208
7164
  port.addEventListener("message", controlListener);
7165
+ const closable = port;
7166
+ if ("onclose" in closable) {
7167
+ const closeListener = () => onControlPortClose(port, minted);
7168
+ controlCloseListener = closeListener;
7169
+ closable.addEventListener("close", closeListener);
7170
+ }
7209
7171
  port.start?.();
7210
7172
  engineReady = false;
7211
7173
  port.postMessage(wrapControlEnvelope({ type: "assign-identity", identity: minted }));
@@ -7539,7 +7501,6 @@ function defineSyncWorker(options) {
7539
7501
  ...engineStorage ? { storage: engineStorage } : {},
7540
7502
  ...placementOpfsAccess ? { hasOpfsSyncAccess: true } : {},
7541
7503
  ...placementFallbackReason ? { storageFallbackReason: placementFallbackReason } : {},
7542
- ...options.adoption ? { adoption: options.adoption } : {},
7543
7504
  ...attach.config?.freshStore === true ? { freshStore: true } : {},
7544
7505
  getAuthToken: getWorkerAuthToken,
7545
7506
  autoSync: gatedTrigger,
@@ -7738,15 +7699,47 @@ function defineSyncWorker(options) {
7738
7699
  break;
7739
7700
  }
7740
7701
  const attempt = placementGate.then(async () => {
7702
+ let recordCandidateBeforeMint = false;
7741
7703
  if (backendOverride !== "memory") {
7742
7704
  const record = await readStoreMetaRecord(storePath);
7743
- if (record !== META_STORE_UNAVAILABLE && record?.phase === "deleting") {
7744
- syncDebug("worker provision declined \u2014 deletion authority is live", { storePath });
7705
+ const metaUnavailable = record === META_STORE_UNAVAILABLE;
7706
+ const phase = metaUnavailable ? undefined : record?.phase;
7707
+ if (phase === "opfs-committed" && !placementOpfsAccess) {
7708
+ syncDebug("worker provision declined \u2014 the store is committed to OPFS and this home holds no sync access", {
7709
+ storePath
7710
+ });
7711
+ return;
7712
+ }
7713
+ if (phase !== undefined && phase !== "opfs-committed" && (placementOpfsAccess || phase === "deleting" || phase === "opfs-candidate")) {
7714
+ syncDebug("worker provision declined \u2014 the store phase is owned elsewhere", { storePath, phase });
7745
7715
  return;
7746
7716
  }
7717
+ if (phase === undefined && placementOpfsAccess) {
7718
+ if (metaUnavailable) {
7719
+ syncDebug("worker provision declined \u2014 no meta store to record an opfs candidate", { storePath });
7720
+ return;
7721
+ }
7722
+ const observation = await createOpfsEffects(storePath).observeCommitmentNamespace();
7723
+ const virgin = observation !== "unobservable" && !observation.sentinelPresent && !observation.storeDirectoryPresent;
7724
+ if (!virgin) {
7725
+ syncDebug("worker provision declined \u2014 the commitment namespace is not a provable virgin", {
7726
+ storePath,
7727
+ observation
7728
+ });
7729
+ return;
7730
+ }
7731
+ if (await idbStoreExists(storePath)) {
7732
+ syncDebug("worker provision declined \u2014 an idb store already exists at this path", { storePath });
7733
+ return;
7734
+ }
7735
+ recordCandidateBeforeMint = true;
7736
+ }
7747
7737
  }
7748
7738
  if (bootPromise != null || provisioned != null)
7749
7739
  return;
7740
+ if (recordCandidateBeforeMint) {
7741
+ await writeStoreMetaRecord(storePath, { phase: "opfs-candidate", updatedAt: Date.now() });
7742
+ }
7750
7743
  const provisionStartedAt = nowStamp();
7751
7744
  const pglite = Promise.resolve().then(() => createPglite(storePath, backendOverride));
7752
7745
  const stamp = pglite.then(() => {
@@ -8045,6 +8038,7 @@ function startEngineControlPlane(controlPort, connect, closeScope) {
8045
8038
  case "connect-port": {
8046
8039
  if (!shouldApplyControlMessage(assigned, message))
8047
8040
  return;
8041
+ post({ type: "connect-port-ack", identity: message.identity });
8048
8042
  const transferred = event.ports?.[0];
8049
8043
  if (!transferred)
8050
8044
  return;
@@ -8362,6 +8356,7 @@ var init_define_sync_worker = __esm(() => {
8362
8356
  init_convergence();
8363
8357
  init_src();
8364
8358
  init_live_rows_sql();
8359
+ init_opfs_effects();
8365
8360
  init_placement_probe();
8366
8361
  init_store_meta();
8367
8362
  init_store_path();
@@ -8664,6 +8659,7 @@ __export(exports_attach_sync_client, {
8664
8659
  createStoreDestructionEffects: () => createStoreDestructionEffects,
8665
8660
  attachSyncClient: () => attachSyncClient,
8666
8661
  StoreDestroyRefusedError: () => StoreDestroyRefusedError,
8662
+ ProvisionExpiredError: () => ProvisionExpiredError,
8667
8663
  ElectedEngineUnconstructibleError: () => ElectedEngineUnconstructibleError
8668
8664
  });
8669
8665
  import { StorageDeclarationRefusedError as StorageDeclarationRefusedError2 } from "@pgxsinkit/contracts";
@@ -8900,6 +8896,11 @@ function adoptOrRegisterCoordinator(storePath, build) {
8900
8896
  let entry = sharedCoordinators.get(storePath);
8901
8897
  if (entry === undefined) {
8902
8898
  entry = { coordinator: build(), refs: 0 };
8899
+ const pending = pendingProvisionPipes.get(storePath);
8900
+ if (pending !== undefined) {
8901
+ pendingProvisionPipes.delete(storePath);
8902
+ entry.provisionPipe = pending;
8903
+ }
8903
8904
  sharedCoordinators.set(storePath, entry);
8904
8905
  }
8905
8906
  entry.refs += 1;
@@ -8921,19 +8922,35 @@ function releaseSharedCoordinator(storePath) {
8921
8922
  if (entry.refs <= 0) {
8922
8923
  entry.provisionPipe?.pipe.close?.();
8923
8924
  sharedCoordinators.delete(storePath);
8925
+ const pending = pendingProvisionPipes.get(storePath);
8926
+ if (pending !== undefined) {
8927
+ pendingProvisionPipes.delete(storePath);
8928
+ pending.pipe.close?.();
8929
+ }
8924
8930
  }
8925
8931
  }
8926
8932
  function stashProvisionPipe(storePath, pipe, identity) {
8927
8933
  const entry = sharedCoordinators.get(storePath);
8934
+ const previous = entry !== undefined ? entry.provisionPipe : pendingProvisionPipes.get(storePath);
8935
+ if (previous !== undefined && previous.pipe !== pipe && !engineIdentityEquals(previous.identity, identity)) {
8936
+ previous.pipe.close?.();
8937
+ }
8928
8938
  if (entry !== undefined)
8929
8939
  entry.provisionPipe = { pipe, identity };
8940
+ else
8941
+ pendingProvisionPipes.set(storePath, { pipe, identity });
8930
8942
  }
8931
8943
  function takeProvisionPipe(storePath) {
8932
8944
  const entry = sharedCoordinators.get(storePath);
8933
- const stashed = entry?.provisionPipe;
8934
- if (entry !== undefined)
8945
+ if (entry?.provisionPipe !== undefined) {
8946
+ const stashed = entry.provisionPipe;
8935
8947
  delete entry.provisionPipe;
8936
- return stashed;
8948
+ return stashed;
8949
+ }
8950
+ const pending = pendingProvisionPipes.get(storePath);
8951
+ if (pending !== undefined)
8952
+ pendingProvisionPipes.delete(storePath);
8953
+ return pending;
8937
8954
  }
8938
8955
  function setProvisionRelease(storePath, release) {
8939
8956
  const entry = sharedCoordinators.get(storePath);
@@ -9961,6 +9978,7 @@ function provisionSyncWorker(options) {
9961
9978
  clearTimeout: (handle) => globalThis.clearTimeout(handle)
9962
9979
  };
9963
9980
  const storePath = options.storePath ?? options.storeId ?? "pgxsinkit-overlay-v1";
9981
+ const expiryMs = options.provisionExpiryMs ?? 60000;
9964
9982
  const memoryOverride = readTestStoreMarker(options) === "memory";
9965
9983
  const provisionPayload = {
9966
9984
  ...options.storeId ? { storeId: options.storeId } : {},
@@ -9972,6 +9990,7 @@ function provisionSyncWorker(options) {
9972
9990
  const provision = new Promise((resolve, reject) => {
9973
9991
  let settled = false;
9974
9992
  const ackRemovers = [];
9993
+ let settlementHandle;
9975
9994
  const controlListener = (event) => {
9976
9995
  const placement = readPlacementResult(event.data);
9977
9996
  if (placement !== undefined) {
@@ -9994,8 +10013,12 @@ function provisionSyncWorker(options) {
9994
10013
  port.removeEventListener("message", controlListener);
9995
10014
  for (const remove of ackRemovers)
9996
10015
  remove();
10016
+ timers.clearTimeout(settlementHandle);
9997
10017
  fn();
9998
10018
  };
10019
+ settlementHandle = timers.setTimeout(() => {
10020
+ settle(() => reject(new ProvisionExpiredError(storePath, expiryMs)));
10021
+ }, expiryMs);
9999
10022
  const awaitAckOn = (ackPort) => {
10000
10023
  const ackListener = (message) => {
10001
10024
  if (!isBridgeEnvelope(message.data) || message.data.type !== "provision-ack")
@@ -10012,11 +10035,9 @@ function provisionSyncWorker(options) {
10012
10035
  postBridgeMessage(target, codec, "provision", provisionPayload);
10013
10036
  };
10014
10037
  let placementDecided = false;
10015
- let piped = false;
10016
10038
  const onProvisionPipe = (pipe, identity) => {
10017
- if (piped || pipe === undefined)
10039
+ if (settled || pipe === undefined)
10018
10040
  return;
10019
- piped = true;
10020
10041
  stashProvisionPipe(storePath, pipe, identity);
10021
10042
  postProvisionOn(pipe);
10022
10043
  };
@@ -10046,7 +10067,6 @@ function provisionSyncWorker(options) {
10046
10067
  ...pageLifecycle ? { pageLifecycle } : {}
10047
10068
  }));
10048
10069
  const releaseProvisionClaim = coordinator.claimForProvision();
10049
- const expiryMs = options.provisionExpiryMs ?? 60000;
10050
10070
  let released = false;
10051
10071
  const expiryHandle = timers.setTimeout(() => {
10052
10072
  if (released)
@@ -10112,6 +10132,9 @@ function rebuildError(error) {
10112
10132
  const mismatch = executionLimitMismatchFromWire(error.detail);
10113
10133
  if (mismatch !== undefined)
10114
10134
  return mismatch;
10135
+ const unreachable = committedStoreUnreachableFromWire(error.detail);
10136
+ if (unreachable !== undefined)
10137
+ return unreachable;
10115
10138
  }
10116
10139
  const rebuilt = new Error(error?.message ?? "worker rpc failed");
10117
10140
  if (error?.name !== undefined) {
@@ -10130,10 +10153,11 @@ function rebuildRpcError(error) {
10130
10153
  }
10131
10154
  return rebuildError(error);
10132
10155
  }
10133
- var StoreDestroyRefusedError, ElectedEngineUnconstructibleError, MUTATION_RPC_OPS, sharedCoordinators;
10156
+ var StoreDestroyRefusedError, ElectedEngineUnconstructibleError, ProvisionExpiredError, MUTATION_RPC_OPS, sharedCoordinators, pendingProvisionPipes;
10134
10157
  var init_attach_sync_client = __esm(() => {
10135
10158
  init_src();
10136
10159
  init_opfs_effects();
10160
+ init_store_boot();
10137
10161
  init_store_meta();
10138
10162
  init_store_path();
10139
10163
  init_store_path();
@@ -10156,6 +10180,16 @@ var init_attach_sync_client = __esm(() => {
10156
10180
  this.name = "ElectedEngineUnconstructibleError";
10157
10181
  }
10158
10182
  };
10183
+ ProvisionExpiredError = class ProvisionExpiredError extends Error {
10184
+ storePath;
10185
+ expiryMs;
10186
+ constructor(storePath, expiryMs) {
10187
+ super(`[pgxsinkit] provisionSyncWorker("${storePath}"): the provision did not settle within ${expiryMs}ms \u2014 the ` + `SharedWorker connection may be dead or the elected engine never came up. The deadline bounds THIS ` + `promise; the worker-side create attempt follows the placement. SW-direct: the attempt is left running, ` + `so a later attach adopts it if it completed and waits on it if it is stuck, and a retry re-acks the ` + `same attempt rather than starting a second open. Elected: this deadline also releases the provision ` + `claim, and a LAST-claim release retires and terminates the engine, so the next attach elects a fresh ` + `one. Retrying is safe either way.`);
10188
+ this.name = "ProvisionExpiredError";
10189
+ this.storePath = storePath;
10190
+ this.expiryMs = expiryMs;
10191
+ }
10192
+ };
10159
10193
  MUTATION_RPC_OPS = new Set([
10160
10194
  "create",
10161
10195
  "update",
@@ -10173,6 +10207,7 @@ var init_attach_sync_client = __esm(() => {
10173
10207
  "rawExec"
10174
10208
  ]);
10175
10209
  sharedCoordinators = new Map;
10210
+ pendingProvisionPipes = new Map;
10176
10211
  });
10177
10212
 
10178
10213
  // packages/client/src/index.ts
@@ -10187,6 +10222,9 @@ import {
10187
10222
  isClaimsDependentRowFilter,
10188
10223
  resolveStorageDeclaration as resolveStorageDeclaration2
10189
10224
  } from "@pgxsinkit/contracts";
10225
+ function isOpfsRepackedPersistent(instance) {
10226
+ return instance[OPFS_REPACKED_PERSISTENT] === true;
10227
+ }
10190
10228
  async function openWithBoundedRetries(open, backoffMs) {
10191
10229
  let lastError;
10192
10230
  for (let attempt = 1;attempt <= OPFS_OPEN_ATTEMPTS; attempt += 1) {
@@ -10206,7 +10244,7 @@ async function createClientPGlite(store, options) {
10206
10244
  const storePath = normalised.storePath;
10207
10245
  const backendOverride = options?.backendOverride ?? normalised.backendOverride;
10208
10246
  if (options?.hasOpfsSyncAccess !== true && backendOverride !== "memory") {
10209
- await recoverDeniedBootDeletion(storePath);
10247
+ await resolveDeniedBootAuthority(storePath);
10210
10248
  }
10211
10249
  const dataDir = options?.hasOpfsSyncAccess ? resolveStoreDataDir(storePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true }) : resolveStoreDataDir(storePath, backendOverride);
10212
10250
  const dataDirScheme = dataDir.slice(0, dataDir.indexOf(":") + 1);
@@ -10252,144 +10290,6 @@ async function createClientPGlite(store, options) {
10252
10290
  }, { ...dataDirScheme ? { dataDir: dataDirScheme } : {}, relaxedDurability });
10253
10291
  return pglite;
10254
10292
  }
10255
- function deleteAdoptionIdbPredecessor(storePath, meta) {
10256
- const idb = meta != null && "indexedDB" in meta ? meta.indexedDB : globalThis.indexedDB;
10257
- if (idb?.deleteDatabase == null)
10258
- return Promise.resolve();
10259
- const name = storeIndexedDbDatabaseName(storePath);
10260
- return new Promise((resolve, reject) => {
10261
- let settled = false;
10262
- let timeout;
10263
- const finish = (error) => {
10264
- if (settled)
10265
- return;
10266
- settled = true;
10267
- if (timeout !== undefined)
10268
- clearTimeout(timeout);
10269
- if (error === undefined)
10270
- resolve();
10271
- else
10272
- reject(error);
10273
- };
10274
- let request;
10275
- try {
10276
- request = idb.deleteDatabase(name);
10277
- } catch (error) {
10278
- finish(error);
10279
- return;
10280
- }
10281
- request.onsuccess = () => finish();
10282
- request.onerror = () => finish(request.error ?? new Error(`indexedDB deletion failed for ${name}`));
10283
- request.onblocked = () => {
10284
- return;
10285
- };
10286
- timeout = setTimeout(() => finish(new Error(`indexedDB deletion timed out while blocked for ${name}`)), 5000);
10287
- });
10288
- }
10289
- function buildRealAdoptionEffects(storePath, ctx) {
10290
- const opfs = createOpfsEffects(storePath, ctx.opfs);
10291
- const createPglite = ctx.createPglite ?? createClientPGlite;
10292
- const setPhase = (phase) => writeStoreMetaRecord(storePath, { phase, updatedAt: Date.now() }, ctx.meta);
10293
- return buildAdoptionEffects({
10294
- async readIdbJournal() {
10295
- const idbPglite = await createPglite(storePath, { durability: "strict" });
10296
- try {
10297
- const runtime = createMutationRuntime({
10298
- db: idbPglite,
10299
- registry: ctx.registry,
10300
- batchWriteUrl: ctx.batchWriteUrl,
10301
- ownsMetaTable: true
10302
- });
10303
- const stats = await runtime.readMutationStats();
10304
- return {
10305
- pending: stats.pendingCount,
10306
- sending: stats.sendingCount,
10307
- acked: stats.ackedCount,
10308
- failed: stats.failedCount,
10309
- quarantined: stats.quarantinedCount,
10310
- conflicted: stats.conflictedCount,
10311
- rejected: stats.rejectedCount
10312
- };
10313
- } finally {
10314
- await idbPglite.close();
10315
- }
10316
- },
10317
- setPhase,
10318
- async buildCandidate() {
10319
- if (!ctx.syncEnabled) {
10320
- throw new Error("[pgxsinkit] adoption gate unmet: sync is disabled (`syncEnabled: false`), so the opfs successor " + "cannot be reconstructed online. The idb store stays authoritative.");
10321
- }
10322
- const candidate = await createSyncClient({
10323
- registry: ctx.registry,
10324
- electricUrl: ctx.electricUrl,
10325
- batchWriteUrl: ctx.batchWriteUrl,
10326
- storePath,
10327
- hasOpfsSyncAccess: true,
10328
- freshStore: true,
10329
- syncEnabled: true,
10330
- [ADOPTION_CANDIDATE_BUILD]: true,
10331
- [INTERNAL_PGLITE_CREATE]: createPglite,
10332
- ...ctx.getAuthToken ? { getAuthToken: ctx.getAuthToken } : {},
10333
- ...ctx.requestHeaders ? { requestHeaders: ctx.requestHeaders } : {}
10334
- });
10335
- const strictSync = candidate.pglite.strictSync;
10336
- if (typeof strictSync !== "function") {
10337
- await candidate.stop().catch(() => {
10338
- return;
10339
- });
10340
- throw new Error("[pgxsinkit] adoption: the candidate store does not expose `strictSync()` \u2014 the commitment barrier " + "requires an OPFS-repacked engine (data-before-authority, invariant 3).");
10341
- }
10342
- return {
10343
- ready: candidate.ready,
10344
- strictSync: () => strictSync.call(candidate.pglite),
10345
- close: () => candidate.stop()
10346
- };
10347
- },
10348
- publishSentinel: () => opfs.publishSentinel(),
10349
- deleteSentinel: () => opfs.deleteSentinel(),
10350
- deleteStoreDirectory: () => opfs.deleteStoreDirectory(),
10351
- deleteIdbPredecessor: () => deleteAdoptionIdbPredecessor(storePath, ctx.meta),
10352
- ...ctx.gateDeadlineMs != null ? { gateDeadlineMs: ctx.gateDeadlineMs } : {}
10353
- });
10354
- }
10355
- function realAdoptionSeams(ctx, seams) {
10356
- return {
10357
- idbStoreExists: seams?.idbStoreExists ?? ((sp) => idbStoreExists(sp, ctx.meta)),
10358
- resolveStoreBoot: seams?.resolveStoreBoot ?? ((sp) => resolveStoreBoot(sp, {
10359
- hasOpfsSyncAccess: true,
10360
- ...ctx.meta || ctx.opfs ? { deps: { ...ctx.meta ? { meta: ctx.meta } : {}, ...ctx.opfs ? { opfs: ctx.opfs } : {} } } : {}
10361
- })),
10362
- buildEffects: seams?.buildEffects ?? ((sp) => buildRealAdoptionEffects(sp, ctx)),
10363
- log: seams?.log ?? ((message, data) => syncDebug(message, data))
10364
- };
10365
- }
10366
- async function runBootAdoption(storePath, declaration, ctx, seamsOverride) {
10367
- const seams = realAdoptionSeams(ctx, seamsOverride);
10368
- if (!await seams.idbStoreExists(storePath))
10369
- return { bootHasOpfs: true };
10370
- const resolution = await seams.resolveStoreBoot(storePath);
10371
- const verdict = resolution.verdict;
10372
- if (verdict === undefined || !adoptionEligible(declaration, verdict, true)) {
10373
- const bootHasOpfs = resolution.storageBackend === "opfs-repacked";
10374
- seams.log("boot adoption not eligible \u2014 using the classifier's resolved backend", {
10375
- action: verdict?.action,
10376
- storageBackend: resolution.storageBackend
10377
- });
10378
- return { bootHasOpfs };
10379
- }
10380
- const outcome = await runAdoptionTransition(declaration, seams.buildEffects(storePath));
10381
- if (outcome.adopted) {
10382
- seams.log("boot adoption committed the opfs successor; idb predecessor deleted", {
10383
- ...outcome.predecessorCleanupPending ? { predecessorCleanupPending: outcome.predecessorCleanupPending } : {}
10384
- });
10385
- return { bootHasOpfs: true, outcome };
10386
- }
10387
- seams.log("boot adoption deferred/failed \u2014 idb stays authoritative", {
10388
- reason: outcome.reason,
10389
- ...outcome.error ? { error: outcome.error } : {}
10390
- });
10391
- return { bootHasOpfs: false, outcome };
10392
- }
10393
10293
  function storageBackendFromDataDir(dataDir) {
10394
10294
  if (dataDir == null)
10395
10295
  return;
@@ -10409,9 +10309,14 @@ function verdictNeedsCommitmentBarrier(verdict, storageBackend) {
10409
10309
  return verdict?.action === "virgin-create" || verdict?.action === "delete-candidate-and-rebuild";
10410
10310
  }
10411
10311
  async function resolveFreshBoot(storePath, hasOpfsSyncAccess, backendOverride, seams) {
10312
+ const bootDeps = {
10313
+ ...seams?.meta ? { meta: seams.meta } : {},
10314
+ ...seams?.opfs ? { opfs: seams.opfs } : {},
10315
+ ...seams?.idbExists ? { idbExists: seams.idbExists } : {}
10316
+ };
10412
10317
  if (!hasOpfsSyncAccess || backendOverride === "memory") {
10413
10318
  if (!hasOpfsSyncAccess && backendOverride !== "memory")
10414
- await recoverDeniedBootDeletion(storePath);
10319
+ await resolveDeniedBootAuthority(storePath, bootDeps);
10415
10320
  return {
10416
10321
  bootHasOpfs: false,
10417
10322
  storageBackend: backendOverride === "memory" ? "memory" : "idbfs",
@@ -10420,13 +10325,7 @@ async function resolveFreshBoot(storePath, hasOpfsSyncAccess, backendOverride, s
10420
10325
  }
10421
10326
  const runResolve = seams?.resolveStoreBoot ?? ((sp) => resolveStoreBoot(sp, {
10422
10327
  hasOpfsSyncAccess: true,
10423
- ...seams?.meta || seams?.opfs || seams?.idbExists ? {
10424
- deps: {
10425
- ...seams?.meta ? { meta: seams.meta } : {},
10426
- ...seams?.opfs ? { opfs: seams.opfs } : {},
10427
- ...seams?.idbExists ? { idbExists: seams.idbExists } : {}
10428
- }
10429
- } : {}
10328
+ ...seams?.meta || seams?.opfs || seams?.idbExists ? { deps: bootDeps } : {}
10430
10329
  }));
10431
10330
  const resolution = await runResolve(storePath);
10432
10331
  const bootHasOpfs = resolution.storageBackend === "opfs-repacked";
@@ -10461,6 +10360,19 @@ async function runFreshCommitmentBarrier(storePath, strictSyncReturns, seams) {
10461
10360
  storePath
10462
10361
  });
10463
10362
  }
10363
+ async function resolveAdoptedCommitmentBarrier(storePath, seams) {
10364
+ const metaResult = await readStoreMetaRecord(storePath, seams?.meta);
10365
+ const metaUnavailable = metaResult === META_STORE_UNAVAILABLE;
10366
+ const record = metaUnavailable ? undefined : metaResult;
10367
+ const needsCommitmentBarrier = !metaUnavailable && (record === undefined || record.phase === "opfs-candidate");
10368
+ (seams?.log ?? ((message, data) => syncDebug(message, data)))("boot adopted store commitment resolved", {
10369
+ storePath,
10370
+ phase: record?.phase ?? null,
10371
+ ...metaUnavailable ? { metaStoreUnavailable: true } : {},
10372
+ needsCommitmentBarrier
10373
+ });
10374
+ return needsCommitmentBarrier;
10375
+ }
10464
10376
  function formatOpenFailureReason(error) {
10465
10377
  if (error instanceof Error)
10466
10378
  return `${error.name || "Error"}: ${error.message}`;
@@ -10475,26 +10387,6 @@ async function fallbackVirginCandidateToIdb(storePath, openError, seams) {
10475
10387
  (seams?.log ?? ((message, data) => syncDebug(message, data)))("boot fresh commitment: opfs candidate uncreatable after bounded retries \u2014 session idbfs fallback", { storePath, reason });
10476
10388
  return reason;
10477
10389
  }
10478
- async function adoptStore(options) {
10479
- const storePath = options.storePath ?? "pgxsinkit-overlay-v1";
10480
- const isStoreLive = options.seams?.isStoreLive ?? ((sp) => liveStorePaths.has(sp));
10481
- if (isStoreLive(storePath))
10482
- throw new StoreInUseError(storePath);
10483
- const ctx = {
10484
- registry: options.registry,
10485
- electricUrl: options.electricUrl,
10486
- batchWriteUrl: options.batchWriteUrl,
10487
- ...options.getAuthToken ? { getAuthToken: options.getAuthToken } : {},
10488
- ...options.requestHeaders ? { requestHeaders: options.requestHeaders } : {},
10489
- syncEnabled: options.syncEnabled ?? true,
10490
- ...options.gateDeadlineMs != null ? { gateDeadlineMs: options.gateDeadlineMs } : {},
10491
- ...options.seams?.meta ? { meta: options.seams.meta } : {},
10492
- ...options.seams?.opfs ? { opfs: options.seams.opfs } : {},
10493
- ...options.seams?.createPglite ? { createPglite: options.seams.createPglite } : {}
10494
- };
10495
- const effects = options.seams?.buildEffects?.(storePath) ?? buildRealAdoptionEffects(storePath, ctx);
10496
- return runManualAdoption(effects);
10497
- }
10498
10390
  function replAdapter(client) {
10499
10391
  return {
10500
10392
  query: (sql7, params, options) => client.rawQuery(sql7, params, options),
@@ -10502,8 +10394,6 @@ function replAdapter(client) {
10502
10394
  };
10503
10395
  }
10504
10396
  async function createSyncClient(options) {
10505
- const adoptionCandidateBuild = options[ADOPTION_CANDIDATE_BUILD] === true;
10506
- const createPglite = options[INTERNAL_PGLITE_CREATE] ?? createClientPGlite;
10507
10397
  validateLiveQueryPolicy(options.liveQueries);
10508
10398
  const status = {
10509
10399
  phase: "booting",
@@ -10583,7 +10473,7 @@ async function createSyncClient(options) {
10583
10473
  const timedCreate = async () => {
10584
10474
  const startedAt = performance.now();
10585
10475
  const resolvedDataDir = bootHasOpfsSyncAccess ? resolveStoreDataDir(fallbackStorePath, backendOverride, { hasIndexedDb: true, hasOpfsSyncAccess: true }) : resolveStoreDataDir(fallbackStorePath, backendOverride);
10586
- const created = await createPglite(fallbackStorePath, {
10476
+ const created = await createClientPGlite(fallbackStorePath, {
10587
10477
  ...createClientOptions,
10588
10478
  ...bootHasOpfsSyncAccess ? { hasOpfsSyncAccess: true } : {}
10589
10479
  });
@@ -10595,26 +10485,10 @@ async function createSyncClient(options) {
10595
10485
  bootReportBuilder.setPgliteCreateMs(performance.now() - startedAt);
10596
10486
  return created;
10597
10487
  };
10598
- const runBootAdoptionIfDeclared = async () => {
10599
- if (!bootHasOpfsSyncAccess || options.adoption !== "server-reconstructible" || restoreBoot)
10600
- return;
10601
- const { bootHasOpfs, outcome } = await runBootAdoption(fallbackStorePath, options.adoption, {
10602
- registry: options.registry,
10603
- electricUrl: options.electricUrl,
10604
- batchWriteUrl: options.batchWriteUrl,
10605
- ...options.getAuthToken ? { getAuthToken: options.getAuthToken } : {},
10606
- ...options.requestHeaders ? { requestHeaders: options.requestHeaders } : {},
10607
- syncEnabled: options.syncEnabled ?? true
10608
- });
10609
- bootHasOpfsSyncAccess = bootHasOpfs;
10610
- if (!bootHasOpfs && outcome && outcome.adopted === false) {
10611
- storageFallbackReason = `adoption deferred (${outcome.reason})`;
10612
- }
10613
- };
10614
10488
  const refuseIfNonPersistent = (instance) => {
10615
10489
  if (testStoreMarker !== undefined)
10616
10490
  return;
10617
- if (instance[OPFS_REPACKED_PERSISTENT] === true)
10491
+ if (isOpfsRepackedPersistent(instance))
10618
10492
  return;
10619
10493
  const observedDataDir = instance.dataDir;
10620
10494
  const observed = classifyNonPersistentDataDir(observedDataDir);
@@ -10623,16 +10497,9 @@ async function createSyncClient(options) {
10623
10497
  };
10624
10498
  const openOwnedStore = async () => {
10625
10499
  if (!bootHasOpfsSyncAccess && backendOverride !== "memory") {
10626
- await recoverDeniedBootDeletion(fallbackStorePath);
10500
+ await resolveDeniedBootAuthority(fallbackStorePath);
10627
10501
  }
10628
- if (!adoptionCandidateBuild)
10629
- await runBootAdoptionIfDeclared();
10630
- if (adoptionCandidateBuild) {
10631
- const opfs = createOpfsEffects(fallbackStorePath);
10632
- await opfs.deleteSentinel();
10633
- await opfs.deleteStoreDirectory();
10634
- await opfs.getStoreDirectoryHandle();
10635
- } else if (bootHasOpfsSyncAccess) {
10502
+ if (bootHasOpfsSyncAccess) {
10636
10503
  const fresh = await resolveFreshBoot(fallbackStorePath, bootHasOpfsSyncAccess, backendOverride);
10637
10504
  if (!fresh.bootHasOpfs && storageFallbackReason == null) {
10638
10505
  storageFallbackReason = `recordless idb store opened in place (invariant 14; verdict ${fresh.verdict?.action ?? "unknown"})`;
@@ -10685,9 +10552,12 @@ async function createSyncClient(options) {
10685
10552
  bootReportBuilder.setStorageBackend(byoBackend);
10686
10553
  }
10687
10554
  }
10555
+ const adoptedCommitmentGate = (options.pgliteInstance != null || adoptedPrecreated) && backendOverride !== "memory" && isOpfsRepackedPersistent(pglite) ? resolveAdoptedCommitmentBarrier(fallbackStorePath) : null;
10556
+ if (adoptedCommitmentGate)
10557
+ adoptedCommitmentGate.catch(() => {
10558
+ return;
10559
+ });
10688
10560
  const ownsStoreLifecycle = !options.pgliteInstance;
10689
- if (ownsStoreLifecycle)
10690
- liveStorePaths.add(fallbackStorePath);
10691
10561
  if (adoptedPrecreated && options.provisionStamp) {
10692
10562
  const stamp = await options.provisionStamp.catch(() => null);
10693
10563
  if (stamp) {
@@ -10785,8 +10655,12 @@ async function createSyncClient(options) {
10785
10655
  const currentFingerprint = computeLocalSchemaFingerprint(options.registry);
10786
10656
  const storedFingerprint = await readStoredLocalSchemaFingerprint(pglite, options.registry);
10787
10657
  if (storedFingerprint === currentFingerprint) {
10658
+ syncDebug("boot local schema fingerprint match \u2014 durable exec skipped");
10788
10659
  bootReportBuilder.setSchemaFastPath({ skipped: true, fingerprintMatch: true });
10789
10660
  } else {
10661
+ syncDebug("boot local schema fingerprint mismatch \u2014 replaying durable schema", {
10662
+ hadStored: storedFingerprint != null
10663
+ });
10790
10664
  await pglite.exec(generateDurableLocalSchemaSql(options.registry));
10791
10665
  await writeStoredLocalSchemaFingerprint(pglite, options.registry, currentFingerprint);
10792
10666
  bootReportBuilder.setSchemaFastPath({ skipped: false, fingerprintMatch: false });
@@ -10862,7 +10736,6 @@ async function createSyncClient(options) {
10862
10736
  const isSyncPending = () => syncEnabled && sync == null && !disposed;
10863
10737
  const quiesceTailForTeardown = async () => {
10864
10738
  disposed = true;
10865
- liveStorePaths.delete(fallbackStorePath);
10866
10739
  const disposedError = new ClientDisposedError;
10867
10740
  rejectWriteReady(disposedError);
10868
10741
  rejectReady(disposedError);
@@ -11395,6 +11268,8 @@ async function createSyncClient(options) {
11395
11268
  subscribeLiveRows: client.subscribeLiveRows,
11396
11269
  query: (sql7, params) => pglite.query(sql7, params)
11397
11270
  });
11271
+ if (adoptedCommitmentGate)
11272
+ commitmentBarrierPending = await adoptedCommitmentGate;
11398
11273
  if (commitmentBarrierPending) {
11399
11274
  await runFreshCommitmentBarrier(fallbackStorePath, resolveEngineStrictSync(pglite));
11400
11275
  }
@@ -11498,9 +11373,8 @@ function getClientProjection2(entry, tableKey) {
11498
11373
  }
11499
11374
  return entry.clientProjection;
11500
11375
  }
11501
- var WriteNotReadyError, ClientDisposedError, OPFS_OPEN_ATTEMPTS = 10, OPFS_OPEN_BACKOFF_MS = 100, OPFS_STORE_EXTENT_SIZE = 65536, OPFS_REPACKED_PERSISTENT, StoreInUseError, liveStorePaths, ADOPTION_CANDIDATE_BUILD, INTERNAL_PGLITE_CREATE;
11376
+ var WriteNotReadyError, ClientDisposedError, OPFS_OPEN_ATTEMPTS = 10, OPFS_OPEN_BACKOFF_MS = 100, OPFS_STORE_EXTENT_SIZE = 65536, OPFS_REPACKED_PERSISTENT;
11502
11377
  var init_src = __esm(() => {
11503
- init_adoption();
11504
11378
  init_boot_report();
11505
11379
  init_convergence();
11506
11380
  init_export_data();
@@ -11524,7 +11398,6 @@ var init_src = __esm(() => {
11524
11398
  init_live_rows_sql();
11525
11399
  init_export_dump();
11526
11400
  init_export_data();
11527
- init_adoption();
11528
11401
  init_lifecycle_slot();
11529
11402
  init_attach_sync_client();
11530
11403
  init_engine_control();
@@ -11552,15 +11425,6 @@ var init_src = __esm(() => {
11552
11425
  }
11553
11426
  };
11554
11427
  OPFS_REPACKED_PERSISTENT = Symbol.for("pgxsinkit.opfsRepackedPersistent");
11555
- StoreInUseError = class StoreInUseError extends Error {
11556
- constructor(storePath) {
11557
- super(`[pgxsinkit] adoptStore(${JSON.stringify(storePath)}) refused: a live client is currently holding this ` + "store. Adoption is a creation-path migration \u2014 call it INSTEAD of createSyncClient, before any client " + "opens the store (stop/destroy the existing client first).");
11558
- this.name = "StoreInUseError";
11559
- }
11560
- };
11561
- liveStorePaths = new Set;
11562
- ADOPTION_CANDIDATE_BUILD = Symbol("pgxsinkit.adoptionCandidateBuild");
11563
- INTERNAL_PGLITE_CREATE = Symbol("pgxsinkit.internalPgliteCreate");
11564
11428
  });
11565
11429
  init_src();
11566
11430
 
@@ -11574,14 +11438,12 @@ export {
11574
11438
  setSyncDebugSink,
11575
11439
  seedLiveDiffState,
11576
11440
  runThrowawayCloneDump,
11577
- runManualAdoption,
11578
11441
  runFreshCommitmentBarrier,
11579
- runBootAdoption,
11580
- runAdoptionTransition,
11581
11442
  rowKey,
11582
11443
  resolveStoreDataDir,
11583
11444
  resolveStoreBoot,
11584
11445
  resolveFreshBoot,
11446
+ resolveAdoptedCommitmentBarrier,
11585
11447
  replAdapter,
11586
11448
  quiesceStoreWorker,
11587
11449
  provisionSyncWorker,
@@ -11618,16 +11480,15 @@ export {
11618
11480
  createClientPGlite,
11619
11481
  createBrowserConvergenceTrigger,
11620
11482
  computeLiveDiff,
11483
+ committedStoreUnreachableFromWire,
11621
11484
  buildRegistryReadHandles,
11622
11485
  buildLazyGuardIndex,
11623
11486
  attachSyncClient,
11624
11487
  assertLazyRefsActivated,
11625
- adoptionEligible,
11626
- adoptStore,
11627
11488
  WriteNotReadyError,
11628
- StoreInUseError,
11629
11489
  StoreDestroyRefusedError,
11630
11490
  RestoreTargetExistsError,
11491
+ ProvisionExpiredError,
11631
11492
  NonPersistentStoreError,
11632
11493
  LiveRowsMaterializer,
11633
11494
  LifecycleBusyError,
@@ -11639,9 +11500,11 @@ export {
11639
11500
  ENGINE_RELOCATED_CODE,
11640
11501
  DataExportDrainError,
11641
11502
  DEFAULT_DRAIN_TIMEOUT_MS,
11503
+ CommittedStoreUnreachableError,
11642
11504
  ClientDisposedError,
11505
+ COMMITTED_STORE_UNREACHABLE_CODE,
11643
11506
  BRIDGE_PROTOCOL_VERSION,
11644
11507
  BRIDGE_CHANNEL
11645
11508
  };
11646
11509
 
11647
- //# debugId=62F3E6980D885DE664756E2164756E21
11510
+ //# debugId=2E0B3932787BD9A964756E2164756E21