@aglyn/tenant-feature-instance 1.20.0 → 1.20.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-feature-instance",
3
- "version": "1.20.0",
3
+ "version": "1.20.2",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.20.0",
29
- "@aglyn/shared-data-enums": "1.20.0",
30
- "@aglyn/shared-ui-jsx": "1.20.0",
31
- "@aglyn/shared-util-email": "1.20.0",
32
- "@aglyn/shared-util-http": "1.20.0",
33
- "@aglyn/shared-util-timestamp": "1.20.0",
28
+ "@aglyn/aglyn": "1.20.2",
29
+ "@aglyn/shared-data-enums": "1.20.2",
30
+ "@aglyn/shared-ui-jsx": "1.20.2",
31
+ "@aglyn/shared-util-email": "1.20.2",
32
+ "@aglyn/shared-util-http": "1.20.2",
33
+ "@aglyn/shared-util-timestamp": "1.20.2",
34
34
  "@swc/helpers": "0.5.23",
35
35
  "lodash-es": "^4.18.1",
36
36
  "mobx": "^7.0.5"
@@ -46,9 +46,13 @@ import { type ClientRow, type LeaseRow } from './firestore-tab-handoff';
46
46
  * the lease and the holder's row, read-only. When the lease is live, held
47
47
  * by another tab, and that tab's own row says it is in the background, it
48
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.
49
+ * as soon as its client has started and five more times in its first 10 s
50
+ * ({@link BOOT_CHECK_DELAYS_MS}), once it has been visible for
51
+ * {@link VISIBLE_DWELL_MS}, and every {@link RECHECK_MS} while it stays
52
+ * visible. When its own row still says hidden (the SDK writes a new tab's
53
+ * first row that way), it cycles its own network first, which rewrites
54
+ * the row from the visibility the SDK has read by then, instead of waiting
55
+ * for the SDK's 4 s tick.
52
56
  * - **The holder** knows its own client id (the one `firestore_clients_*` key
53
57
  * that appeared while its client started, as in AGL-3660). On a `yield`
54
58
  * naming it, while it is hidden and online, it rereads in one transaction:
@@ -76,9 +80,12 @@ import { type ClientRow, type LeaseRow } from './firestore-tab-handoff';
76
80
  * started together) never acts as holder. The asker's row must be younger
77
81
  * than {@link ASKER_FRESH_MS}, or the SDK would not hand to it and the
78
82
  * 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.
83
+ * - **Rate-limited both ways**: up to {@link ASK_BURST} asks
84
+ * {@link ASK_RETRY_MS} apart (an ask a background holder never answered,
85
+ * or answered while the asker's row was not yet fresh, is asked again),
86
+ * then one per {@link ASK_INTERVAL_MS}; one yield per
87
+ * {@link YIELD_INTERVAL_MS}. Switching between two console tabs moves the
88
+ * role at most that often.
82
89
  * - **Every failure is the old behaviour.** No `BroadcastChannel`, no
83
90
  * database, a store another tab has locked, any throw: nothing is posted
84
91
  * or cycled, and the SDK's election runs as it always has.
@@ -88,16 +95,29 @@ export declare const VISIBLE_DWELL_MS = 3000;
88
95
  /** How often a visible tab looks again while it stays visible. */
89
96
  export declare const RECHECK_MS = 15000;
90
97
  /**
91
- * The looks after boot. The first comes once AGL-3660's claim has had its
92
- * turn. The SDK writes a new tab's first row as hidden, and corrects it at
93
- * its first 4 s tick (see `firestore-tab-handoff.ts`), so the first look
94
- * often finds this tab "not ready". The later ones land after that tick. Each
95
- * is a no-op once an ask has gone out (`ASK_INTERVAL_MS`) or the role has
96
- * moved here.
98
+ * The looks after this tab's client has started. The first is immediate: a
99
+ * background holder costs a cold load 10-16 s (measured in production on
100
+ * 2026-11-10), and the first looks at 2, 5 and 9 s it replaced asked only
101
+ * on the third. The SDK writes a new tab's first row as hidden (see
102
+ * `firestore-tab-handoff.ts`), so a look that finds its own row not ready
103
+ * rewrites it with a network cycle ({@link REFRESH_INTERVAL_MS}) and asks
104
+ * once the rewrite has landed: in the same look, or in the next one a
105
+ * second later. The later looks cover a read that found the store
106
+ * locked and an ask the holder did not act on. Each is a no-op once the role
107
+ * has moved here.
97
108
  */
98
- export declare const BOOT_CHECK_DELAYS_MS: readonly [2000, 5000, 9000];
99
- /** At most one ask per this long from one tab. */
109
+ export declare const BOOT_CHECK_DELAYS_MS: readonly [0, 1000, 2500, 4500, 7000, 10000];
110
+ /** An unanswered ask may be repeated this soon, up to {@link ASK_BURST}. */
111
+ export declare const ASK_RETRY_MS = 3000;
112
+ /** Asks allowed {@link ASK_RETRY_MS} apart before the long interval. */
113
+ export declare const ASK_BURST = 3;
114
+ /** After a burst, at most one ask per this long from one tab. */
100
115
  export declare const ASK_INTERVAL_MS = 15000;
116
+ /**
117
+ * At most one rewrite of this tab's own row per this long: the SDK's own
118
+ * renewal tick, after which it would have rewritten the row anyway.
119
+ */
120
+ export declare const REFRESH_INTERVAL_MS = 4000;
101
121
  /** At most one yield per this long from one tab. */
102
122
  export declare const YIELD_INTERVAL_MS = 30000;
103
123
  /**
@@ -188,6 +208,9 @@ export type YieldEvent = {
188
208
  side: 'asker';
189
209
  result: 'took-over';
190
210
  fromId: string;
211
+ } | {
212
+ side: 'asker';
213
+ result: 'refreshed';
191
214
  } | {
192
215
  side: 'holder';
193
216
  result: 'yielded';
@@ -46,9 +46,13 @@ import { openExisting, PRIMARY_LEASE_MAX_AGE_MS, readSharedClientIds } from "./f
46
46
  * the lease and the holder's row, read-only. When the lease is live, held
47
47
  * by another tab, and that tab's own row says it is in the background, it
48
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.
49
+ * as soon as its client has started and five more times in its first 10 s
50
+ * ({@link BOOT_CHECK_DELAYS_MS}), once it has been visible for
51
+ * {@link VISIBLE_DWELL_MS}, and every {@link RECHECK_MS} while it stays
52
+ * visible. When its own row still says hidden (the SDK writes a new tab's
53
+ * first row that way), it cycles its own network first, which rewrites
54
+ * the row from the visibility the SDK has read by then, instead of waiting
55
+ * for the SDK's 4 s tick.
52
56
  * - **The holder** knows its own client id (the one `firestore_clients_*` key
53
57
  * that appeared while its client started, as in AGL-3660). On a `yield`
54
58
  * naming it, while it is hidden and online, it rereads in one transaction:
@@ -76,27 +80,43 @@ import { openExisting, PRIMARY_LEASE_MAX_AGE_MS, readSharedClientIds } from "./f
76
80
  * started together) never acts as holder. The asker's row must be younger
77
81
  * than {@link ASKER_FRESH_MS}, or the SDK would not hand to it and the
78
82
  * 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.
83
+ * - **Rate-limited both ways**: up to {@link ASK_BURST} asks
84
+ * {@link ASK_RETRY_MS} apart (an ask a background holder never answered,
85
+ * or answered while the asker's row was not yet fresh, is asked again),
86
+ * then one per {@link ASK_INTERVAL_MS}; one yield per
87
+ * {@link YIELD_INTERVAL_MS}. Switching between two console tabs moves the
88
+ * role at most that often.
82
89
  * - **Every failure is the old behaviour.** No `BroadcastChannel`, no
83
90
  * database, a store another tab has locked, any throw: nothing is posted
84
91
  * or cycled, and the SDK's election runs as it always has.
85
92
  */ /** How long a tab must stay visible before it asks for the role. */ export const VISIBLE_DWELL_MS = 3000;
86
93
  /** How often a visible tab looks again while it stays visible. */ export const RECHECK_MS = 15000;
87
94
  /**
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.
95
+ * The looks after this tab's client has started. The first is immediate: a
96
+ * background holder costs a cold load 10-16 s (measured in production on
97
+ * 2026-11-10), and the first looks at 2, 5 and 9 s it replaced asked only
98
+ * on the third. The SDK writes a new tab's first row as hidden (see
99
+ * `firestore-tab-handoff.ts`), so a look that finds its own row not ready
100
+ * rewrites it with a network cycle ({@link REFRESH_INTERVAL_MS}) and asks
101
+ * once the rewrite has landed: in the same look, or in the next one a
102
+ * second later. The later looks cover a read that found the store
103
+ * locked and an ask the holder did not act on. Each is a no-op once the role
104
+ * has moved here.
94
105
  */ export const BOOT_CHECK_DELAYS_MS = [
95
- 2000,
96
- 5000,
97
- 9000
106
+ 0,
107
+ 1000,
108
+ 2500,
109
+ 4500,
110
+ 7000,
111
+ 10000
98
112
  ];
99
- /** At most one ask per this long from one tab. */ export const ASK_INTERVAL_MS = 15000;
113
+ /** An unanswered ask may be repeated this soon, up to {@link ASK_BURST}. */ export const ASK_RETRY_MS = 3000;
114
+ /** Asks allowed {@link ASK_RETRY_MS} apart before the long interval. */ export const ASK_BURST = 3;
115
+ /** After a burst, at most one ask per this long from one tab. */ export const ASK_INTERVAL_MS = 15000;
116
+ /**
117
+ * At most one rewrite of this tab's own row per this long: the SDK's own
118
+ * renewal tick, after which it would have rewritten the row anyway.
119
+ */ export const REFRESH_INTERVAL_MS = 4000;
100
120
  /** At most one yield per this long from one tab. */ export const YIELD_INTERVAL_MS = 30000;
101
121
  /**
102
122
  * The asker's row must be at least this fresh. The SDK only hands the lease
@@ -282,6 +302,8 @@ const MUTATIONS_STORE = 'mutations';
282
302
  * Neither method ever rejects.
283
303
  */ export function createPrimaryYield(deps) {
284
304
  let lastAskAt = Number.NEGATIVE_INFINITY;
305
+ let asksInBurst = 0;
306
+ let lastRefreshAt = Number.NEGATIVE_INFINITY;
285
307
  let lastYieldAt = Number.NEGATIVE_INFINITY;
286
308
  let busy = false;
287
309
  // Looks can overlap (a boot look, the dwell look and the recheck): only
@@ -298,7 +320,7 @@ const MUTATIONS_STORE = 'mutations';
298
320
  result: 'skipped',
299
321
  reason: 'self-not-ready'
300
322
  });
