@pgxsinkit/client 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -14,7 +14,7 @@ description: >-
14
14
  metadata:
15
15
  type: task
16
16
  library: "@pgxsinkit/client"
17
- library_version: "0.2.0"
17
+ library_version: "0.2.2"
18
18
  source: https://pgxsinkit.github.io/start/operating-in-production/
19
19
  ---
20
20
 
@@ -115,9 +115,15 @@ mode and the main-thread idb fallback where SharedWorker is missing.
115
115
  durability option (both are runtime/registry concerns); the registry is CODE, _imported_ by the worker
116
116
  file, never cloned/serialized in. Give each store a stable SharedWorker name and always pass
117
117
  `extendedLifetime: true` (Chromium 148+ grace period; ignore-safe elsewhere). The tab calls
118
- `attachSyncClient({ worker, registry, getToken })`, where `worker` is a **factory**
119
- (`worker: () => SharedWorker`), not an instance — a SharedWorker cannot be reconstructed from itself, and
120
- the factory is what makes SharedWorker-death recovery a guarantee. The elected engine worker needs no
118
+ `attachSyncClient({ worker, registry, getToken })`. Prefer the **factory** form (`worker: () => SharedWorker`)
119
+ over a bare instance or a raw `port` (`SharedWorker.port`) — a SharedWorker cannot be reconstructed from
120
+ itself, so **in elected placement** (Chromium/Firefox) the factory is what arms SharedWorker(router)-death
121
+ recovery: the election coordinator's keepalive reconstructs the router through it. A `port`/instance input
122
+ stays fully functional — provision, attach, and the provision→attach handoff all work (the handoff is keyed
123
+ by `storePath`, not the transport) — but **forfeits that reconstruction** (the coordinator detects the death
124
+ and can only stop). In SW-direct placement (Safari/idbfs) the engine lives in the SharedWorker and there is
125
+ no keepalive; neither form auto-recovers a dead SharedWorker (opt into `bridgeSilenceMs` + a factory for a
126
+ bridge-silence reconnect there). The elected engine worker needs no
121
127
  consumer wiring: the SharedWorker reports its own script URL and the winning tab constructs the engine as
122
128
  `new Worker(reportedUrl, { type: "module" })`. Supply `createEngineWorker` ONLY as an override for entries
