@aglyn/tenant-feature-instance 1.15.2 → 1.17.0

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.
@@ -0,0 +1,545 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { disableNetwork, enableNetwork } from "firebase/firestore";
18
+ import { openExisting, PRIMARY_LEASE_MAX_AGE_MS, readSharedClientIds } from "./firestore-tab-handoff.js";
19
+ /**
20
+ * A BACKGROUND TAB HANDS THE SHARED CACHE TO THE TAB THE USER IS LOOKING AT
21
+ * (AGL-4204).
22
+ *
23
+ * ## What it fixes
24
+ *
25
+ * With `persistentMultipleTabManager` one tab, the lease holder, does every
26
+ * tab's network and most of their IndexedDB work, and every SDK transaction
27
+ * locks every store. The SDK never moves a LIVE lease
28
+ * (`IndexedDbPersistence.canActAsPrimary`, `@firebase/firestore` 4.18.0):
29
+ * a holder whose lease is under 5 s old and whose network is on keeps it
30
+ * whatever its visibility, and a visible tab wins only on a lapse. A console
31
+ * tab left in the background therefore serves the tab the user is in for as
32
+ * long as it keeps renewing, from a renderer the browser runs at background
33
+ * priority. Measured in production on 2026-11-06: reads in other tabs waited
34
+ * 16.9 s, 18.9 s and 4.5 s behind a background holder within three minutes,
35
+ * and a lease went 23.7 s stale. The cache's size never moved in those
36
+ * stalls, so they were not LRU collection.
37
+ *
38
+ * `firestore-tab-handoff.ts` (AGL-3660) claims a LAPSED lease for a new
39
+ * visible tab at boot. It cannot take a live one: two primaries over one
40
+ * cache write tombstones (AGL-3788). This module covers the live case by
41
+ * having the HOLDER let go, through the SDK's own election.
42
+ *
43
+ * ## How
44
+ *
45
+ * - **The asker** (a visible, online tab on the durable multi-tab cache) reads
46
+ * the lease and the holder's row, read-only. When the lease is live, held
47
+ * by another tab, and that tab's own row says it is in the background, it
48
+ * posts `yield` on a `BroadcastChannel` named for this cache. It looks
49
+ * three times in its first 9 s, once it has been visible for
50
+ * {@link VISIBLE_DWELL_MS}, and
51
+ * every {@link RECHECK_MS} while it stays visible.
52
+ * - **The holder** knows its own client id (the one `firestore_clients_*` key
53
+ * that appeared while its client started, as in AGL-3660). On a `yield`
54
+ * naming it, while it is hidden and online, it rereads in one transaction:
55
+ * still the holder; the asker's row fresh, foreground and online; no write
56
+ * pending. Then `disableNetwork` → `enableNetwork`. With its network off,
57
+ * the SDK's election finds the asker a better candidate
58
+ * (`otherClientHasBetterNetworkState`) and releases the lease, after the
59
+ * disable has stopped its Watch and write streams, because the election
60
+ * is queued behind the disable. Re-enabled, it finds the lease vacant and
61
+ * a foreground candidate, so it stays secondary. It replies `yielded`.
62
+ * - **The asker** then cycles its own network. That cycle is invisible in a
63
+ * secondary (`syncEngineApplyOnlineStateChange` ignores its own remote
64
+ * store there), and the election it runs takes the vacant lease at once
65
+ * instead of on its next 4 s tick.
66
+ *
67
+ * ## Why it is safe
68
+ *
69
+ * - **Never two primaries.** The lease is only ever released by its holder
70
+ * and only ever taken vacant, both by the SDK's own code. Nothing here
71
+ * writes a lease.
72
+ * - **Never with a write in flight.** A new primary resends every
73
+ * unacknowledged batch, so the holder declines while `mutations` has a row,
74
+ * the same rule AGL-3660 follows.
75
+ * - **Never on a guess.** A tab that cannot tell which client it is (two tabs
76
+ * started together) never acts as holder. The asker's row must be younger
77
+ * than {@link ASKER_FRESH_MS}, or the SDK would not hand to it and the
78
+ * holder's cycle would only flicker its network.
79
+ * - **Rate-limited both ways**: one ask per {@link ASK_INTERVAL_MS}, one
80
+ * yield per {@link YIELD_INTERVAL_MS}. Switching between two console tabs
81
+ * moves the role at most that often.
82
+ * - **Every failure is the old behaviour.** No `BroadcastChannel`, no
83
+ * database, a store another tab has locked, any throw: nothing is posted
84
+ * or cycled, and the SDK's election runs as it always has.
85
+ */ /** How long a tab must stay visible before it asks for the role. */ export const VISIBLE_DWELL_MS = 3000;
86
+ /** How often a visible tab looks again while it stays visible. */ export const RECHECK_MS = 15000;
87
+ /**
88
+ * The looks after boot. The first comes once AGL-3660's claim has had its
89
+ * turn. The SDK writes a new tab's first row as hidden, and corrects it at
90
+ * its first 4 s tick (see `firestore-tab-handoff.ts`), so the first look
91
+ * often finds this tab "not ready". The later ones land after that tick. Each
92
+ * is a no-op once an ask has gone out (`ASK_INTERVAL_MS`) or the role has
93
+ * moved here.
94
+ */ export const BOOT_CHECK_DELAYS_MS = [
95
+ 2000,
96
+ 5000,
97
+ 9000
98
+ ];
99
+ /** At most one ask per this long from one tab. */ export const ASK_INTERVAL_MS = 15000;
100
+ /** At most one yield per this long from one tab. */ export const YIELD_INTERVAL_MS = 30000;
101
+ /**
102
+ * The asker's row must be at least this fresh. The SDK only hands the lease
103
+ * to a client renewed within `MAX_PRIMARY_ELIGIBLE_AGE_MS` (5 s); a visible
104
+ * tab renews every 4 s.
105
+ */ export const ASKER_FRESH_MS = 4500;
106
+ /** How long a read may wait to start before it counts as locked. */ export const READ_TIMEOUT_MS = 1500;
107
+ /**
108
+ * Whether the tab `selfId` should ask the holder to yield. Pure.
109
+ *
110
+ * A lapsed lease is left alone: the SDK's next election in a visible tab
111
+ * takes it, and AGL-3660 claims it at boot.
112
+ */ export function decideAsk(input) {
113
+ const { owner, holder, self, selfId, now } = input;
114
+ if (!owner) return {
115
+ ask: false,
116
+ reason: 'vacant'
117
+ };
118
+ if (owner.ownerId === selfId) return {
119
+ ask: false,
120
+ reason: 'self-holds'
121
+ };
122
+ if (now - owner.leaseTimestampMs >= PRIMARY_LEASE_MAX_AGE_MS) return {
123
+ ask: false,
124
+ reason: 'lease-lapsed'
125
+ };
126
+ if (!holder) return {
127
+ ask: false,
128
+ reason: 'holder-unknown'
129
+ };
130
+ if (holder.inForeground) return {
131
+ ask: false,
132
+ reason: 'holder-visible'
133
+ };
134
+ if (!self) return {
135
+ ask: false,
136
+ reason: 'self-unknown'
137
+ };
138
+ // The SDK hands only to a client that has recorded itself foreground and
139
+ // online; the first record a new tab writes says hidden (AGL-3660).
140
+ if (!self.inForeground || !self.networkEnabled) return {
141
+ ask: false,
142
+ reason: 'self-not-ready'
143
+ };
144
+ return {
145
+ ask: true,
146
+ holderId: owner.ownerId
147
+ };
148
+ }
149
+ /** Whether the holder `selfId` should let go for `asker`. Pure. */ export function decideYield(input) {
150
+ const { owner, asker, selfId, pendingWrites, now } = input;
151
+ if ((owner == null ? void 0 : owner.ownerId) !== selfId) return {
152
+ yield: false,
153
+ reason: 'not-holder'
154
+ };
155
+ if (pendingWrites > 0) return {
156
+ yield: false,
157
+ reason: 'pending-writes'
158
+ };
159
+ if (!asker) return {
160
+ yield: false,
161
+ reason: 'asker-unknown'
162
+ };
163
+ if (!asker.inForeground) return {
164
+ yield: false,
165
+ reason: 'asker-hidden'
166
+ };
167
+ if (!asker.networkEnabled) return {
168
+ yield: false,
169
+ reason: 'asker-offline'
170
+ };
171
+ if (now - asker.updateTimeMs > ASKER_FRESH_MS) return {
172
+ yield: false,
173
+ reason: 'asker-stale'
174
+ };
175
+ return {
176
+ yield: true
177
+ };
178
+ }
179
+ const OWNER_STORE = 'owner';
180
+ const OWNER_KEY = 'owner';
181
+ const CLIENT_METADATA_STORE = 'clientMetadata';
182
+ const MUTATIONS_STORE = 'mutations';
183
+ /**
184
+ * Reads the lease, the rows for `clientIds` (plus the holder's), and the
185
+ * pending-write count in one `readonly` transaction. Gives up when the
186
+ * transaction cannot start within `timeoutMs`: a store another tab holds is
187
+ * the AGL-3428 wedge, which `firestore-multitab-wedge.ts` handles.
188
+ */ export async function readLease(factory, databaseName, clientIds, { timeoutMs = READ_TIMEOUT_MS } = {}) {
189
+ if (!factory) return {
190
+ state: 'unavailable'
191
+ };
192
+ const database = await openExisting(factory, databaseName).catch(()=>undefined);
193
+ if (!database) return {
194
+ state: 'unavailable'
195
+ };
196
+ const stores = [
197
+ OWNER_STORE,
198
+ CLIENT_METADATA_STORE,
199
+ MUTATIONS_STORE
200
+ ];
201
+ if (!stores.every((store)=>database.objectStoreNames.contains(store))) {
202
+ database.close();
203
+ return {
204
+ state: 'unavailable'
205
+ };
206
+ }
207
+ return new Promise((resolve)=>{
208
+ let transaction;
209
+ try {
210
+ transaction = database.transaction(stores, 'readonly');
211
+ } catch (unused) {
212
+ database.close();
213
+ resolve({
214
+ state: 'unavailable'
215
+ });
216
+ return;
217
+ }
218
+ let settled = false;
219
+ let started = false;
220
+ let result = {
221
+ state: 'unavailable'
222
+ };
223
+ const finish = (value)=>{
224
+ if (settled) return;
225
+ settled = true;
226
+ clearTimeout(timer);
227
+ database.close();
228
+ resolve(value);
229
+ };
230
+ const timer = setTimeout(()=>{
231
+ if (started) return;
232
+ try {
233
+ transaction.abort();
234
+ } catch (unused) {
235
+ // Already finished.
236
+ }
237
+ finish({
238
+ state: 'locked'
239
+ });
240
+ }, timeoutMs);
241
+ transaction.oncomplete = ()=>finish(result);
242
+ transaction.onabort = ()=>finish(started ? {
243
+ state: 'unavailable'
244
+ } : {
245
+ state: 'locked'
246
+ });
247
+ transaction.onerror = ()=>finish({
248
+ state: 'unavailable'
249
+ });
250
+ const clients = transaction.objectStore(CLIENT_METADATA_STORE);
251
+ const ownerRequest = transaction.objectStore(OWNER_STORE).get(OWNER_KEY);
252
+ ownerRequest.onsuccess = ()=>{
253
+ started = true;
254
+ const owner = ownerRequest.result;
255
+ const ids = [
256
+ ...new Set([
257
+ ...clientIds,
258
+ owner == null ? void 0 : owner.ownerId
259
+ ].filter(Boolean))
260
+ ];
261
+ const requests = ids.map((id)=>[
262
+ id,
263
+ clients.get(id)
264
+ ]);
265
+ const countRequest = transaction.objectStore(MUTATIONS_STORE).count();
266
+ countRequest.onsuccess = ()=>{
267
+ // Requests in one transaction complete in order: every get landed.
268
+ const rows = {};
269
+ for (const [id, request] of requests)rows[id] = request.result;
270
+ result = {
271
+ state: 'read',
272
+ owner,
273
+ rows,
274
+ pendingWrites: countRequest.result
275
+ };
276
+ };
277
+ };
278
+ });
279
+ }
280
+ /**
281
+ * Both halves of the handoff for one tab, with the browser parts injected.
282
+ * Neither method ever rejects.
283
+ */ export function createPrimaryYield(deps) {
284
+ let lastAskAt = Number.NEGATIVE_INFINITY;
285
+ let lastYieldAt = Number.NEGATIVE_INFINITY;
286
+ let busy = false;
287
+ // Looks can overlap (a boot look, the dwell look and the recheck): only
288
+ // one reads at a time, so the throttle sees the ask the first one made.
289
+ let looking = false;
290
+ const emit = (event)=>{
291
+ deps.onEvent == null ? void 0 : deps.onEvent.call(deps, event);
292
+ return event;
293
+ };
294
+ /** A visible tab's look: ask the holder to yield when it should. */ async function check() {
295
+ try {
296
+ if (!deps.isVisible() || !deps.isOnline()) return emit({
297
+ side: 'asker',
298
+ result: 'skipped',
299
+ reason: 'self-not-ready'
300
+ });
301
+ if (looking || deps.now() - lastAskAt < ASK_INTERVAL_MS) return emit({
302
+ side: 'asker',
303
+ result: 'skipped',
304
+ reason: 'throttled'
305
+ });
306
+ looking = true;
307
+ try {
308
+ return await look();
309
+ } finally{
310
+ looking = false;
311
+ }
312
+ } catch (unused) {
313
+ return emit({
314
+ side: 'asker',
315
+ result: 'error'
316
+ });
317
+ }
318
+ }
319
+ /** One read and, when it says so, one ask. */ async function look() {
320
+ const read = await deps.read([
321
+ deps.selfId
322
+ ]);
323
+ if (read.state !== 'read') return emit({
324
+ side: 'asker',
325
+ result: 'skipped',
326
+ reason: read.state
327
+ });
328
+ const decision = decideAsk({
329
+ owner: read.owner,
330
+ holder: read.owner ? read.rows[read.owner.ownerId] : undefined,
331
+ self: read.rows[deps.selfId],
332
+ selfId: deps.selfId,
333
+ now: deps.now()
334
+ });
335
+ if ('reason' in decision) return emit({
336
+ side: 'asker',
337
+ result: 'skipped',
338
+ reason: decision.reason
339
+ });
340
+ // Hidden or offline since the read: the SDK would not hand to us.
341
+ if (!deps.isVisible() || !deps.isOnline()) return emit({
342
+ side: 'asker',
343
+ result: 'skipped',
344
+ reason: 'self-not-ready'
345
+ });
346
+ lastAskAt = deps.now();
347
+ deps.post({
348
+ type: 'yield',
349
+ holderId: decision.holderId,
350
+ askerId: deps.selfId
351
+ });
352
+ return emit({
353
+ side: 'asker',
354
+ result: 'asked',
355
+ holderId: decision.holderId
356
+ });
357
+ }
358
+ /** Both sides' message handler. */ async function receive(message) {
359
+ if (!message || typeof message !== 'object') return undefined;
360
+ const { type, holderId, askerId } = message;
361
+ if (typeof holderId !== 'string' || typeof askerId !== 'string') return undefined;
362
+ try {
363
+ if (type === 'yielded' && askerId === deps.selfId) {
364
+ // The holder let go: run our election now, not on the next tick.
365
+ if (!deps.isVisible() || !deps.isOnline()) return undefined;
366
+ await deps.cycleNetwork();
367
+ return emit({
368
+ side: 'asker',
369
+ result: 'took-over',
370
+ fromId: holderId
371
+ });
372
+ }
373
+ if (type !== 'yield' || holderId !== deps.selfId) return undefined;
374
+ if (deps.isVisible()) return emit({
375
+ side: 'holder',
376
+ result: 'skipped',
377
+ reason: 'visible'
378
+ });
379
+ if (!deps.isOnline()) return emit({
380
+ side: 'holder',
381
+ result: 'skipped',
382
+ reason: 'offline'
383
+ });
384
+ if (busy || deps.now() - lastYieldAt < YIELD_INTERVAL_MS) return emit({
385
+ side: 'holder',
386
+ result: 'skipped',
387
+ reason: 'throttled'
388
+ });
389
+ busy = true;
390
+ try {
391
+ const read = await deps.read([
392
+ askerId
393
+ ]);
394
+ if (read.state !== 'read') return emit({
395
+ side: 'holder',
396
+ result: 'skipped',
397
+ reason: read.state
398
+ });
399
+ const decision = decideYield({
400
+ owner: read.owner,
401
+ asker: read.rows[askerId],
402
+ selfId: deps.selfId,
403
+ pendingWrites: read.pendingWrites,
404
+ now: deps.now()
405
+ });
406
+ if ('reason' in decision) return emit({
407
+ side: 'holder',
408
+ result: 'skipped',
409
+ reason: decision.reason
410
+ });
411
+ // Shown again while we read: keep the role, the user is here now.
412
+ if (deps.isVisible()) return emit({
413
+ side: 'holder',
414
+ result: 'skipped',
415
+ reason: 'visible'
416
+ });
417
+ lastYieldAt = deps.now();
418
+ await deps.cycleNetwork();
419
+ deps.post({
420
+ type: 'yielded',
421
+ holderId: deps.selfId,
422
+ askerId
423
+ });
424
+ return emit({
425
+ side: 'holder',
426
+ result: 'yielded',
427
+ askerId
428
+ });
429
+ } finally{
430
+ busy = false;
431
+ }
432
+ } catch (unused) {
433
+ return emit({
434
+ side: type === 'yielded' ? 'asker' : 'holder',
435
+ result: 'error'
436
+ });
437
+ }
438
+ }
439
+ return {
440
+ check,
441
+ receive
442
+ };
443
+ }
444
+ /**
445
+ * Identifies this tab's client, then wires the asker's looks and the
446
+ * holder's handler. Never rejects.
447
+ */ export async function runPrimaryYield(browser) {
448
+ try {
449
+ // Before this tab's Firestore starts, or this tab would be in it.
450
+ const before = browser.readClientIds();
451
+ const channel = browser.openChannel();
452
+ if (!channel) return {
453
+ started: false,
454
+ reason: 'no-channel'
455
+ };
456
+ await browser.startClient();
457
+ const added = [
458
+ ...browser.readClientIds()
459
+ ].filter((id)=>!before.has(id));
460
+ // Exactly one new client is this tab; anything else cannot be told apart.
461
+ if (added.length !== 1) return {
462
+ started: false,
463
+ reason: 'unidentified'
464
+ };
465
+ const selfId = added[0];
466
+ const handoff = createPrimaryYield(_extends({}, browser.factory, {
467
+ selfId,
468
+ post: channel.post
469
+ }));
470
+ channel.listen((message)=>void handoff.receive(message));
471
+ for (const delay of BOOT_CHECK_DELAYS_MS)browser.setTimer(()=>{
472
+ if (browser.factory.isVisible()) void handoff.check();
473
+ }, delay);
474
+ browser.onVisible(()=>browser.setTimer(()=>{
475
+ if (browser.factory.isVisible()) void handoff.check();
476
+ }, VISIBLE_DWELL_MS));
477
+ browser.setRepeating(()=>{
478
+ if (browser.factory.isVisible()) void handoff.check();
479
+ }, RECHECK_MS);
480
+ return {
481
+ started: true,
482
+ selfId
483
+ };
484
+ } catch (unused) {
485
+ return {
486
+ started: false,
487
+ reason: 'error'
488
+ };
489
+ }
490
+ }
491
+ /**
492
+ * Starts the handoff for a Firestore that `initializeFirestore` has just
493
+ * configured with the durable multi-tab cache under `prefix`. Call it in the
494
+ * same task as `initializeFirestore`, before any read: its first step is the
495
+ * synchronous snapshot of the clients that are not this tab.
496
+ */ export function startFirestorePrimaryYield(firestore, prefix) {
497
+ if (typeof window === 'undefined') return Promise.resolve({
498
+ started: false,
499
+ reason: 'no-channel'
500
+ });
501
+ let storage;
502
+ let factory;
503
+ try {
504
+ storage = window.localStorage;
505
+ factory = window.indexedDB;
506
+ } catch (unused) {
507
+ // Site data blocked: the snapshot reads nothing and nothing starts.
508
+ }
509
+ const databaseName = `${prefix}main`;
510
+ const isVisible = ()=>document.visibilityState === 'visible';
511
+ return runPrimaryYield({
512
+ readClientIds: ()=>readSharedClientIds(storage, prefix),
513
+ startClient: ()=>enableNetwork(firestore),
514
+ openChannel: ()=>{
515
+ if (typeof BroadcastChannel !== 'function') return undefined;
516
+ const channel = new BroadcastChannel(`aglyn:firestore-primary:${prefix}`);
517
+ return {
518
+ post: (message)=>channel.postMessage(message),
519
+ listen: (handler)=>{
520
+ channel.onmessage = (event)=>handler(event.data);
521
+ }
522
+ };
523
+ },
524
+ onVisible: (handler)=>document.addEventListener('visibilitychange', ()=>{
525
+ if (isVisible()) handler();
526
+ }),
527
+ setTimer: (handler, ms)=>void setTimeout(handler, ms),
528
+ setRepeating: (handler, ms)=>void setInterval(handler, ms),
529
+ factory: {
530
+ isVisible,
531
+ isOnline: ()=>navigator.onLine !== false,
532
+ now: Date.now,
533
+ read: (clientIds)=>readLease(factory, databaseName, clientIds),
534
+ cycleNetwork: async ()=>{
535
+ await disableNetwork(firestore);
536
+ await enableNetwork(firestore);
537
+ },
538
+ onEvent: (event)=>{
539
+ if (event.result === 'yielded' || event.result === 'took-over') console.debug('[firestore] Moved the shared cache to the visible tab (AGL-4204).', event);
540
+ }
541
+ }
542
+ });
543
+ }
544
+
545
+ //# sourceMappingURL=firestore-primary-yield.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-primary-yield.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\nimport {\n type ClientRow,\n type LeaseRow,\n openExisting,\n PRIMARY_LEASE_MAX_AGE_MS,\n readSharedClientIds,\n} from './firestore-tab-handoff'\n\n/**\n * A BACKGROUND TAB HANDS THE SHARED CACHE TO THE TAB THE USER IS LOOKING AT\n * (AGL-4204).\n *\n * ## What it fixes\n *\n * With `persistentMultipleTabManager` one tab, the lease holder, does every\n * tab's network and most of their IndexedDB work, and every SDK transaction\n * locks every store. The SDK never moves a LIVE lease\n * (`IndexedDbPersistence.canActAsPrimary`, `@firebase/firestore` 4.18.0):\n * a holder whose lease is under 5 s old and whose network is on keeps it\n * whatever its visibility, and a visible tab wins only on a lapse. A console\n * tab left in the background therefore serves the tab the user is in for as\n * long as it keeps renewing, from a renderer the browser runs at background\n * priority. Measured in production on 2026-11-06: reads in other tabs waited\n * 16.9 s, 18.9 s and 4.5 s behind a background holder within three minutes,\n * and a lease went 23.7 s stale. The cache's size never moved in those\n * stalls, so they were not LRU collection.\n *\n * `firestore-tab-handoff.ts` (AGL-3660) claims a LAPSED lease for a new\n * visible tab at boot. It cannot take a live one: two primaries over one\n * cache write tombstones (AGL-3788). This module covers the live case by\n * having the HOLDER let go, through the SDK's own election.\n *\n * ## How\n *\n * - **The asker** (a visible, online tab on the durable multi-tab cache) reads\n * the lease and the holder's row, read-only. When the lease is live, held\n * by another tab, and that tab's own row says it is in the background, it\n * posts `yield` on a `BroadcastChannel` named for this cache. It looks\n * three times in its first 9 s, once it has been visible for\n * {@link VISIBLE_DWELL_MS}, and\n * every {@link RECHECK_MS} while it stays visible.\n * - **The holder** knows its own client id (the one `firestore_clients_*` key\n * that appeared while its client started, as in AGL-3660). On a `yield`\n * naming it, while it is hidden and online, it rereads in one transaction:\n * still the holder; the asker's row fresh, foreground and online; no write\n * pending. Then `disableNetwork` → `enableNetwork`. With its network off,\n * the SDK's election finds the asker a better candidate\n * (`otherClientHasBetterNetworkState`) and releases the lease, after the\n * disable has stopped its Watch and write streams, because the election\n * is queued behind the disable. Re-enabled, it finds the lease vacant and\n * a foreground candidate, so it stays secondary. It replies `yielded`.\n * - **The asker** then cycles its own network. That cycle is invisible in a\n * secondary (`syncEngineApplyOnlineStateChange` ignores its own remote\n * store there), and the election it runs takes the vacant lease at once\n * instead of on its next 4 s tick.\n *\n * ## Why it is safe\n *\n * - **Never two primaries.** The lease is only ever released by its holder\n * and only ever taken vacant, both by the SDK's own code. Nothing here\n * writes a lease.\n * - **Never with a write in flight.** A new primary resends every\n * unacknowledged batch, so the holder declines while `mutations` has a row,\n * the same rule AGL-3660 follows.\n * - **Never on a guess.** A tab that cannot tell which client it is (two tabs\n * started together) never acts as holder. The asker's row must be younger\n * than {@link ASKER_FRESH_MS}, or the SDK would not hand to it and the\n * holder's cycle would only flicker its network.\n * - **Rate-limited both ways**: one ask per {@link ASK_INTERVAL_MS}, one\n * yield per {@link YIELD_INTERVAL_MS}. Switching between two console tabs\n * moves the role at most that often.\n * - **Every failure is the old behaviour.** No `BroadcastChannel`, no\n * database, a store another tab has locked, any throw: nothing is posted\n * or cycled, and the SDK's election runs as it always has.\n */\n\n/** How long a tab must stay visible before it asks for the role. */\nexport const VISIBLE_DWELL_MS = 3_000\n\n/** How often a visible tab looks again while it stays visible. */\nexport const RECHECK_MS = 15_000\n\n/**\n * The looks after boot. The first comes once AGL-3660's claim has had its\n * turn. The SDK writes a new tab's first row as hidden, and corrects it at\n * its first 4 s tick (see `firestore-tab-handoff.ts`), so the first look\n * often finds this tab \"not ready\". The later ones land after that tick. Each\n * is a no-op once an ask has gone out (`ASK_INTERVAL_MS`) or the role has\n * moved here.\n */\nexport const BOOT_CHECK_DELAYS_MS = [2_000, 5_000, 9_000] as const\n\n/** At most one ask per this long from one tab. */\nexport const ASK_INTERVAL_MS = 15_000\n\n/** At most one yield per this long from one tab. */\nexport const YIELD_INTERVAL_MS = 30_000\n\n/**\n * The asker's row must be at least this fresh. The SDK only hands the lease\n * to a client renewed within `MAX_PRIMARY_ELIGIBLE_AGE_MS` (5 s); a visible\n * tab renews every 4 s.\n */\nexport const ASKER_FRESH_MS = 4_500\n\n/** How long a read may wait to start before it counts as locked. */\nexport const READ_TIMEOUT_MS = 1_500\n\nexport type YieldMessage =\n | { type: 'yield'; holderId: string; askerId: string }\n | { type: 'yielded'; holderId: string; askerId: string }\n\n/** Why a visible tab did not ask. */\nexport type AskSkip =\n | 'vacant'\n | 'self-holds'\n | 'holder-unknown'\n | 'holder-visible'\n | 'lease-lapsed'\n | 'self-unknown'\n | 'self-not-ready'\n\nexport type AskDecision =\n { ask: true; holderId: string } | { ask: false; reason: AskSkip }\n\n/**\n * Whether the tab `selfId` should ask the holder to yield. Pure.\n *\n * A lapsed lease is left alone: the SDK's next election in a visible tab\n * takes it, and AGL-3660 claims it at boot.\n */\nexport function decideAsk(input: {\n owner: LeaseRow | undefined\n holder: ClientRow | undefined\n self: ClientRow | undefined\n selfId: string\n now: number\n}): AskDecision {\n const { owner, holder, self, selfId, now } = input\n if (!owner) return { ask: false, reason: 'vacant' }\n if (owner.ownerId === selfId) return { ask: false, reason: 'self-holds' }\n if (now - owner.leaseTimestampMs >= PRIMARY_LEASE_MAX_AGE_MS)\n return { ask: false, reason: 'lease-lapsed' }\n if (!holder) return { ask: false, reason: 'holder-unknown' }\n if (holder.inForeground) return { ask: false, reason: 'holder-visible' }\n if (!self) return { ask: false, reason: 'self-unknown' }\n // The SDK hands only to a client that has recorded itself foreground and\n // online; the first record a new tab writes says hidden (AGL-3660).\n if (!self.inForeground || !self.networkEnabled)\n return { ask: false, reason: 'self-not-ready' }\n return { ask: true, holderId: owner.ownerId }\n}\n\n/** Why the holder did not yield. */\nexport type YieldSkip =\n | 'not-holder'\n | 'asker-unknown'\n | 'asker-stale'\n | 'asker-hidden'\n | 'asker-offline'\n | 'pending-writes'\n\nexport type YieldDecision =\n { yield: true } | { yield: false; reason: YieldSkip }\n\n/** Whether the holder `selfId` should let go for `asker`. Pure. */\nexport function decideYield(input: {\n owner: LeaseRow | undefined\n asker: ClientRow | undefined\n selfId: string\n pendingWrites: number\n now: number\n}): YieldDecision {\n const { owner, asker, selfId, pendingWrites, now } = input\n if (owner?.ownerId !== selfId) return { yield: false, reason: 'not-holder' }\n if (pendingWrites > 0) return { yield: false, reason: 'pending-writes' }\n if (!asker) return { yield: false, reason: 'asker-unknown' }\n if (!asker.inForeground) return { yield: false, reason: 'asker-hidden' }\n if (!asker.networkEnabled) return { yield: false, reason: 'asker-offline' }\n if (now - asker.updateTimeMs > ASKER_FRESH_MS)\n return { yield: false, reason: 'asker-stale' }\n return { yield: true }\n}\n\n/** One read-only look at the lease, two client rows and the write queue. */\nexport type LeaseRead =\n | {\n state: 'read'\n owner: LeaseRow | undefined\n rows: Record<string, ClientRow | undefined>\n pendingWrites: number\n }\n | { state: 'locked' }\n | { state: 'unavailable' }\n\nconst OWNER_STORE = 'owner'\nconst OWNER_KEY = 'owner'\nconst CLIENT_METADATA_STORE = 'clientMetadata'\nconst MUTATIONS_STORE = 'mutations'\n\n/**\n * Reads the lease, the rows for `clientIds` (plus the holder's), and the\n * pending-write count in one `readonly` transaction. Gives up when the\n * transaction cannot start within `timeoutMs`: a store another tab holds is\n * the AGL-3428 wedge, which `firestore-multitab-wedge.ts` handles.\n */\nexport async function readLease(\n factory: IDBFactory | undefined,\n databaseName: string,\n clientIds: string[],\n { timeoutMs = READ_TIMEOUT_MS }: { timeoutMs?: number } = {},\n): Promise<LeaseRead> {\n if (!factory) return { state: 'unavailable' }\n const database = await openExisting(factory, databaseName).catch(\n () => undefined,\n )\n if (!database) return { state: 'unavailable' }\n const stores = [OWNER_STORE, CLIENT_METADATA_STORE, MUTATIONS_STORE]\n if (!stores.every((store) => database.objectStoreNames.contains(store))) {\n database.close()\n return { state: 'unavailable' }\n }\n return new Promise<LeaseRead>((resolve) => {\n let transaction: IDBTransaction\n try {\n transaction = database.transaction(stores, 'readonly')\n } catch {\n database.close()\n resolve({ state: 'unavailable' })\n return\n }\n let settled = false\n let started = false\n let result: LeaseRead = { state: 'unavailable' }\n const finish = (value: LeaseRead) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n database.close()\n resolve(value)\n }\n const timer = setTimeout(() => {\n if (started) return\n try {\n transaction.abort()\n } catch {\n // Already finished.\n }\n finish({ state: 'locked' })\n }, timeoutMs)\n transaction.oncomplete = () => finish(result)\n transaction.onabort = () =>\n finish(started ? { state: 'unavailable' } : { state: 'locked' })\n transaction.onerror = () => finish({ state: 'unavailable' })\n\n const clients = transaction.objectStore(CLIENT_METADATA_STORE)\n const ownerRequest = transaction.objectStore(OWNER_STORE).get(OWNER_KEY)\n ownerRequest.onsuccess = () => {\n started = true\n const owner = ownerRequest.result as LeaseRow | undefined\n const ids = [...new Set([...clientIds, owner?.ownerId].filter(Boolean))]\n const requests = ids.map((id) => [id, clients.get(id!)] as const)\n const countRequest = transaction.objectStore(MUTATIONS_STORE).count()\n countRequest.onsuccess = () => {\n // Requests in one transaction complete in order: every get landed.\n const rows: Record<string, ClientRow | undefined> = {}\n for (const [id, request] of requests)\n rows[id!] = request.result as ClientRow | undefined\n result = {\n state: 'read',\n owner,\n rows,\n pendingWrites: countRequest.result,\n }\n }\n }\n })\n}\n\n/** What one look or one message did, for the debug log and the specs. */\nexport type YieldEvent =\n | { side: 'asker'; result: 'asked'; holderId: string }\n | {\n side: 'asker'\n result: 'skipped'\n reason: AskSkip | 'locked' | 'unavailable' | 'throttled'\n }\n | { side: 'asker'; result: 'took-over'; fromId: string }\n | { side: 'holder'; result: 'yielded'; askerId: string }\n | {\n side: 'holder'\n result: 'skipped'\n reason:\n | YieldSkip\n | 'visible'\n | 'offline'\n | 'locked'\n | 'unavailable'\n | 'throttled'\n }\n | { side: 'holder' | 'asker'; result: 'error' }\n\nexport interface PrimaryYieldDeps {\n selfId: string\n isVisible: () => boolean\n isOnline: () => boolean\n now: () => number\n read: (clientIds: string[]) => Promise<LeaseRead>\n post: (message: YieldMessage) => void\n /** `disableNetwork` then `enableNetwork`: two elections, at once. */\n cycleNetwork: () => Promise<void>\n onEvent?: (event: YieldEvent) => void\n}\n\n/**\n * Both halves of the handoff for one tab, with the browser parts injected.\n * Neither method ever rejects.\n */\nexport function createPrimaryYield(deps: PrimaryYieldDeps) {\n let lastAskAt = Number.NEGATIVE_INFINITY\n let lastYieldAt = Number.NEGATIVE_INFINITY\n let busy = false\n // Looks can overlap (a boot look, the dwell look and the recheck): only\n // one reads at a time, so the throttle sees the ask the first one made.\n let looking = false\n const emit = (event: YieldEvent) => {\n deps.onEvent?.(event)\n return event\n }\n\n /** A visible tab's look: ask the holder to yield when it should. */\n async function check(): Promise<YieldEvent> {\n try {\n if (!deps.isVisible() || !deps.isOnline())\n return emit({\n side: 'asker',\n result: 'skipped',\n reason: 'self-not-ready',\n })\n if (looking || deps.now() - lastAskAt < ASK_INTERVAL_MS)\n return emit({ side: 'asker', result: 'skipped', reason: 'throttled' })\n looking = true\n try {\n return await look()\n } finally {\n looking = false\n }\n } catch {\n return emit({ side: 'asker', result: 'error' })\n }\n }\n\n /** One read and, when it says so, one ask. */\n async function look(): Promise<YieldEvent> {\n const read = await deps.read([deps.selfId])\n if (read.state !== 'read')\n return emit({ side: 'asker', result: 'skipped', reason: read.state })\n const decision = decideAsk({\n owner: read.owner,\n holder: read.owner ? read.rows[read.owner.ownerId] : undefined,\n self: read.rows[deps.selfId],\n selfId: deps.selfId,\n now: deps.now(),\n })\n if ('reason' in decision)\n return emit({ side: 'asker', result: 'skipped', reason: decision.reason })\n // Hidden or offline since the read: the SDK would not hand to us.\n if (!deps.isVisible() || !deps.isOnline())\n return emit({\n side: 'asker',\n result: 'skipped',\n reason: 'self-not-ready',\n })\n lastAskAt = deps.now()\n deps.post({\n type: 'yield',\n holderId: decision.holderId,\n askerId: deps.selfId,\n })\n return emit({ side: 'asker', result: 'asked', holderId: decision.holderId })\n }\n\n /** Both sides' message handler. */\n async function receive(message: unknown): Promise<YieldEvent | undefined> {\n if (!message || typeof message !== 'object') return undefined\n const { type, holderId, askerId } = message as Partial<YieldMessage>\n if (typeof holderId !== 'string' || typeof askerId !== 'string')\n return undefined\n try {\n if (type === 'yielded' && askerId === deps.selfId) {\n // The holder let go: run our election now, not on the next tick.\n if (!deps.isVisible() || !deps.isOnline()) return undefined\n await deps.cycleNetwork()\n return emit({ side: 'asker', result: 'took-over', fromId: holderId })\n }\n if (type !== 'yield' || holderId !== deps.selfId) return undefined\n if (deps.isVisible())\n return emit({ side: 'holder', result: 'skipped', reason: 'visible' })\n if (!deps.isOnline())\n return emit({ side: 'holder', result: 'skipped', reason: 'offline' })\n if (busy || deps.now() - lastYieldAt < YIELD_INTERVAL_MS)\n return emit({ side: 'holder', result: 'skipped', reason: 'throttled' })\n busy = true\n try {\n const read = await deps.read([askerId])\n if (read.state !== 'read')\n return emit({ side: 'holder', result: 'skipped', reason: read.state })\n const decision = decideYield({\n owner: read.owner,\n asker: read.rows[askerId],\n selfId: deps.selfId,\n pendingWrites: read.pendingWrites,\n now: deps.now(),\n })\n if ('reason' in decision)\n return emit({\n side: 'holder',\n result: 'skipped',\n reason: decision.reason,\n })\n // Shown again while we read: keep the role, the user is here now.\n if (deps.isVisible())\n return emit({ side: 'holder', result: 'skipped', reason: 'visible' })\n lastYieldAt = deps.now()\n await deps.cycleNetwork()\n deps.post({ type: 'yielded', holderId: deps.selfId, askerId })\n return emit({ side: 'holder', result: 'yielded', askerId })\n } finally {\n busy = false\n }\n } catch {\n return emit({\n side: type === 'yielded' ? 'asker' : 'holder',\n result: 'error',\n })\n }\n }\n\n return { check, receive }\n}\n\n/** What started, for the specs. */\nexport type PrimaryYieldStart =\n | { started: true; selfId: string }\n | { started: false; reason: 'no-channel' | 'unidentified' | 'error' }\n\nexport interface PrimaryYieldBrowser {\n /** Synchronous: the first call is the snapshot before this client starts. */\n readClientIds: () => ReadonlySet<string>\n startClient: () => Promise<void>\n openChannel: () =>\n | {\n post: (message: YieldMessage) => void\n listen: (handler: (message: unknown) => void) => void\n }\n | undefined\n onVisible: (handler: () => void) => void\n setTimer: (handler: () => void, ms: number) => void\n setRepeating: (handler: () => void, ms: number) => void\n factory: Omit<PrimaryYieldDeps, 'selfId' | 'post'>\n}\n\n/**\n * Identifies this tab's client, then wires the asker's looks and the\n * holder's handler. Never rejects.\n */\nexport async function runPrimaryYield(\n browser: PrimaryYieldBrowser,\n): Promise<PrimaryYieldStart> {\n try {\n // Before this tab's Firestore starts, or this tab would be in it.\n const before = browser.readClientIds()\n const channel = browser.openChannel()\n if (!channel) return { started: false, reason: 'no-channel' }\n await browser.startClient()\n const added = [...browser.readClientIds()].filter((id) => !before.has(id))\n // Exactly one new client is this tab; anything else cannot be told apart.\n if (added.length !== 1) return { started: false, reason: 'unidentified' }\n const selfId = added[0]\n const handoff = createPrimaryYield({\n ...browser.factory,\n selfId,\n post: channel.post,\n })\n channel.listen((message) => void handoff.receive(message))\n for (const delay of BOOT_CHECK_DELAYS_MS)\n browser.setTimer(() => {\n if (browser.factory.isVisible()) void handoff.check()\n }, delay)\n browser.onVisible(() =>\n browser.setTimer(() => {\n if (browser.factory.isVisible()) void handoff.check()\n }, VISIBLE_DWELL_MS),\n )\n browser.setRepeating(() => {\n if (browser.factory.isVisible()) void handoff.check()\n }, RECHECK_MS)\n return { started: true, selfId }\n } catch {\n return { started: false, reason: 'error' }\n }\n}\n\n/**\n * Starts the handoff for a Firestore that `initializeFirestore` has just\n * configured with the durable multi-tab cache under `prefix`. Call it in the\n * same task as `initializeFirestore`, before any read: its first step is the\n * synchronous snapshot of the clients that are not this tab.\n */\nexport function startFirestorePrimaryYield(\n firestore: Firestore,\n prefix: string,\n): Promise<PrimaryYieldStart> {\n if (typeof window === 'undefined')\n return Promise.resolve({ started: false, reason: 'no-channel' })\n let storage: Storage | undefined\n let factory: IDBFactory | undefined\n try {\n storage = window.localStorage\n factory = window.indexedDB\n } catch {\n // Site data blocked: the snapshot reads nothing and nothing starts.\n }\n const databaseName = `${prefix}main`\n const isVisible = () => document.visibilityState === 'visible'\n return runPrimaryYield({\n readClientIds: () => readSharedClientIds(storage, prefix),\n startClient: () => enableNetwork(firestore),\n openChannel: () => {\n if (typeof BroadcastChannel !== 'function') return undefined\n const channel = new BroadcastChannel(`aglyn:firestore-primary:${prefix}`)\n return {\n post: (message) => channel.postMessage(message),\n listen: (handler) => {\n channel.onmessage = (event) => handler(event.data)\n },\n }\n },\n onVisible: (handler) =>\n document.addEventListener('visibilitychange', () => {\n if (isVisible()) handler()\n }),\n setTimer: (handler, ms) => void setTimeout(handler, ms),\n setRepeating: (handler, ms) => void setInterval(handler, ms),\n factory: {\n isVisible,\n isOnline: () => navigator.onLine !== false,\n now: Date.now,\n read: (clientIds) => readLease(factory, databaseName, clientIds),\n cycleNetwork: async () => {\n await disableNetwork(firestore)\n await enableNetwork(firestore)\n },\n onEvent: (event) => {\n if (event.result === 'yielded' || event.result === 'took-over')\n console.debug(\n '[firestore] Moved the shared cache to the visible tab (AGL-4204).',\n event,\n )\n },\n },\n })\n}\n"],"names":["disableNetwork","enableNetwork","openExisting","PRIMARY_LEASE_MAX_AGE_MS","readSharedClientIds","VISIBLE_DWELL_MS","RECHECK_MS","BOOT_CHECK_DELAYS_MS","ASK_INTERVAL_MS","YIELD_INTERVAL_MS","ASKER_FRESH_MS","READ_TIMEOUT_MS","decideAsk","input","owner","holder","self","selfId","now","ask","reason","ownerId","leaseTimestampMs","inForeground","networkEnabled","holderId","decideYield","asker","pendingWrites","yield","updateTimeMs","OWNER_STORE","OWNER_KEY","CLIENT_METADATA_STORE","MUTATIONS_STORE","readLease","factory","databaseName","clientIds","timeoutMs","state","database","catch","undefined","stores","every","store","objectStoreNames","contains","close","Promise","resolve","transaction","settled","started","result","finish","value","clearTimeout","timer","setTimeout","abort","oncomplete","onabort","onerror","clients","objectStore","ownerRequest","get","onsuccess","ids","Set","filter","Boolean","requests","map","id","countRequest","count","rows","request","createPrimaryYield","deps","lastAskAt","Number","NEGATIVE_INFINITY","lastYieldAt","busy","looking","emit","event","onEvent","check","isVisible","isOnline","side","look","read","decision","post","type","askerId","receive","message","cycleNetwork","fromId","runPrimaryYield","browser","before","readClientIds","channel","openChannel","startClient","added","has","length","handoff","listen","delay","setTimer","onVisible","setRepeating","startFirestorePrimaryYield","firestore","prefix","window","storage","localStorage","indexedDB","document","visibilityState","BroadcastChannel","postMessage","handler","onmessage","data","addEventListener","ms","setInterval","navigator","onLine","Date","console","debug"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,aAAa,QAER,qBAAoB;AAC3B,SAGEC,YAAY,EACZC,wBAAwB,EACxBC,mBAAmB,QACd,6BAAyB;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkEC,GAED,kEAAkE,GAClE,OAAO,MAAMC,mBAAmB,KAAK;AAErC,gEAAgE,GAChE,OAAO,MAAMC,aAAa,MAAM;AAEhC;;;;;;;CAOC,GACD,OAAO,MAAMC,uBAAuB;IAAC;IAAO;IAAO;CAAM,CAAS;AAElE,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IAAI0G;IACJ,IAAI1F;IACJ,IAAI;QACF0F,UAAUD,OAAOE,YAAY;QAC7B3F,UAAUyF,OAAOG,SAAS;IAC5B,EAAE,eAAM;IACN,oEAAoE;IACtE;IACA,MAAM3F,eAAe,GAAGuF,OAAO,IAAI,CAAC;IACpC,MAAM/B,YAAY,IAAMoC,SAASC,eAAe,KAAK;IACrD,OAAOxB,gBAAgB;QACrBG,eAAe,IAAMzG,oBAAoB0H,SAASF;QAClDZ,aAAa,IAAM/G,cAAc0H;QACjCZ,aAAa;YACX,IAAI,OAAOoB,qBAAqB,YAAY,OAAOxF;YACnD,MAAMmE,UAAU,IAAIqB,iBAAiB,CAAC,wBAAwB,EAAEP,QAAQ;YACxE,OAAO;gBACLzB,MAAM,CAACI,UAAYO,QAAQsB,WAAW,CAAC7B;gBACvCc,QAAQ,CAACgB;oBACPvB,QAAQwB,SAAS,GAAG,CAAC5C,QAAU2C,QAAQ3C,MAAM6C,IAAI;gBACnD;YACF;QACF;QACAf,WAAW,CAACa,UACVJ,SAASO,gBAAgB,CAAC,oBAAoB;gBAC5C,IAAI3C,aAAawC;YACnB;QACFd,UAAU,CAACc,SAASI,KAAO,KAAK7E,WAAWyE,SAASI;QACpDhB,cAAc,CAACY,SAASI,KAAO,KAAKC,YAAYL,SAASI;QACzDrG,SAAS;YACPyD;YACAC,UAAU,IAAM6C,UAAUC,MAAM,KAAK;YACrC1H,KAAK2H,KAAK3H,GAAG;YACb+E,MAAM,CAAC3D,YAAcH,UAAUC,SAASC,cAAcC;YACtDkE,cAAc;gBACZ,MAAMxG,eAAe2H;gBACrB,MAAM1H,cAAc0H;YACtB;YACAhC,SAAS,CAACD;gBACR,IAAIA,MAAMnC,MAAM,KAAK,aAAamC,MAAMnC,MAAM,KAAK,aACjDuF,QAAQC,KAAK,CACX,qEACArD;YAEN;QACF;IACF;AACF"}
@@ -205,6 +205,12 @@ export interface TabHandoffDeps {
205
205
  * The boot handoff, with its browser parts injected. Never rejects.
206
206
  */
207
207
  export declare function runTabHandoff(deps: TabHandoffDeps): Promise<TabHandoffOutcome>;
208
+ /**
209
+ * Opens `databaseName` only if it already exists, at its current version —
210
+ * never creating it under the SDK (the rule `probePrimaryLease` follows) —
211
+ * and closes on `versionchange` so an SDK upgrade is never held up.
212
+ */
213
+ export declare function openExisting(factory: IDBFactory, databaseName: string): Promise<IDBDatabase | undefined>;
208
214
  /**
209
215
  * The client ids the SDK has registered under `prefix`
210
216
  * (`firestore/<app>/<project>/`), from its `firestore_clients_<prefix>_<id>`
@@ -243,7 +243,7 @@ const MUTATIONS_STORE = 'mutations';
243
243
  * Opens `databaseName` only if it already exists, at its current version —
244
244
  * never creating it under the SDK (the rule `probePrimaryLease` follows) —
245
245
  * and closes on `versionchange` so an SDK upgrade is never held up.
246
- */ async function openExisting(factory, databaseName) {
246
+ */ export async function openExisting(factory, databaseName) {
247
247
  if (typeof factory.databases !== 'function') return undefined;
248
248
  const databases = await factory.databases();
249
249
  if (!databases.some((database)=>database.name === databaseName)) return undefined;