301
- if (looking || deps.now() - lastAskAt < ASK_INTERVAL_MS) return emit({
323
+ if (looking || !mayAsk()) return emit({
302
324
  side: 'asker',
303
325
  result: 'skipped',
304
326
  reason: 'throttled'
@@ -316,15 +338,18 @@ const MUTATIONS_STORE = 'mutations';
316
338
  });
317
339
  }
318
340
  }
319
- /** One read and, when it says so, one ask. */ async function look() {
341
+ /** A short burst of asks, then the long interval. */ function mayAsk() {
342
+ const since = deps.now() - lastAskAt;
343
+ if (since >= ASK_INTERVAL_MS) return true;
344
+ return since >= ASK_RETRY_MS && asksInBurst < ASK_BURST;
345
+ }
346
+ /** One read, and the decision it supports. */ async function decide() {
320
347
  const read = await deps.read([
321
348
  deps.selfId
322
349
  ]);
323
- if (read.state !== 'read') return emit({
324
- side: 'asker',
325
- result: 'skipped',
326
- reason: read.state
327
- });
350
+ if (read.state !== 'read') return {
351
+ skipped: read.state
352
+ };
328
353
  const decision = decideAsk({
329
354
  owner: read.owner,
330
355
  holder: read.owner ? read.rows[read.owner.ownerId] : undefined,
@@ -332,6 +357,39 @@ const MUTATIONS_STORE = 'mutations';
332
357
  selfId: deps.selfId,
333
358
  now: deps.now()
334
359
  });
360
+ return {
361
+ read,
362
+ decision
363
+ };
364
+ }
365
+ /** One read and, when it says so, one ask. */ async function look() {
366
+ let looked = await decide();
367
+ if ('skipped' in looked) return emit({
368
+ side: 'asker',
369
+ result: 'skipped',
370
+ reason: looked.skipped
371
+ });
372
+ // Visible and online, but the row the holder will read says otherwise:
373
+ // the SDK wrote it before it read the visibility. A network cycle runs
374
+ // its election, which rewrites the row; a secondary's cycle touches no
375
+ // stream. The SDK queues that election behind the cycle, so this second
376
+ // read usually sees it and sometimes does not; the next boot look, a
377
+ // second later, does.
378
+ if ('reason' in looked.decision && looked.decision.reason === 'self-not-ready' && deps.isVisible() && deps.isOnline() && deps.now() - lastRefreshAt >= REFRESH_INTERVAL_MS) {
379
+ lastRefreshAt = deps.now();
380
+ await deps.cycleNetwork();
381
+ emit({
382
+ side: 'asker',
383
+ result: 'refreshed'
384
+ });
385
+ looked = await decide();
386
+ if ('skipped' in looked) return emit({
387
+ side: 'asker',
388
+ result: 'skipped',
389
+ reason: looked.skipped
390
+ });
391
+ }
392
+ const { decision } = looked;
335
393
  if ('reason' in decision) return emit({
336
394
  side: 'asker',
337
395
  result: 'skipped',
@@ -343,6 +401,7 @@ const MUTATIONS_STORE = 'mutations';
343
401
  result: 'skipped',
344
402
  reason: 'self-not-ready'
345
403
  });
404
+ asksInBurst = deps.now() - lastAskAt >= ASK_INTERVAL_MS ? 1 : asksInBurst + 1;
346
405
  lastAskAt = deps.now();
347
406
  deps.post({
348
407
  type: 'yield',
@@ -1 +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,Y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,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"}
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 * as soon as its client has started and five more times in its first 10 s\n * ({@link BOOT_CHECK_DELAYS_MS}), once it has been visible for\n * {@link VISIBLE_DWELL_MS}, and every {@link RECHECK_MS} while it stays\n * visible. When its own row still says hidden (the SDK writes a new tab's\n * first row that way), it cycles its own network first, which rewrites\n * the row from the visibility the SDK has read by then, instead of waiting\n * for the SDK's 4 s tick.\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**: up to {@link ASK_BURST} asks\n * {@link ASK_RETRY_MS} apart (an ask a background holder never answered,\n * or answered while the asker's row was not yet fresh, is asked again),\n * then one per {@link ASK_INTERVAL_MS}; one yield per\n * {@link YIELD_INTERVAL_MS}. Switching between two console tabs moves the\n * 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 this tab's client has started. The first is immediate: a\n * background holder costs a cold load 10-16 s (measured in production on\n * 2026-11-10), and the first looks at 2, 5 and 9 s it replaced asked only\n * on the third. The SDK writes a new tab's first row as hidden (see\n * `firestore-tab-handoff.ts`), so a look that finds its own row not ready\n * rewrites it with a network cycle ({@link REFRESH_INTERVAL_MS}) and asks\n * once the rewrite has landed: in the same look, or in the next one a\n * second later. The later looks cover a read that found the store\n * locked and an ask the holder did not act on. Each is a no-op once the role\n * has moved here.\n */\nexport const BOOT_CHECK_DELAYS_MS = [\n 0, 1_000, 2_500, 4_500, 7_000, 10_000,\n] as const\n\n/** An unanswered ask may be repeated this soon, up to {@link ASK_BURST}. */\nexport const ASK_RETRY_MS = 3_000\n\n/** Asks allowed {@link ASK_RETRY_MS} apart before the long interval. */\nexport const ASK_BURST = 3\n\n/** After a burst, at most one ask per this long from one tab. */\nexport const ASK_INTERVAL_MS = 15_000\n\n/**\n * At most one rewrite of this tab's own row per this long: the SDK's own\n * renewal tick, after which it would have rewritten the row anyway.\n */\nexport const REFRESH_INTERVAL_MS = 4_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: 'asker'; result: 'refreshed' }\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 asksInBurst = 0\n let lastRefreshAt = 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 || !mayAsk())\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 /** A short burst of asks, then the long interval. */\n function mayAsk(): boolean {\n const since = deps.now() - lastAskAt\n if (since >= ASK_INTERVAL_MS) return true\n return since >= ASK_RETRY_MS && asksInBurst < ASK_BURST\n }\n\n /** One read, and the decision it supports. */\n async function decide(): Promise<\n | { read: Extract<LeaseRead, { state: 'read' }>; decision: AskDecision }\n | { skipped: 'locked' | 'unavailable' }\n > {\n const read = await deps.read([deps.selfId])\n if (read.state !== 'read') return { skipped: 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 return { read, decision }\n }\n\n /** One read and, when it says so, one ask. */\n async function look(): Promise<YieldEvent> {\n let looked = await decide()\n if ('skipped' in looked)\n return emit({ side: 'asker', result: 'skipped', reason: looked.skipped })\n // Visible and online, but the row the holder will read says otherwise:\n // the SDK wrote it before it read the visibility. A network cycle runs\n // its election, which rewrites the row; a secondary's cycle touches no\n // stream. The SDK queues that election behind the cycle, so this second\n // read usually sees it and sometimes does not; the next boot look, a\n // second later, does.\n if (\n 'reason' in looked.decision &&\n looked.decision.reason === 'self-not-ready' &&\n deps.isVisible() &&\n deps.isOnline() &&\n deps.now() - lastRefreshAt >= REFRESH_INTERVAL_MS\n ) {\n lastRefreshAt = deps.now()\n await deps.cycleNetwork()\n emit({ side: 'asker', result: 'refreshed' })\n looked = await decide()\n if ('skipped' in looked)\n return emit({\n side: 'asker',\n result: 'skipped',\n reason: looked.skipped,\n })\n }\n const { decision } = looked\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 asksInBurst =\n deps.now() - lastAskAt >= ASK_INTERVAL_MS ? 1 : asksInBurst + 1\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_RETRY_MS","ASK_BURST","ASK_INTERVAL_MS","REFRESH_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","asksInBurst","lastRefreshAt","lastYieldAt","busy","looking","emit","event","onEvent","check","isVisible","isOnline","side","mayAsk","look","since","decide","read","skipped","decision","looked","cycleNetwork","post","type","askerId","receive","message","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,EACd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,MAAM7G,eAAeqI;gBACrB,MAAMpI,cAAcoI;YACtB;YACArC,SAAS,CAACD;gBACR,IAAIA,MAAMrC,MAAM,KAAK,aAAaqC,MAAMrC,MAAM,KAAK,aACjD8F,QAAQC,KAAK,CACX,qEACA1D;YAEN;QACF;IACF;AACF"}
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Whether a site's workspace can take card payments, as the console can tell
19
+ * from the workspace owner's profile.
20
+ *
21
+ * - `pending` — the org or the owner's profile has not answered yet. Never
22
+ * gate on this: a notice that flashes before the read lands tells a
23
+ * connected merchant to connect.
24
+ * - `error` — the profile could not be read. Also never gated on.
25
+ * - `not-connected` — no Stripe account on file.
26
+ * - `charges-disabled` — Stripe has not enabled charges yet (onboarding
27
+ * unfinished, or Stripe needs more details).
28
+ * - `mode-mismatch` — the account is in the other Stripe mode from this
29
+ * deployment (a test account on a live deployment, or the reverse).
30
+ * Setting up payments replaces it with an account in this mode.
31
+ * - `mode-unverified` — a live deployment with an account whose mode was
32
+ * never recorded; reconnecting records it.
33
+ * - `ready` — charges go through.
34
+ */
35
+ export type MerchantPaymentsState = 'pending' | 'error' | 'not-connected' | 'charges-disabled' | 'mode-mismatch' | 'mode-unverified' | 'ready';
36
+ export type MerchantPaymentsPlatformMode = 'live' | 'test' | undefined;
37
+ /**
38
+ * This deployment's Stripe mode, from its publishable key: `pk_live_…` is
39
+ * live, `pk_test_…` is test. The server reads the same answer off its secret
40
+ * key, and the two keys of one deployment are always a pair.
41
+ */
42
+ export declare function merchantPaymentsPlatformMode(publishableKey?: string | undefined): MerchantPaymentsPlatformMode;
43
+ /**
44
+ * The verdict for one owner profile. It is the client's copy of the server's
45
+ * `merchantAccountReadiness` and has to answer exactly as that does: a console
46
+ * that calls an account ready while checkout refuses it, or the reverse, puts
47
+ * a notice beside a control that works, or none beside one that fails.
48
+ *
49
+ * Only a literal `true` enables charges and only a literal boolean records a
50
+ * mode, because a field written as `'true'` or `1` was written by something
51
+ * other than the onboarding route.
52
+ */
53
+ export declare function merchantPaymentsStateFromProfile(profile: Record<string, unknown> | null | undefined, platformMode: MerchantPaymentsPlatformMode): Exclude<MerchantPaymentsState, 'pending' | 'error'>;
54
+ /**
55
+ * One sentence on what stands between the workspace and card payments, for a
56
+ * notice or a disabled control's reason. `null` when nothing does, or while
57
+ * the answer is unknown.
58
+ */
59
+ export declare function merchantPaymentsBlockedReason(state: MerchantPaymentsState, platformMode?: MerchantPaymentsPlatformMode): string | null;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /*
17
+ * The pure half of `use-merchant-payments`: the verdict and its wording, with
18
+ * no Firebase and no React, so a card or a spec can use them without the hook
19
+ * (AGL-2471).
20
+ */ /**
21
+ * Whether a site's workspace can take card payments, as the console can tell
22
+ * from the workspace owner's profile.
23
+ *
24
+ * - `pending` — the org or the owner's profile has not answered yet. Never
25
+ * gate on this: a notice that flashes before the read lands tells a
26
+ * connected merchant to connect.
27
+ * - `error` — the profile could not be read. Also never gated on.
28
+ * - `not-connected` — no Stripe account on file.
29
+ * - `charges-disabled` — Stripe has not enabled charges yet (onboarding
30
+ * unfinished, or Stripe needs more details).
31
+ * - `mode-mismatch` — the account is in the other Stripe mode from this
32
+ * deployment (a test account on a live deployment, or the reverse).
33
+ * Setting up payments replaces it with an account in this mode.
34
+ * - `mode-unverified` — a live deployment with an account whose mode was
35
+ * never recorded; reconnecting records it.
36
+ * - `ready` — charges go through.
37
+ */ /**
38
+ * This deployment's Stripe mode, from its publishable key: `pk_live_…` is
39
+ * live, `pk_test_…` is test. The server reads the same answer off its secret
40
+ * key, and the two keys of one deployment are always a pair.
41
+ */ export function merchantPaymentsPlatformMode(// The dot form: a bundler inlines `process.env.NEXT_PUBLIC_…` into browser
42
+ // code only when the name is written out like this.
43
+ publishableKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) {
44
+ const key = String(publishableKey != null ? publishableKey : '').trim();
45
+ if (key.startsWith('pk_live_')) return 'live';
46
+ if (key.startsWith('pk_test_')) return 'test';
47
+ return undefined;
48
+ }
49
+ /**
50
+ * The verdict for one owner profile. It is the client's copy of the server's
51
+ * `merchantAccountReadiness` and has to answer exactly as that does: a console
52
+ * that calls an account ready while checkout refuses it, or the reverse, puts
53
+ * a notice beside a control that works, or none beside one that fails.
54
+ *
55
+ * Only a literal `true` enables charges and only a literal boolean records a
56
+ * mode, because a field written as `'true'` or `1` was written by something
57
+ * other than the onboarding route.
58
+ */ export function merchantPaymentsStateFromProfile(profile, platformMode) {
59
+ const accountId = typeof (profile == null ? void 0 : profile['stripeAccountId']) === 'string' ? profile['stripeAccountId'].trim() : '';
60
+ if (!accountId) return 'not-connected';
61
+ if ((profile == null ? void 0 : profile['stripeChargesEnabled']) !== true) return 'charges-disabled';
62
+ const accountLivemode = profile == null ? void 0 : profile['stripeAccountLivemode'];
63
+ if (typeof accountLivemode === 'boolean') {
64
+ if (!platformMode) return 'ready';
65
+ return accountLivemode === (platformMode === 'live') ? 'ready' : 'mode-mismatch';
66
+ }
67
+ return platformMode === 'live' ? 'mode-unverified' : 'ready';
68
+ }
69
+ /**
70
+ * One sentence on what stands between the workspace and card payments, for a
71
+ * notice or a disabled control's reason. `null` when nothing does, or while
72
+ * the answer is unknown.
73
+ */ export function merchantPaymentsBlockedReason(state, platformMode = merchantPaymentsPlatformMode()) {
74
+ switch(state){
75
+ case 'not-connected':
76
+ return 'Connect Stripe to take card payments.';
77
+ case 'charges-disabled':
78
+ return 'Finish setting up Stripe to take card payments: Stripe has not turned on charges for this account yet.';
79
+ case 'mode-mismatch':
80
+ // Proven, so said plainly: setting up payments replaces the account
81
+ // with one in this deployment's mode.
82
+ return platformMode === 'test' ? 'Set up payments to take card payments: the connected Stripe account is a live account, and this site takes test payments only.' : 'Set up payments to take card payments: the connected Stripe account is a test account, and live payments need a live one.';
83
+ case 'mode-unverified':
84
+ return 'Reconnect Stripe to take card payments: the connected account has not been confirmed for live payments.';
85
+ default:
86
+ return null;
87
+ }
88
+ }
89
+
90
+ //# sourceMappingURL=merchant-payments-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/merchant-payments-state.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\n/*\n * The pure half of `use-merchant-payments`: the verdict and its wording, with\n * no Firebase and no React, so a card or a spec can use them without the hook\n * (AGL-2471).\n */\n\n/**\n * Whether a site's workspace can take card payments, as the console can tell\n * from the workspace owner's profile.\n *\n * - `pending` — the org or the owner's profile has not answered yet. Never\n * gate on this: a notice that flashes before the read lands tells a\n * connected merchant to connect.\n * - `error` — the profile could not be read. Also never gated on.\n * - `not-connected` — no Stripe account on file.\n * - `charges-disabled` — Stripe has not enabled charges yet (onboarding\n * unfinished, or Stripe needs more details).\n * - `mode-mismatch` — the account is in the other Stripe mode from this\n * deployment (a test account on a live deployment, or the reverse).\n * Setting up payments replaces it with an account in this mode.\n * - `mode-unverified` — a live deployment with an account whose mode was\n * never recorded; reconnecting records it.\n * - `ready` — charges go through.\n */\nexport type MerchantPaymentsState =\n | 'pending'\n | 'error'\n | 'not-connected'\n | 'charges-disabled'\n | 'mode-mismatch'\n | 'mode-unverified'\n | 'ready'\n\nexport type MerchantPaymentsPlatformMode = 'live' | 'test' | undefined\n\n/**\n * This deployment's Stripe mode, from its publishable key: `pk_live_…` is\n * live, `pk_test_…` is test. The server reads the same answer off its secret\n * key, and the two keys of one deployment are always a pair.\n */\nexport function merchantPaymentsPlatformMode(\n // The dot form: a bundler inlines `process.env.NEXT_PUBLIC_…` into browser\n // code only when the name is written out like this.\n publishableKey: string | undefined = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,\n): MerchantPaymentsPlatformMode {\n const key = String(publishableKey ?? '').trim()\n if (key.startsWith('pk_live_')) return 'live'\n if (key.startsWith('pk_test_')) return 'test'\n return undefined\n}\n\n/**\n * The verdict for one owner profile. It is the client's copy of the server's\n * `merchantAccountReadiness` and has to answer exactly as that does: a console\n * that calls an account ready while checkout refuses it, or the reverse, puts\n * a notice beside a control that works, or none beside one that fails.\n *\n * Only a literal `true` enables charges and only a literal boolean records a\n * mode, because a field written as `'true'` or `1` was written by something\n * other than the onboarding route.\n */\nexport function merchantPaymentsStateFromProfile(\n profile: Record<string, unknown> | null | undefined,\n platformMode: MerchantPaymentsPlatformMode,\n): Exclude<MerchantPaymentsState, 'pending' | 'error'> {\n const accountId = typeof profile?.['stripeAccountId'] === 'string' ? profile['stripeAccountId'].trim() : ''\n if (!accountId) return 'not-connected'\n if (profile?.['stripeChargesEnabled'] !== true) return 'charges-disabled'\n const accountLivemode = profile?.['stripeAccountLivemode']\n if (typeof accountLivemode === 'boolean') {\n if (!platformMode) return 'ready'\n return accountLivemode === (platformMode === 'live') ? 'ready' : 'mode-mismatch'\n }\n return platformMode === 'live' ? 'mode-unverified' : 'ready'\n}\n\n/**\n * One sentence on what stands between the workspace and card payments, for a\n * notice or a disabled control's reason. `null` when nothing does, or while\n * the answer is unknown.\n */\nexport function merchantPaymentsBlockedReason(\n state: MerchantPaymentsState,\n platformMode: MerchantPaymentsPlatformMode = merchantPaymentsPlatformMode(),\n): string | null {\n switch (state) {\n case 'not-connected':\n return 'Connect Stripe to take card payments.'\n case 'charges-disabled':\n return 'Finish setting up Stripe to take card payments: Stripe has not turned on charges for this account yet.'\n case 'mode-mismatch':\n // Proven, so said plainly: setting up payments replaces the account\n // with one in this deployment's mode.\n return platformMode === 'test'\n ? 'Set up payments to take card payments: the connected Stripe account is a live account, and this site takes test payments only.'\n : 'Set up payments to take card payments: the connected Stripe account is a test account, and live payments need a live one.'\n case 'mode-unverified':\n return 'Reconnect Stripe to take card payments: the connected account has not been confirmed for live payments.'\n default:\n return null\n }\n}\n"],"names":["merchantPaymentsPlatformMode","publishableKey","process","env","NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY","key","String","trim","startsWith","undefined","merchantPaymentsStateFromProfile","profile","platformMode","accountId","accountLivemode","merchantPaymentsBlockedReason","state"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;CAIC,GAED;;;;;;;;;;;;;;;;;CAiBC,GAYD;;;;CAIC,GACD,OAAO,SAASA,6BACd,2EAA2E;AAC3E,oDAAoD;AACpDC,iBAAqCC,QAAQC,GAAG,CAACC,kCAAkC;IAEnF,MAAMC,MAAMC,OAAOL,yBAAAA,iBAAkB,IAAIM,IAAI;IAC7C,IAAIF,IAAIG,UAAU,CAAC,aAAa,OAAO;IACvC,IAAIH,IAAIG,UAAU,CAAC,aAAa,OAAO;IACvC,OAAOC;AACT;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,iCACdC,OAAmD,EACnDC,YAA0C;IAE1C,MAAMC,YAAY,QAAOF,2BAAAA,OAAS,CAAC,kBAAkB,MAAK,WAAWA,OAAO,CAAC,kBAAkB,CAACJ,IAAI,KAAK;IACzG,IAAI,CAACM,WAAW,OAAO;IACvB,IAAIF,CAAAA,2BAAAA,OAAS,CAAC,uBAAuB,MAAK,MAAM,OAAO;IACvD,MAAMG,kBAAkBH,2BAAAA,OAAS,CAAC,wBAAwB;IAC1D,IAAI,OAAOG,oBAAoB,WAAW;QACxC,IAAI,CAACF,cAAc,OAAO;QAC1B,OAAOE,oBAAqBF,CAAAA,iBAAiB,MAAK,IAAK,UAAU;IACnE;IACA,OAAOA,iBAAiB,SAAS,oBAAoB;AACvD;AAEA;;;;CAIC,GACD,OAAO,SAASG,8BACdC,KAA4B,EAC5BJ,eAA6CZ,8BAA8B;IAE3E,OAAQgB;QACN,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAO;QACT,KAAK;YACH,oEAAoE;YACpE,sCAAsC;YACtC,OAAOJ,iBAAiB,SACpB,mIACA;QACN,KAAK;YACH,OAAO;QACT;YACE,OAAO;IACX;AACF"}
@@ -1,45 +1,5 @@
1
- /**
2
- * Whether a site's workspace can take card payments, as the console can tell
3
- * from the workspace owner's profile.
4
- *
5
- * - `pending` — the org or the owner's profile has not answered yet. Never
6
- * gate on this: a notice that flashes before the read lands tells a
7
- * connected merchant to connect.
8
- * - `error` — the profile could not be read. Also never gated on.
9
- * - `not-connected` — no Stripe account on file.
10
- * - `charges-disabled` — Stripe has not enabled charges yet (onboarding
11
- * unfinished, or Stripe needs more details).
12
- * - `mode-mismatch` — the account is in the other Stripe mode from this
13
- * deployment (a test account on a live deployment, or the reverse).
14
- * - `mode-unverified` — a live deployment with an account whose mode was
15
- * never recorded; reconnecting records it.
16
- * - `ready` — charges go through.
17
- */
18
- export type MerchantPaymentsState = 'pending' | 'error' | 'not-connected' | 'charges-disabled' | 'mode-mismatch' | 'mode-unverified' | 'ready';
19
- export type MerchantPaymentsPlatformMode = 'live' | 'test' | undefined;
20
- /**
21
- * This deployment's Stripe mode, from its publishable key: `pk_live_…` is
22
- * live, `pk_test_…` is test. The server reads the same answer off its secret
23
- * key, and the two keys of one deployment are always a pair.
24
- */
25
- export declare function merchantPaymentsPlatformMode(publishableKey?: string | undefined): MerchantPaymentsPlatformMode;
26
- /**
27
- * The verdict for one owner profile. It is the client's copy of the server's
28
- * `merchantAccountReadiness` and has to answer exactly as that does: a console
29
- * that calls an account ready while checkout refuses it, or the reverse, puts
30
- * a notice beside a control that works, or none beside one that fails.
31
- *
32
- * Only a literal `true` enables charges and only a literal boolean records a
33
- * mode, because a field written as `'true'` or `1` was written by something
34
- * other than the onboarding route.
35
- */
36
- export declare function merchantPaymentsStateFromProfile(profile: Record<string, unknown> | null | undefined, platformMode: MerchantPaymentsPlatformMode): Exclude<MerchantPaymentsState, 'pending' | 'error'>;
37
- /**
38
- * One sentence on what stands between the workspace and card payments, for a
39
- * notice or a disabled control's reason. `null` when nothing does, or while
40
- * the answer is unknown.
41
- */
42
- export declare function merchantPaymentsBlockedReason(state: MerchantPaymentsState): string | null;
1
+ import { type MerchantPaymentsState } from './merchant-payments-state';
2
+ export * from './merchant-payments-state';
43
3
  /**
44
4
  * A site's store settings page (`payments`, `shipping`, `pos` …), or `null`
45
5
  * until the site's console address resolves or when no installed plugin
@@ -21,55 +21,8 @@ import { useFirestore } from "./firebase/firebase-services.js";
21
21
  import { useConsoleHostRoute } from "./use-console-host-route.js";
22
22
  import { useFirestoreDoc } from "./use-firestore-doc.js";
23
23
  import { useOrgPlan } from "./use-org-plan.js";
24
- /**
25
- * This deployment's Stripe mode, from its publishable key: `pk_live_…` is
26
- * live, `pk_test_…` is test. The server reads the same answer off its secret
27
- * key, and the two keys of one deployment are always a pair.
28
- */ export function merchantPaymentsPlatformMode(// The dot form: a bundler inlines `process.env.NEXT_PUBLIC_…` into browser
29
- // code only when the name is written out like this.
30
- publishableKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) {
31
- const key = String(publishableKey != null ? publishableKey : '').trim();
32
- if (key.startsWith('pk_live_')) return 'live';
33
- if (key.startsWith('pk_test_')) return 'test';
34
- return undefined;
35
- }
36
- /**
37
- * The verdict for one owner profile. It is the client's copy of the server's
38
- * `merchantAccountReadiness` and has to answer exactly as that does: a console
39
- * that calls an account ready while checkout refuses it, or the reverse, puts
40
- * a notice beside a control that works, or none beside one that fails.
41
- *
42
- * Only a literal `true` enables charges and only a literal boolean records a
43
- * mode, because a field written as `'true'` or `1` was written by something
44
- * other than the onboarding route.
45
- */ export function merchantPaymentsStateFromProfile(profile, platformMode) {
46
- const accountId = typeof (profile == null ? void 0 : profile['stripeAccountId']) === 'string' ? profile['stripeAccountId'].trim() : '';
47
- if (!accountId) return 'not-connected';
48
- if ((profile == null ? void 0 : profile['stripeChargesEnabled']) !== true) return 'charges-disabled';
49
- const accountLivemode = profile == null ? void 0 : profile['stripeAccountLivemode'];
50
- if (typeof accountLivemode === 'boolean') {
51
- if (!platformMode) return 'ready';
52
- return accountLivemode === (platformMode === 'live') ? 'ready' : 'mode-mismatch';
53
- }
54
- return platformMode === 'live' ? 'mode-unverified' : 'ready';
55
- }
56
- /**
57
- * One sentence on what stands between the workspace and card payments, for a
58
- * notice or a disabled control's reason. `null` when nothing does, or while
59
- * the answer is unknown.
60
- */ export function merchantPaymentsBlockedReason(state) {
61
- switch(state){
62
- case 'not-connected':
63
- return 'Connect Stripe to take card payments.';
64
- case 'charges-disabled':
65
- return 'Finish setting up Stripe to take card payments: Stripe has not turned on charges for this account yet.';
66
- case 'mode-mismatch':
67
- case 'mode-unverified':
68
- return 'Reconnect Stripe to take card payments: the connected account has not been confirmed for live payments.';
69
- default:
70
- return null;
71
- }
72
- }
24
+ import { merchantPaymentsBlockedReason, merchantPaymentsPlatformMode, merchantPaymentsStateFromProfile } from "./merchant-payments-state.js";
25
+ export * from "./merchant-payments-state.js";
73
26
  /**
74
27
  * A site's store settings page (`payments`, `shipping`, `pos` …), or `null`
75
28
  * until the site's console address resolves or when no installed plugin
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-merchant-payments.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'use client'\n\nimport { pluginRecordHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { doc } from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport { useFirestore } from './firebase/firebase-services'\nimport { useConsoleHostRoute } from './use-console-host-route'\nimport { useFirestoreDoc } from './use-firestore-doc'\nimport { useOrgPlan } from './use-org-plan'\n\n/**\n * Whether a site's workspace can take card payments, as the console can tell\n * from the workspace owner's profile.\n *\n * - `pending` — the org or the owner's profile has not answered yet. Never\n * gate on this: a notice that flashes before the read lands tells a\n * connected merchant to connect.\n * - `error` — the profile could not be read. Also never gated on.\n * - `not-connected` — no Stripe account on file.\n * - `charges-disabled` — Stripe has not enabled charges yet (onboarding\n * unfinished, or Stripe needs more details).\n * - `mode-mismatch` — the account is in the other Stripe mode from this\n * deployment (a test account on a live deployment, or the reverse).\n * - `mode-unverified` — a live deployment with an account whose mode was\n * never recorded; reconnecting records it.\n * - `ready` — charges go through.\n */\nexport type MerchantPaymentsState =\n | 'pending'\n | 'error'\n | 'not-connected'\n | 'charges-disabled'\n | 'mode-mismatch'\n | 'mode-unverified'\n | 'ready'\n\nexport type MerchantPaymentsPlatformMode = 'live' | 'test' | undefined\n\n/**\n * This deployment's Stripe mode, from its publishable key: `pk_live_…` is\n * live, `pk_test_…` is test. The server reads the same answer off its secret\n * key, and the two keys of one deployment are always a pair.\n */\nexport function merchantPaymentsPlatformMode(\n // The dot form: a bundler inlines `process.env.NEXT_PUBLIC_…` into browser\n // code only when the name is written out like this.\n publishableKey: string | undefined = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY,\n): MerchantPaymentsPlatformMode {\n const key = String(publishableKey ?? '').trim()\n if (key.startsWith('pk_live_')) return 'live'\n if (key.startsWith('pk_test_')) return 'test'\n return undefined\n}\n\n/**\n * The verdict for one owner profile. It is the client's copy of the server's\n * `merchantAccountReadiness` and has to answer exactly as that does: a console\n * that calls an account ready while checkout refuses it, or the reverse, puts\n * a notice beside a control that works, or none beside one that fails.\n *\n * Only a literal `true` enables charges and only a literal boolean records a\n * mode, because a field written as `'true'` or `1` was written by something\n * other than the onboarding route.\n */\nexport function merchantPaymentsStateFromProfile(\n profile: Record<string, unknown> | null | undefined,\n platformMode: MerchantPaymentsPlatformMode,\n): Exclude<MerchantPaymentsState, 'pending' | 'error'> {\n const accountId = typeof profile?.['stripeAccountId'] === 'string' ? profile['stripeAccountId'].trim() : ''\n if (!accountId) return 'not-connected'\n if (profile?.['stripeChargesEnabled'] !== true) return 'charges-disabled'\n const accountLivemode = profile?.['stripeAccountLivemode']\n if (typeof accountLivemode === 'boolean') {\n if (!platformMode) return 'ready'\n return accountLivemode === (platformMode === 'live') ? 'ready' : 'mode-mismatch'\n }\n return platformMode === 'live' ? 'mode-unverified' : 'ready'\n}\n\n/**\n * One sentence on what stands between the workspace and card payments, for a\n * notice or a disabled control's reason. `null` when nothing does, or while\n * the answer is unknown.\n */\nexport function merchantPaymentsBlockedReason(state: MerchantPaymentsState): string | null {\n switch (state) {\n case 'not-connected':\n return 'Connect Stripe to take card payments.'\n case 'charges-disabled':\n return 'Finish setting up Stripe to take card payments: Stripe has not turned on charges for this account yet.'\n case 'mode-mismatch':\n case 'mode-unverified':\n return 'Reconnect Stripe to take card payments: the connected account has not been confirmed for live payments.'\n default:\n return null\n }\n}\n\n/**\n * A site's store settings page (`payments`, `shipping`, `pos` …), or `null`\n * until the site's console address resolves or when no installed plugin\n * publishes store settings. Resolved through the plugin record-route seam, so\n * a plugin that only needs to point at the page never imports the one that\n * owns it.\n */\nexport function useStoreSettingsHref(hostId: string | undefined, page: string): string | null {\n const { orgSlug, subdomain } = useConsoleHostRoute(hostId)\n return useMemo(\n () => (orgSlug && subdomain ? pluginRecordHref('store-settings', { orgSlug, host: subdomain }, page) : null),\n [orgSlug, subdomain, page],\n )\n}\n\nexport interface MerchantPaymentsStatus {\n state: MerchantPaymentsState\n /** The answer has arrived, so a notice may be shown or held. */\n settled: boolean\n /** Settled and able to charge. */\n ready: boolean\n /** Settled and NOT able to charge: the case to explain. */\n blocked: boolean\n /** {@link merchantPaymentsBlockedReason} for the current state. */\n reason: string | null\n /** The site's Payments settings page, where Stripe is connected. */\n href: string | null\n}\n\n/**\n * Card-payment readiness for the workspace that owns a site.\n *\n * Reads the OWNER's profile, the document every money route checks, rather\n * than the signed-in member's: an admin who is not the owner has no Stripe\n * account of their own, and reading theirs would report a connected store as\n * not set up.\n */\nexport function useMerchantPayments(hostId: string | undefined): MerchantPaymentsStatus {\n const firestore = useFirestore()\n const { org, ready: orgReady } = useOrgPlan(hostId)\n const href = useStoreSettingsHref(hostId, 'payments')\n const ownerUid = typeof org?.['ownerUid'] === 'string' ? (org['ownerUid'] as string) : ''\n const { data: profile, status } = useFirestoreDoc<Record<string, unknown>>(\n () => (ownerUid ? doc(firestore, 'profiles', ownerUid) : null),\n [firestore, ownerUid],\n )\n return useMemo(() => {\n let state: MerchantPaymentsState\n if (!orgReady) state = 'pending'\n else if (!ownerUid) state = 'not-connected'\n else if (status === 'error') state = 'error'\n else if (status !== 'success') state = 'pending'\n else state = merchantPaymentsStateFromProfile(profile, merchantPaymentsPlatformMode())\n const settled = state !== 'pending' && state !== 'error'\n return {\n state,\n settled,\n ready: state === 'ready',\n blocked: settled && state !== 'ready',\n reason: merchantPaymentsBlockedReason(state),\n href,\n }\n }, [orgReady, ownerUid, status, profile, href])\n}\n\nexport default useMerchantPayments\n"],"names":["pluginRecordHref","doc","useMemo","useFirestore","useConsoleHostRoute","useFirestoreDoc","useOrgPlan","merchantPaymentsPlatformMode","publishableKey","process","env","NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY","key","String","trim","startsWith","undefined","merchantPaymentsStateFromProfile","profile","platformMode","accountId","accountLivemode","merchantPaymentsBlockedReason","state","useStoreSettingsHref","hostId","page","orgSlug","subdomain","host","useMerchantPayments","firestore","org","ready","orgReady","href","ownerUid","data","status","settled","blocked","reason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAASA,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,OAAO,QAAQ,QAAO;AAC/B,SAASC,YAAY,QAAQ,kCAA8B;AAC3D,SAASC,mBAAmB,QAAQ,8BAA0B;AAC9D,SAASC,eAAe,QAAQ,yBAAqB;AACrD,SAASC,UAAU,QAAQ,oBAAgB;AA8B3C;;;;CAIC,GACD,OAAO,SAASC,6BACd,2EAA2E;AAC3E,oDAAoD;AACpDC,iBAAqCC,QAAQC,GAAG,CAACC,kCAAkC;IAEnF,MAAMC,MAAMC,OAAOL,yBAAAA,iBAAkB,IAAIM,IAAI;IAC7C,IAAIF,IAAIG,UAAU,CAAC,aAAa,OAAO;IACvC,IAAIH,IAAIG,UAAU,CAAC,aAAa,OAAO;IACvC,OAAOC;AACT;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,iCACdC,OAAmD,EACnDC,YAA0C;IAE1C,MAAMC,YAAY,QAAOF,2BAAAA,OAAS,CAAC,kBAAkB,MAAK,WAAWA,OAAO,CAAC,kBAAkB,CAACJ,IAAI,KAAK;IACzG,IAAI,CAACM,WAA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AACa,UAAUb,QAAQ;aACvB,IAAIe,WAAW,SAASf,QAAQ;aAChC,IAAIe,WAAW,WAAWf,QAAQ;aAClCA,QAAQN,iCAAiCC,SAASX;QACvD,MAAMgC,UAAUhB,UAAU,aAAaA,UAAU;QACjD,OAAO;YACLA;YACAgB;YACAN,OAAOV,UAAU;YACjBiB,SAASD,WAAWhB,UAAU;YAC9BkB,QAAQnB,8BAA8BC;YACtCY;QACF;IACF,GAAG;QAACD;QAAUE;QAAUE;QAAQpB;QAASiB;KAAK;AAChD;AAEA,eAAeL,oBAAmB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-merchant-payments.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'use client'\n\nimport { pluginRecordHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { doc } from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport { useFirestore } from './firebase/firebase-services'\nimport { useConsoleHostRoute } from './use-console-host-route'\nimport { useFirestoreDoc } from './use-firestore-doc'\nimport { useOrgPlan } from './use-org-plan'\nimport {\n merchantPaymentsBlockedReason,\n merchantPaymentsPlatformMode,\n merchantPaymentsStateFromProfile,\n type MerchantPaymentsState,\n} from './merchant-payments-state'\n\nexport * from './merchant-payments-state'\n\n/**\n * A site's store settings page (`payments`, `shipping`, `pos` …), or `null`\n * until the site's console address resolves or when no installed plugin\n * publishes store settings. Resolved through the plugin record-route seam, so\n * a plugin that only needs to point at the page never imports the one that\n * owns it.\n */\nexport function useStoreSettingsHref(hostId: string | undefined, page: string): string | null {\n const { orgSlug, subdomain } = useConsoleHostRoute(hostId)\n return useMemo(\n () => (orgSlug && subdomain ? pluginRecordHref('store-settings', { orgSlug, host: subdomain }, page) : null),\n [orgSlug, subdomain, page],\n )\n}\n\nexport interface MerchantPaymentsStatus {\n state: MerchantPaymentsState\n /** The answer has arrived, so a notice may be shown or held. */\n settled: boolean\n /** Settled and able to charge. */\n ready: boolean\n /** Settled and NOT able to charge: the case to explain. */\n blocked: boolean\n /** {@link merchantPaymentsBlockedReason} for the current state. */\n reason: string | null\n /** The site's Payments settings page, where Stripe is connected. */\n href: string | null\n}\n\n/**\n * Card-payment readiness for the workspace that owns a site.\n *\n * Reads the OWNER's profile, the document every money route checks, rather\n * than the signed-in member's: an admin who is not the owner has no Stripe\n * account of their own, and reading theirs would report a connected store as\n * not set up.\n */\nexport function useMerchantPayments(hostId: string | undefined): MerchantPaymentsStatus {\n const firestore = useFirestore()\n const { org, ready: orgReady } = useOrgPlan(hostId)\n const href = useStoreSettingsHref(hostId, 'payments')\n const ownerUid = typeof org?.['ownerUid'] === 'string' ? (org['ownerUid'] as string) : ''\n const { data: profile, status } = useFirestoreDoc<Record<string, unknown>>(\n () => (ownerUid ? doc(firestore, 'profiles', ownerUid) : null),\n [firestore, ownerUid],\n )\n return useMemo(() => {\n let state: MerchantPaymentsState\n if (!orgReady) state = 'pending'\n else if (!ownerUid) state = 'not-connected'\n else if (status === 'error') state = 'error'\n else if (status !== 'success') state = 'pending'\n else state = merchantPaymentsStateFromProfile(profile, merchantPaymentsPlatformMode())\n const settled = state !== 'pending' && state !== 'error'\n return {\n state,\n settled,\n ready: state === 'ready',\n blocked: settled && state !== 'ready',\n reason: merchantPaymentsBlockedReason(state),\n href,\n }\n }, [orgReady, ownerUid, status, profile, href])\n}\n\nexport default useMerchantPayments\n"],"names":["pluginRecordHref","doc","useMemo","useFirestore","useConsoleHostRoute","useFirestoreDoc","useOrgPlan","merchantPaymentsBlockedReason","merchantPaymentsPlatformMode","merchantPaymentsStateFromProfile","useStoreSettingsHref","hostId","page","orgSlug","subdomain","host","useMerchantPayments","firestore","org","ready","orgReady","href","ownerUid","data","profile","status","state","settled","blocked","reason"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAASA,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,OAAO,QAAQ,QAAO;AAC/B,SAASC,YAAY,QAAQ,kCAA8B;AAC3D,SAASC,mBAAmB,QAAQ,8BAA0B;AAC9D,SAASC,eAAe,QAAQ,yBAAqB;AACrD,SAASC,UAAU,QAAQ,oBAAgB;AAC3C,SACEC,6BAA6B,EAC7BC,4BAA4B,EAC5BC,gCAAgC,QAE3B,+BAA2B;AAElC,cAAc,+BAA2B;AAEzC;;;;;;CAMC,GACD,OAAO,SAASC,qBAAqBC,MAA0B,EAAEC,IAAY;IAC3E,MAAM,EAAEC,OAAO,EAAEC,SAAS,EAAE,GAAGV,oBAAoBO;IACnD,OAAOT,QACL,IAAOW,WAAWC,YAAYd,iBAAiB,kBAAkB;YAAEa;YAASE,MAAMD;QAAU,GAAGF,QAAQ,MACvG;QAACC;QAASC;QAAWF;KAAK;AAE9B;AAgBA;;;;;;;CAOC,GACD,OAAO,SAASI,oBAAoBL,MAA0B;IAC5D,MAAMM,YAAYd;IAClB,MAAM,EAAEe,GAAG,EAAEC,OAAOC,QAAQ,EAAE,GAAGd,WAAWK;IAC5C,MAAMU,OAAOX,qBAAqBC,QAAQ;IAC1C,MAAMW,WAAW,QAAOJ,uBAAAA,GAAK,CAAC,WAAW,MAAK,WAAYA,GAAG,CAAC,WAAW,GAAc;IACvF,MAAM,EAAEK,MAAMC,OAAO,EAAEC,MAAM,EAAE,GAAGpB,gBAChC,IAAOiB,WAAWrB,IAAIgB,WAAW,YAAYK,YAAY,MACzD;QAACL;QAAWK;KAAS;IAEvB,OAAOpB,QAAQ;QACb,IAAIwB;QACJ,IAAI,CAACN,UAAUM,QAA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