123
129
  that cannot be reconstructed from their URL as a module worker (classic-script workers, `blob:`/`data:`
@@ -165,7 +171,7 @@ so GoTrue refresh-token reuse detection can't be tripped by a second client.
165
171
  **Boot: spare-as-worker + internal prefetch overlap.** The spare store (see above) becomes a pre-spawned
166
172
  schemaless worker at the login screen (create + initdb off every thread that matters); the userId→storeId
167
173
  registry stays tab-side in localStorage so binding resolves before attach (SharedWorker naming needs it).
168
- Call `provisionSyncWorker` with the same `worker` factory as attach; an elected
174
+ Call `provisionSyncWorker` with the same `worker` input as attach (the factory form, so elected-mode recovery is armed for provisioning too); an elected
169
175
  Chromium/Firefox pre-open shares the tab's one election coordinator and auto-derives the engine from the
170
176
  SharedWorker's own script URL (override with `createEngineWorker` only for non-module/underivable entries).
171
177
  Claim = bind id, attach, push config + token. On a PROVABLY-fresh claimed store, pass
@@ -294,13 +300,52 @@ offline for inspection; a clean-journal restore may honor the normal online opti
294
300
  persisted store normally. Consumer docs:
295
301
  <https://pgxsinkit.github.io/concepts/export-and-restore/>.
296
302
 
297
- **Adoption and construction changes.** An existing idb store is authoritative and is never silently
298
- replaced by a newly capable OPFS home. Automatic adoption is default-off and requires the worker-entry
299
- declaration `adoption: "server-reconstructible"`; only a drained journal, authorized online reconstruction,
300
- and a returned strict barrier permit the idb predecessor to be deleted. `adoptStore()` is the manual
301
- creation-path equivalent and refuses a live store with `StoreInUseError`. Before changing a SW-direct
302
- construction identity such as durability, await `retireSyncWorkerHost()` so an extended-lifetime worker
303
- releases its handle without deleting the store; it refuses peers and does not apply to elected placement.
303
+ **Adoption.** An existing idb store is authoritative and is never silently replaced by a newly capable
304
+ OPFS home. Automatic adoption is default-off and requires the worker-entry declaration
305
+ `adoption: "server-reconstructible"`; only a drained journal, authorized online reconstruction, and a
306
+ returned strict barrier permit the idb predecessor to be deleted. `adoptStore()` is the manual
307
+ creation-path equivalent and refuses a live store with `StoreInUseError`.
308
+
309
+ **Resetting and deleting stores (ADR-0050).** Three non-interchangeable levers — pick by what you keep
310
+ and whether the store is running:
311
+
312
+ - `client.dropReadCache()` — keep the store, drop synced rows, resync in place (overlay + journal survive).
313
+ - `client.destroy()` — delete a RUNNING store from an attached client: peer-count checked
314
+ (`StoreDestroyRefusedError` while peers hold it), owed-journal checked (refused unless `force`),
315
+ teardown-acknowledged before deletion.
316
+ - `destroyStoreArtifacts(storePath)` — delete a NOT-running store by path: OPFS directory + commitment
317
+ sentinel + meta record + idb database, backend-agnostic, bounded ownership-lag retry. Documented
318
+ precondition, no liveness probe: on a still-held path it throws the ownership error — loud and safely
319
+ re-runnable (idempotent, phase-recorded; a `deleting`-marked store is refused for boot). Keep failed
320
+ paths on a retry list for the next boot. An idb-only sweep is NOT a substitute — it leaks the OPFS arena.
321
+ - `quiesceStoreWorker(worker, opts?)` (ADR-0050) — the by-path TEARDOWN companion that MAKES a store
322
+ not-running before `destroyStoreArtifacts`. Give it a worker factory of the same shape `attachSyncClient`
323
+ takes (`() => new SharedWorker(url, { name: storePath })`) — but the factory MUST construct the worker with
324
+ **byte-identical options to the LIVE store worker**, `extendedLifetime: true` included. A named SharedWorker
325
+ dedups onto one instance, and Chromium (148+) FAILS a second `new SharedWorker(name, …)` whose options
326
+ disagree with the live one (an `error` event, no `onconnect`) — the teardown port then exchanges zero
327
+ messages and only times out. Omitting `extendedLifetime` on the teardown worker does not shorten its life
328
+ (`closeHost` + `scope.close()` end it); it only breaks the dedup and defeats the primitive. It reaches the
329
+ worker by name, posts the
330
+ declaration, queries placement, and for an SW-direct home (idbfs, real-Safari opfs) sends `engine-teardown`
331
+ and AWAITS the reserved ack (engine stopped, backend connection released → `{ toreDown: true }`); an elected
332
+ home is a no-op (`{ toreDown: false }` — the elected engine dies with its tab). Compose best-effort:
333
+ `await quiesceStoreWorker(f).catch(() => {}); await destroyStoreArtifacts(path)`. A timeout REJECTS (not
334
+ proof of teardown, default 6s) and must not abort the destroy; omit `storage` (no opinion) so a worker on
335
+ an older declaration is never refused; idempotent + safe on an already-dead store.
336
+
337
+ **Storage-preference changes.** A store's storage declaration (backend/durability) is IMMUTABLE — bound at
338
+ first contact, conflicts refused typed (`StorageDeclarationRefusedError`). Never re-home or
339
+ delete-and-recreate a live path (an `extendedLifetime` predecessor may still hold it). The pattern:
340
+ atomically drop bindings + record the old exact paths on an obsolete list FIRST, then write the new
341
+ preference and reload; fresh stores mint under fresh paths, and each boot walks the obsolete list in
342
+ the background (never awaited on sign-in), per path QUIESCING the worker (`quiesceStoreWorker`) BEFORE
343
+ `destroyStoreArtifacts`. The quiesce is what makes idbfs converge: an `extendedLifetime` idbfs
344
+ predecessor holds its IndexedDB connection across the reload, so a bare destroy would block forever
345
+ (opfs releases on idle; idbfs does not) — tearing the host down releases the connection so the first
346
+ retry wins. Dynamic declarations travel as the wire `storage` option on
347
+ `attachSyncClient`/`provisionSyncWorker`; a registry-attached static declaration stays authoritative. Consumer docs:
348
+ <https://pgxsinkit.github.io/concepts/local-store-lifecycle/>.
304
349
 
305
350
  ## Proxying Electric: force `cache-control: no-store`
306
351
 
package/src/index.ts CHANGED
@@ -15,6 +15,7 @@ import type {
15
15
  SyncRuntimeStatus,
16
16
  SyncTableCreateInput,
17
17
  SyncTableEntry,
18
+ SyncStorageDeclaration,
18
19
  SyncTableName,
19
20
  SyncTableRegistry,
20
21
  SyncTableUpdateInput,
@@ -26,6 +27,7 @@ import {
26
27
  getSyncRegistrySchema,
27
28
  getSyncRegistryStorage,
28
29
  isClaimsDependentRowFilter,
30
+ resolveStorageDeclaration,
29
31
  } from "@pgxsinkit/contracts";
30
32
  // Type-only import (erased at runtime): the opfs-repacked factory's option/return types for the `opfs://`
31
33
  // branch. The factory VALUE is loaded lazily via dynamic `import()` inside that branch so a Bun unit test
@@ -168,9 +170,14 @@ export {
168
170
  } from "./adoption";
169
171
  export { createLifecycleSlot, LifecycleBusyError, type LifecycleSlot } from "./lifecycle-slot";
170
172
  export {
173
+ destroyStoreArtifacts,
171
174
  type ElectedEngineWorker,
172
175
  ElectedEngineUnconstructibleError,
176
+ quiesceStoreWorker,
173
177
  StoreDestroyRefusedError,
178
+ type StoreDestructionRetryOptions,
179
+ type StoreWorkerQuiesceOptions,
180
+ type StoreWorkerQuiesceOutcome,
174
181
  wrapEngineWorker,
175
182
  } from "./worker/attach-sync-client";
176
183
  export {
@@ -210,8 +217,6 @@ export {
210
217
  attachSyncClient,
211
218
  type AttachSyncClientOptions,
212
219
  provisionSyncWorker,
213
- retireSyncWorkerHost,
214
- type RetireSyncWorkerHostOptions,
215
220
  } from "./worker/attach-sync-client";
216
221
  export { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from "./worker/define-sync-worker";
217
222
  export {
@@ -1178,6 +1183,15 @@ export interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {
1178
1183
  * `@pgxsinkit/client/testing` instead of naming one here.
1179
1184
  */
1180
1185
  storePath?: string;
1186
+ /**
1187
+ * @internal Toolkit-internal WIRE-declaration carrier (ADR-0050), NOT a public per-boot knob. The worker
1188
+ * host threads the store's BOUND storage declaration (registry static + the first payload's wire
1189
+ * declaration + defaults) in here, and this boot's single storage resolution point folds it with the
1190
+ * registry's own static declaration — an explicit disagreement is a typed
1191
+ * `StorageDeclarationRefusedError` (the worker handlers refuse conflicts before this ever throws).
1192
+ * In-process consumers never set it: their registry IS the declaration.
1193
+ */
1194
+ storage?: SyncStorageDeclaration;
1181
1195
  /**
1182
1196
  * ADR-0049 D1: the placement probe's OPFS-sync-access grant, threaded from the SharedWorker's engine home
1183
1197
  * (`defineSyncWorker`'s SW-direct bootstrap) into this boot so the client-owned create opens the OPFS-repacked
@@ -1595,6 +1609,14 @@ export interface SyncClient<TRegistry extends SyncTableRegistry> {
1595
1609
  ready: Promise<void>;
1596
1610
  status: SyncRuntimeStatus;
1597
1611
  start: () => Promise<void>;
1612
+ /**
1613
+ * Synchronously abort all sync/write activity (in-flight write fetches, shape-stream long-polls, convergence
1614
+ * scheduling) without awaiting. Idempotent. The first action of every teardown path — stop()/destroy() call it,
1615
+ * and the SharedWorker host calls it before draining subscribes / disposing live queries so no teardown step
1616
+ * races a still-live engine. Not a substitute for stop()/destroy(): the awaited teardown (unsubscribe, dispose,
1617
+ * pglite.close) still follows. Callers rarely invoke it directly.
1618
+ */
1619
+ haltActivity: () => void;
1598
1620
  stop: () => Promise<void>;
1599
1621
  /**
1600
1622
  * Wipe the entire local store (synced cache + overlay + journal) and close the handle
@@ -2050,11 +2072,17 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2050
2072
  // once the adoption + fresh phase machine has settled (never on a plain idb boot, where `probeGranted` is false).
2051
2073
  const probeGranted = options.hasOpfsSyncAccess === true;
2052
2074
  let storageFallbackReason: string | undefined;
2053
- // Durability (ADR-0047 D2): resolve the registry's declared mode ONCE here — this is the single resolution
2054
- // point — and thread it into every client-owned mint (its own boot create and the precreated-reject fallback)
2055
- // via the internal carrier on `createClientPGlite`. `storage.durability ?? "relaxed"` is the toolkit default;
2056
- // no open site takes a durability option, so no mint can contradict the data contract.
2057
- const resolvedDurability: StorageDurability = getSyncRegistryStorage(options.registry)?.durability ?? "relaxed";
2075
+ // Durability (ADR-0047 D2 + ADR-0050): resolve the store's declared mode ONCE here — this is the single
2076
+ // resolution point — from the registry's static declaration folded with the worker-threaded wire
2077
+ // declaration (`options.storage`, the ADR-0050 internal carrier; absent for in-process consumers). An
2078
+ // explicit disagreement is a typed refusal (the worker handlers refuse conflicts before this throws).
2079
+ // The resolved mode threads into every client-owned mint (its own boot create and the precreated-reject
2080
+ // fallback) via the internal carrier on `createClientPGlite`; no open site takes a durability option, so
2081
+ // no mint can contradict the data contract.
2082
+ const resolvedDurability: StorageDurability = resolveStorageDeclaration(
2083
+ getSyncRegistryStorage(options.registry),
2084
+ options.storage,
2085
+ ).durability;
2058
2086
  const createClientOptions: CreateClientPGliteOptions = {
2059
2087
  ...(options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : {}),
2060
2088
  ...(backendOverride ? { backendOverride } : {}),
@@ -2617,6 +2645,21 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
2617
2645
  await bootSettled.catch(() => undefined);
2618
2646
  };
2619
2647
 
2648
+ // Synchronously halt ALL sync/write ACTIVITY without awaiting anything — the first action of every teardown
2649
+ // entry point (stop()/destroy() here, and the SharedWorker host's closeHost, which calls this before it drains
2650
+ // pending subscribes or disposes live queries). Abort the mutation runtime's in-flight write fetches + any
2651
+ // stalled auth resolve, abort every shape-stream long-poll (engine.close's AbortControllers fire synchronously),
2652
+ // and stop convergence scheduling (the in-flight pass then settles fast — its fetch is aborted). Idempotent.
2653
+ // Without this, a teardown step that runs BEFORE the streams are aborted (live-query dispose, pending-subscribe
2654
+ // drain) races an engine still committing shape data and never settles. The full AWAITED teardown still runs
2655
+ // after; this only guarantees the network + scheduling are already dead when it does.
2656
+ const haltActivity = (): void => {
2657
+ disposed = true;
2658
+ mutationRuntime.abortInFlight();
2659
+ void engine.close();
2660
+ void convergenceDriver?.stop();
2661
+ };
2662
+
2620
2663
  // The write/sync activation tail (ADR-0041 decision 3). On a NORMAL boot this runs in the BACKGROUND after
2621
2664
  // `localReadReady` resolves, so `createSyncClient` resolves at `localReadReady` (the Option B contract). On a
2622
2665
  // restore boot recovery already ran in the core, so the tail only opens the (unused) gate and settles. It
@@ -3178,7 +3221,10 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3178
3221
  start: async () => {
3179
3222
  await ready;
3180
3223
  },
3224
+ haltActivity,
3181
3225
  stop: async () => {
3226
+ // Halt all activity FIRST (see haltActivity) — before any await.
3227
+ haltActivity();
3182
3228
  // ADR-0041: quiesce the background boot tail FIRST — flag disposal (so it never starts sync after this)
3183
3229
  // and await its settlement — so no shape stream is left running and nothing execs against the closing
3184
3230
  // PGlite. Any sync the tail started before disposal is now in `sync` for the unsubscribe below.
@@ -3204,6 +3250,8 @@ export async function createSyncClient<const TRegistry extends SyncTableRegistry
3204
3250
  // LifecycleBusyError fires in both directions. The refuse-if-owed guard stays EXACTLY as it was, now
3205
3251
  // inside the slot run.
3206
3252
  lifecycleSlot.run("destroy", async () => {
3253
+ // Halt all activity FIRST (see haltActivity) — before any await.
3254
+ haltActivity();
3207
3255
  // ADR-0041: quiesce the background boot tail BEFORE the owed-mutations read and the wipe, so neither
3208
3256
  // races the tail's recovery journal updates / sync start (BLOCKER 2). After this the tail has settled.
3209
3257
  await quiesceTailForTeardown();
package/src/mutation.ts CHANGED
@@ -379,6 +379,12 @@ export interface MutationRuntime<TRegistry extends SyncTableRegistry> {
379
379
  */
380
380
  flushUnit: (unitId: string) => Promise<{ acks: MutationAck[] }>;
381
381
  reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;
382
+ /**
383
+ * Fire the runtime's dispose signal: abort every in-flight write-path fetch AND unblock any await parked on
384
+ * a stalled getAuthToken(). Called FIRST by the client's stop()/destroy() so teardown halts all write-network
385
+ * activity before it awaits the convergence pass. Idempotent; a disposed runtime performs no further network.
386
+ */
387
+ abortInFlight: () => void;
382
388
  retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;
383
389
  recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;
384
390
  /**
@@ -508,6 +514,24 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
508
514
  const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);
509
515
  let flushQueue = Promise.resolve();
510
516
 
517
+ // Teardown halt (see stop()/destroy()): a disposed runtime stops ALL activity at once. The signal is
518
+ // fired once by abortInFlight() and never reset. Every write-path fetch rides it (aborting an in-flight
519
+ // POST), and every getAuthToken() await is raced against it — the board's getAuthToken calls
520
+ // supabase.auth.getSession(), which can stall on token refresh (see flushBatch), so a fetch signal alone
521
+ // would not release teardown. On abort, flush()/flushUnit() reject promptly and the convergence pass settles.
522
+ const disposeController = new AbortController();
523
+ // Reject a pending await the instant the runtime is disposed. Cleans up its listener so per-flush use never leaks.
524
+ const untilAborted = <T>(work: Promise<T>): Promise<T> => {
525
+ if (disposeController.signal.aborted) {
526
+ return Promise.reject(new DOMException("Mutation runtime disposed", "AbortError"));
527
+ }
528
+ return new Promise<T>((resolve, reject) => {
529
+ const onAbort = () => reject(new DOMException("Mutation runtime disposed", "AbortError"));
530
+ disposeController.signal.addEventListener("abort", onAbort, { once: true });
531
+ work.then(resolve, reject).finally(() => disposeController.signal.removeEventListener("abort", onAbort));
532
+ });
533
+ };
534
+
511
535
  // Whether pgxsinkit owns the local schema (and the `pgxsinkit_local_meta` table the durable
512
536
  // recovery-required marker lives in). A caller-owned PGlite boot sets this false, so the marker is never
513
537
  // touched and the SET/clear seams below are no-ops.
@@ -995,6 +1019,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
995
1019
  options.requestHeaders,
996
1020
  ensureRecoveryMarker,
997
1021
  markSendingScope,
1022
+ disposeController.signal,
998
1023
  );
999
1024
 
1000
1025
  processedCount = batchResult.processedCount;
@@ -1117,6 +1142,7 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1117
1142
  flushQueue = nextFlush.catch(() => undefined);
1118
1143
  await nextFlush;
1119
1144
  },
1145
+ abortInFlight: () => disposeController.abort(),
1120
1146
  flushUnit: async (unitId) => {
1121
1147
  const contexts = Object.values(tableContexts).filter((context): context is TableContext => context != null);
1122
1148
  const unitRows = await readUnitPendingRows(options.db, contexts, unitId);
@@ -1200,18 +1226,21 @@ export function createMutationRuntime<TRegistry extends SyncTableRegistry>(
1200
1226
  let acksByMutationId: Map<string, BatchMutationAck["acks"][number]>;
1201
1227
 
1202
1228
  try {
1203
- const authToken = await options.getAuthToken?.();
1229
+ const authToken = await untilAborted(Promise.resolve(options.getAuthToken?.()));
1204
1230
  let response = await fetch(url, {
1205
1231
  method: "POST",
1206
1232
  headers: buildRequestHeaders(authToken, options.requestHeaders),
1207
1233
  body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
1234
+ signal: disposeController.signal,
1208
1235
  });
1209
1236
 
1210
1237
  if ([401, 403].includes(response.status) && options.getAuthToken) {
1238
+ const retryToken = await untilAborted(Promise.resolve(options.getAuthToken()));
1211
1239
  response = await fetch(url, {
1212
1240
  method: "POST",
1213
- headers: buildRequestHeaders(await options.getAuthToken(), options.requestHeaders),
1241
+ headers: buildRequestHeaders(retryToken, options.requestHeaders),
1214
1242
  body: jsonStringifyPayload({ writeUnit: unitId, mutations }),
1243
+ signal: disposeController.signal,
1215
1244
  });
1216
1245
  }
1217
1246
 
@@ -2546,6 +2575,18 @@ async function readUnitPendingRows(
2546
2575
  return result.rows;
2547
2576
  }
2548
2577
 
2578
+ // Race a promise against an AbortSignal so a disposed runtime's teardown never parks on it (mirrors
2579
+ // createMutationRuntime's untilAborted; used by the module-level flushBatch). A missing signal is a passthrough.
2580
+ function raceAbort<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
2581
+ if (!signal) return work;
2582
+ if (signal.aborted) return Promise.reject(new DOMException("Mutation runtime disposed", "AbortError"));
2583
+ return new Promise<T>((resolve, reject) => {
2584
+ const onAbort = () => reject(new DOMException("Mutation runtime disposed", "AbortError"));
2585
+ signal.addEventListener("abort", onAbort, { once: true });
2586
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
2587
+ });
2588
+ }
2589
+
2549
2590
  async function flushBatch(
2550
2591
  db: MutationDb,
2551
2592
  tableContexts: Record<string, TableContext>,
@@ -2557,6 +2598,7 @@ async function flushBatch(
2557
2598
  requestHeaders?: Record<string, string>,
2558
2599
  ensureRecoveryMarker?: () => Promise<void>,
2559
2600
  markSendingScope?: MarkSendingScope,
2601
+ signal?: AbortSignal,
2560
2602
  ): Promise<FlushBatchResult> {
2561
2603
  const contexts = filterContexts(tableContexts, tableFilter);
2562
2604
  const nowUs = nowMicroseconds();
@@ -2671,7 +2713,7 @@ async function flushBatch(
2671
2713
  // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise
2672
2714
  // be invisibly folded into "the write was slow".
2673
2715
  const authStart = typeof performance !== "undefined" ? performance.now() : Date.now();
2674
- const authToken = await getAuthToken?.();
2716
+ const authToken = await raceAbort(getAuthToken?.() ?? Promise.resolve(undefined), signal);
2675
2717
  const fetchStart = typeof performance !== "undefined" ? performance.now() : Date.now();
2676
2718
  syncDebug("board-write auth token resolved", { ms: Math.round(fetchStart - authStart) });
2677
2719
 
@@ -2679,13 +2721,15 @@ async function flushBatch(
2679
2721
  method: "POST",
2680
2722
  headers: buildRequestHeaders(authToken, requestHeaders),
2681
2723
  body: jsonStringifyPayload({ mutations }),
2724
+ signal: signal ?? null,
2682
2725
  });
2683
2726
 
2684
2727
  if ([401, 403].includes(response.status) && getAuthToken) {
2685
2728
  response = await fetch(batchMutationUrl, {
2686
2729
  method: "POST",
2687
- headers: buildRequestHeaders(await getAuthToken(), requestHeaders),
2730
+ headers: buildRequestHeaders(await raceAbort(getAuthToken(), signal), requestHeaders),
2688
2731
  body: jsonStringifyPayload({ mutations }),
2732
+ signal: signal ?? null,
2689
2733
  });
2690
2734
  }
2691
2735