@aglyn/tenant-feature-instance 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/hooks/firebase/firebase-services.d.ts +7 -0
- package/src/lib/hooks/firebase/firebase-services.js.map +1 -1
- package/src/lib/hooks/firebase/firestore-multitab-wedge.d.ts +67 -1
- package/src/lib/hooks/firebase/firestore-multitab-wedge.js +81 -2
- package/src/lib/hooks/firebase/firestore-multitab-wedge.js.map +1 -1
- package/src/lib/hooks/firebase/firestore-stall-recovery.d.ts +52 -4
- package/src/lib/hooks/firebase/firestore-stall-recovery.js +87 -16
- package/src/lib/hooks/firebase/firestore-stall-recovery.js.map +1 -1
- package/src/lib/hooks/helpers/guarded-seed-write.d.ts +71 -1
- package/src/lib/hooks/helpers/guarded-seed-write.js +4 -3
- package/src/lib/hooks/helpers/guarded-seed-write.js.map +1 -1
- package/src/lib/hooks/helpers/listen-confirmation.d.ts +54 -7
- package/src/lib/hooks/helpers/listen-confirmation.js +89 -12
- package/src/lib/hooks/helpers/listen-confirmation.js.map +1 -1
- package/src/lib/hooks/helpers/use-doc.js +6 -4
- package/src/lib/hooks/helpers/use-doc.js.map +1 -1
- package/src/lib/hooks/use-firestore-collection.d.ts +7 -0
- package/src/lib/hooks/use-firestore-collection.js +6 -4
- package/src/lib/hooks/use-firestore-collection.js.map +1 -1
- package/src/lib/hooks/use-firestore-doc.d.ts +7 -0
- package/src/lib/hooks/use-firestore-doc.js +6 -4
- package/src/lib/hooks/use-firestore-doc.js.map +1 -1
- package/src/lib/hooks/use-paged-collection.d.ts +7 -1
- package/src/lib/hooks/use-paged-collection.js.map +1 -1
- package/src/lib/hooks/use-sorted-paged-collection.js +3 -1
- package/src/lib/hooks/use-sorted-paged-collection.js.map +1 -1
- package/src/lib/testing/list-query-double.js +1 -0
- package/src/lib/testing/list-query-double.js.map +1 -1
|
@@ -14,6 +14,67 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
+
/**
|
|
18
|
+
* Refuse a whole-object write whose form was seeded from a read we cannot
|
|
19
|
+
* trust (AGL-1356, AGL-1358, AGL-1066).
|
|
20
|
+
*
|
|
21
|
+
* ## The shape this exists for
|
|
22
|
+
*
|
|
23
|
+
* A form seeded from a Firestore LISTENER, saved with a payload that carries
|
|
24
|
+
* every field rather than the one that changed. `merge: true` protects
|
|
25
|
+
* nothing there — the untouched fields are all present in the payload — so
|
|
26
|
+
* saving one edit rewrites the rest to whatever the seed held. If the seed
|
|
27
|
+
* came from IndexedDB during a stale session, "whatever the seed held" can
|
|
28
|
+
* be arbitrarily old, and the user's real values are destroyed by a save
|
|
29
|
+
* they asked for and had every reason to expect to be safe.
|
|
30
|
+
*
|
|
31
|
+
* ## Why it WRAPS the write instead of preceding it
|
|
32
|
+
*
|
|
33
|
+
* The guards this replaces sat in front of their writes as early returns,
|
|
34
|
+
* which is a shape you can have and still write — add a branch, reorder a
|
|
35
|
+
* line, and the guard is decoration. Here the write is only reachable
|
|
36
|
+
* THROUGH the verdict, so a call site cannot keep the guard and lose the
|
|
37
|
+
* protection. It also makes the refusal testable as a refusal: assert the
|
|
38
|
+
* inner function never ran.
|
|
39
|
+
*
|
|
40
|
+
* ## The three signals, in the order they are worth trusting
|
|
41
|
+
*
|
|
42
|
+
* 1. `fromCache` — the server never confirmed what is on screen (AGL-1066).
|
|
43
|
+
* This is the one that catches the dangerous case, because a cache-served
|
|
44
|
+
* read looks completely healthy: populated form, plausible values. It is
|
|
45
|
+
* per-listener ground truth from the SDK, so it needs no threshold and no
|
|
46
|
+
* window, and it clears itself the instant a server snapshot lands. It
|
|
47
|
+
* leads because it is also the more ACCURATE explanation whenever it is
|
|
48
|
+
* true — see the ordering note on `checkSeedFreshness`. It is also the one
|
|
49
|
+
* signal that a little patience answers, so `writeGuardedBySeed` waits for
|
|
50
|
+
* the confirmation before it refuses on this alone (AGL-4120).
|
|
51
|
+
* 2. `unreadable` — the read FAILED and there is nothing cached behind it
|
|
52
|
+
* (AGL-1143). Saving would write blanks over a populated document.
|
|
53
|
+
* 3. `staleSession` — the console's own heuristic. Kept because it means
|
|
54
|
+
* something the other two do not (the SESSION is dead, not merely
|
|
55
|
+
* unconfirmed), but it must never be the ONLY guard: it needs two
|
|
56
|
+
* distinct labelled collections denied inside 60s, which is unreachable
|
|
57
|
+
* on a listener-only page. That was exactly how AGL-1356 stayed open.
|
|
58
|
+
*
|
|
59
|
+
* ## Why this lives in the library rather than the console (AGL-1358)
|
|
60
|
+
*
|
|
61
|
+
* Most of the ~forty sites wearing this shape are plugin cards in
|
|
62
|
+
* `libs/plugins/**`, which cannot import from `apps/console`. The guard
|
|
63
|
+
* itself is pure, and `fromCache` — the signal that actually fires —
|
|
64
|
+
* originates here, on the listener hooks. What it cannot own is
|
|
65
|
+
* `session-health`, which is console state.
|
|
66
|
+
*
|
|
67
|
+
* So the third signal is INJECTED, through the same seam
|
|
68
|
+
* `firestore-denial-reporter` already uses for the reverse direction: the
|
|
69
|
+
* console registers a check at startup and the guard pulls it. That keeps a
|
|
70
|
+
* single guard for every call site with no new dependency edge and nothing
|
|
71
|
+
* inverted — the library still knows nothing about the app. An unregistered
|
|
72
|
+
* check simply reports "not stale", which is what the tenant runtime and the
|
|
73
|
+
* unit tests want; the other two signals are unaffected, and they are the
|
|
74
|
+
* ones the doc above says must carry the guard anyway.
|
|
75
|
+
*/
|
|
76
|
+
import { type ListenHandle } from './listen-confirmation';
|
|
77
|
+
export type { ListenHandle } from './listen-confirmation';
|
|
17
78
|
export type StaleSeedReason = 'unreadable' | 'unconfirmed' | 'stale-session'
|
|
18
79
|
/** The server's confirmation changed the values the form was built from. */
|
|
19
80
|
| 'refreshed';
|
|
@@ -38,6 +99,14 @@ export interface GuardedSeedWriteOptions {
|
|
|
38
99
|
unreadable?: boolean;
|
|
39
100
|
/** The seeding snapshot came from cache (`metadata.fromCache`). */
|
|
40
101
|
fromCache?: boolean;
|
|
102
|
+
/**
|
|
103
|
+
* The listener the seed came from: `listen` on the hook that gave
|
|
104
|
+
* `fromCache` (AGL-4135). With it, an unconfirmed seed waits on that read
|
|
105
|
+
* alone. Without it, the save waits on every listener unconfirmed at the
|
|
106
|
+
* click, so an unrelated one that is slow, refused or torn down can hold it
|
|
107
|
+
* back or refuse it.
|
|
108
|
+
*/
|
|
109
|
+
listen?: ListenHandle | null;
|
|
41
110
|
/**
|
|
42
111
|
* Also consult `session-health`. On by default; the only reason to turn it
|
|
43
112
|
* off is a surface that deliberately writes during a known-degraded
|
|
@@ -69,7 +138,8 @@ export declare function checkSeedFreshness(options: GuardedSeedWriteOptions): Gu
|
|
|
69
138
|
* A seed that is only UNCONFIRMED is waited for before it is refused
|
|
70
139
|
* (AGL-4120): the save stays in its busy state while the server answers, which
|
|
71
140
|
* is normally a moment. The other reasons are facts about the read or the
|
|
72
|
-
* session that waiting does not change, and they refuse at once.
|
|
141
|
+
* session that waiting does not change, and they refuse at once. A save that
|
|
142
|
+
* names its seed's listener (`listen`) waits on that read alone (AGL-4135).
|
|
73
143
|
*/
|
|
74
144
|
export declare function writeGuardedBySeed(options: GuardedSeedWriteOptions, write: () => Promise<void>): Promise<GuardedSeedWriteResult>;
|
|
75
145
|
export default writeGuardedBySeed;
|
|
@@ -72,7 +72,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
72
72
|
* check simply reports "not stale", which is what the tenant runtime and the
|
|
73
73
|
* unit tests want; the other two signals are unaffected, and they are the
|
|
74
74
|
* ones the doc above says must carry the guard anyway.
|
|
75
|
-
*/ import { whenListensConfirmed } from "./listen-confirmation.js";
|
|
75
|
+
*/ import { whenListenConfirmed, whenListensConfirmed } from "./listen-confirmation.js";
|
|
76
76
|
/**
|
|
77
77
|
* The console's `session-health` verdict, injected because it is app state.
|
|
78
78
|
* Null until the app registers one — see {@link setStaleSessionCheck}.
|
|
@@ -167,7 +167,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
167
167
|
* A seed that is only UNCONFIRMED is waited for before it is refused
|
|
168
168
|
* (AGL-4120): the save stays in its busy state while the server answers, which
|
|
169
169
|
* is normally a moment. The other reasons are facts about the read or the
|
|
170
|
-
* session that waiting does not change, and they refuse at once.
|
|
170
|
+
* session that waiting does not change, and they refuse at once. A save that
|
|
171
|
+
* names its seed's listener (`listen`) waits on that read alone (AGL-4135).
|
|
171
172
|
*/ export async function writeGuardedBySeed(options, write) {
|
|
172
173
|
const verdict = checkSeedFreshness(options);
|
|
173
174
|
if (verdict.ok) {
|
|
@@ -175,7 +176,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
175
176
|
return verdict;
|
|
176
177
|
}
|
|
177
178
|
if (verdict.reason !== 'unconfirmed') return verdict;
|
|
178
|
-
const settlement = await whenListensConfirmed();
|
|
179
|
+
const settlement = options.listen ? await whenListenConfirmed(options.listen) : await whenListensConfirmed();
|
|
179
180
|
if (settlement === 'refreshed') {
|
|
180
181
|
return {
|
|
181
182
|
ok: false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/guarded-seed-write.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 * Refuse a whole-object write whose form was seeded from a read we cannot\n * trust (AGL-1356, AGL-1358, AGL-1066).\n *\n * ## The shape this exists for\n *\n * A form seeded from a Firestore LISTENER, saved with a payload that carries\n * every field rather than the one that changed. `merge: true` protects\n * nothing there — the untouched fields are all present in the payload — so\n * saving one edit rewrites the rest to whatever the seed held. If the seed\n * came from IndexedDB during a stale session, \"whatever the seed held\" can\n * be arbitrarily old, and the user's real values are destroyed by a save\n * they asked for and had every reason to expect to be safe.\n *\n * ## Why it WRAPS the write instead of preceding it\n *\n * The guards this replaces sat in front of their writes as early returns,\n * which is a shape you can have and still write — add a branch, reorder a\n * line, and the guard is decoration. Here the write is only reachable\n * THROUGH the verdict, so a call site cannot keep the guard and lose the\n * protection. It also makes the refusal testable as a refusal: assert the\n * inner function never ran.\n *\n * ## The three signals, in the order they are worth trusting\n *\n * 1. `fromCache` — the server never confirmed what is on screen (AGL-1066).\n * This is the one that catches the dangerous case, because a cache-served\n * read looks completely healthy: populated form, plausible values. It is\n * per-listener ground truth from the SDK, so it needs no threshold and no\n * window, and it clears itself the instant a server snapshot lands. It\n * leads because it is also the more ACCURATE explanation whenever it is\n * true — see the ordering note on `checkSeedFreshness`. It is also the one\n * signal that a little patience answers, so `writeGuardedBySeed` waits for\n * the confirmation before it refuses on this alone (AGL-4120).\n * 2. `unreadable` — the read FAILED and there is nothing cached behind it\n * (AGL-1143). Saving would write blanks over a populated document.\n * 3. `staleSession` — the console's own heuristic. Kept because it means\n * something the other two do not (the SESSION is dead, not merely\n * unconfirmed), but it must never be the ONLY guard: it needs two\n * distinct labelled collections denied inside 60s, which is unreachable\n * on a listener-only page. That was exactly how AGL-1356 stayed open.\n *\n * ## Why this lives in the library rather than the console (AGL-1358)\n *\n * Most of the ~forty sites wearing this shape are plugin cards in\n * `libs/plugins/**`, which cannot import from `apps/console`. The guard\n * itself is pure, and `fromCache` — the signal that actually fires —\n * originates here, on the listener hooks. What it cannot own is\n * `session-health`, which is console state.\n *\n * So the third signal is INJECTED, through the same seam\n * `firestore-denial-reporter` already uses for the reverse direction: the\n * console registers a check at startup and the guard pulls it. That keeps a\n * single guard for every call site with no new dependency edge and nothing\n * inverted — the library still knows nothing about the app. An unregistered\n * check simply reports \"not stale\", which is what the tenant runtime and the\n * unit tests want; the other two signals are unaffected, and they are the\n * ones the doc above says must carry the guard anyway.\n */\n\nimport { whenListensConfirmed } from './listen-confirmation'\n\nexport type StaleSeedReason =\n | 'unreadable'\n | 'unconfirmed'\n | 'stale-session'\n /** The server's confirmation changed the values the form was built from. */\n | 'refreshed'\n\n/**\n * The console's `session-health` verdict, injected because it is app state.\n * Null until the app registers one — see {@link setStaleSessionCheck}.\n */\nlet staleSessionCheck: (() => boolean) | null = null\n\n/**\n * Register the app's stale-session verdict. Called once, by the app that owns\n * `session-health`. Pass `null` to unregister (tests).\n *\n * Registered at module scope alongside `setFirestoreSessionReporters` rather\n * than in an effect, for the same reason: a save can be clicked before any\n * effect has run, and a guard that consults a check which does not exist yet\n * silently loses its third signal.\n */\nexport function setStaleSessionCheck(check: (() => boolean) | null): void {\n staleSessionCheck = check\n}\n\n/** The registered verdict, or `false` when nothing is registered. */\nfunction isSessionStale(): boolean {\n return staleSessionCheck ? staleSessionCheck() : false\n}\n\nexport interface GuardedSeedWriteOptions {\n /**\n * What is being saved, in the user's words — \"profile\", \"settings\".\n * Used to build the refusal message, so it reads naturally in a sentence\n * like \"Your profile could not be loaded\".\n */\n subject: string\n /** The seeding read FAILED (`status === 'error'`). */\n unreadable?: boolean\n /** The seeding snapshot came from cache (`metadata.fromCache`). */\n fromCache?: boolean\n /**\n * Also consult `session-health`. On by default; the only reason to turn it\n * off is a surface that deliberately writes during a known-degraded\n * session.\n */\n checkSession?: boolean\n}\n\nexport interface GuardedSeedWriteResult {\n /** True when the write RAN. */\n ok: boolean\n /** Why it did not run. */\n reason?: StaleSeedReason\n /**\n * What to tell the user. Always populated when `ok` is false — a refused\n * save that says nothing is its own bug: the user retypes the form and\n * tries again, and the second attempt is refused just as silently.\n */\n message?: string\n}\n\n/**\n * Why we refused, in words that say what to DO about it.\n *\n * ## The subject is INTERPOLATED, so nothing here may agree with it (AGL-1446)\n *\n * Call sites pass \"profile\", \"SEO settings\", \"theme overrides\", \"categories\".\n * The copy used to read \"Your SEO settings **has** not been confirmed\", \"so\n * **it** cannot be saved\", \"so **this** SEO settings may be out of date\" —\n * fine for the singular subjects it was written against and wrong for half the\n * ~126 call sites. Every sentence below is number-neutral instead, and\n * `guarded-seed-write.spec.ts` pins all three verbatim against a plural\n * subject so it stays that way.\n *\n * ## What `unconfirmed` may claim (AGL-4120)\n *\n * It used to tell people a tab could be \"permanently cache-only\" and to open a\n * new one, \"because reloading cannot restore a connection this tab never\n * opened\". That theory was wrong twice over. AGL-2486 showed the Listen channel\n * open and answering all along, and AGL-4120 measured what was left: nothing\n * had disconnected, the console's own stall recovery had taken a healthy client\n * off the network. A fresh tab only looked like a cure because it had not been\n * knocked off yet.\n *\n * By the time this reads, the save has waited {@link SEED_CONFIRM_WAIT_MS} for\n * the confirmation. So it says the three things that are true, which are the\n * three a person acting on it needs: the save did not happen, what they typed\n * is still there, and trying again in a moment is the remedy.\n */\nfunction refusalMessage(subject: string, reason: StaleSeedReason): string {\n switch (reason) {\n case 'unreadable':\n return (\n `Your ${subject} could not be loaded, so there is nothing safe to ` +\n 'save — saving now would overwrite the stored copy with blanks. ' +\n 'Reload and try again.'\n )\n case 'unconfirmed':\n return (\n `We could not confirm your ${subject} with the server yet, so nothing ` +\n 'was saved. What you entered is still here. Check your connection and ' +\n 'save again in a moment.'\n )\n case 'refreshed':\n return (\n `Your ${subject} just updated from the server, so nothing was saved ` +\n 'yet. Check the latest values, then save again.'\n )\n case 'stale-session':\n return (\n `Your session went stale, so your ${subject} may be out of date — ` +\n 'saving now could overwrite newer values. Sign in again and reload.'\n )\n }\n}\n\n/** The verdict on its own, for a caller that needs it before the click. */\nexport function checkSeedFreshness(\n options: GuardedSeedWriteOptions,\n): GuardedSeedWriteResult {\n const { subject, unreadable, fromCache, checkSession = true } = options\n /**\n * `fromCache` OUTRANKS `unreadable` (AGL-1066).\n *\n * It did not, and the ordering was harmless only while a refused listen\n * could never reach `status: 'error'`. Now that it can, the common case is\n * BOTH flags true at once — the cache is serving the document and the\n * server has stopped answering for it — and taking `unreadable` there\n * tells the user their settings \"could not be loaded\" and that saving\n * \"would overwrite it with blanks\", while a populated, plausible form sits\n * in front of them. The refusal is right; that explanation is not, and a\n * refusal whose reason is visibly false is one the user works around.\n *\n * What is left to `unreadable` is the read that failed with nothing to\n * show for it, which is the AGL-1143 case it was written for and where the\n * blanks are real. The heuristic still comes last.\n */\n const reason: StaleSeedReason | undefined = fromCache\n ? 'unconfirmed'\n : unreadable\n ? 'unreadable'\n : checkSession && isSessionStale()\n ? 'stale-session'\n : undefined\n if (!reason) return { ok: true }\n return { ok: false, reason, message: refusalMessage(subject, reason) }\n}\n\n/**\n * Run `write` only if the seed can be trusted.\n *\n * Never throws on refusal — the caller reports `message` and leaves the\n * user's typed values on screen, because the whole point is that we are not\n * confident enough to touch the stored document, not that the input was bad.\n *\n * A seed that is only UNCONFIRMED is waited for before it is refused\n * (AGL-4120): the save stays in its busy state while the server answers, which\n * is normally a moment. The other reasons are facts about the read or the\n * session that waiting does not change, and they refuse at once.\n */\nexport async function writeGuardedBySeed(\n options: GuardedSeedWriteOptions,\n write: () => Promise<void>,\n): Promise<GuardedSeedWriteResult> {\n const verdict = checkSeedFreshness(options)\n if (verdict.ok) {\n await write()\n return verdict\n }\n if (verdict.reason !== 'unconfirmed') return verdict\n const settlement = await whenListensConfirmed()\n if (settlement === 'refreshed') {\n return {\n ok: false,\n reason: 'refreshed',\n message: refusalMessage(options.subject, 'refreshed'),\n }\n }\n if (settlement !== 'confirmed') return verdict\n // The wait took time, and the session may not have survived it.\n const confirmed = checkSeedFreshness({ ...options, fromCache: false })\n if (!confirmed.ok) return confirmed\n await write()\n return confirmed\n}\n\nexport default writeGuardedBySeed\n"],"names":["whenListensConfirmed","staleSessionCheck","setStaleSessionCheck","check","isSessionStale","refusalMessage","subject","reason","checkSeedFreshness","options","unreadable","fromCache","checkSession","undefined","ok","message","writeGuardedBySeed","write","verdict","settlement","confirmed"],"mappings":";AAAA;;;;;;;;;;;;;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A,QAAQX,MAAM,KAAK,eAAe,OAAOW;IAC7C,MAAMC,aAAa,MAAMnB;IACzB,IAAImB,eAAe,aAAa;QAC9B,OAAO;YACLL,IAAI;YACJP,QAAQ;YACRQ,SAASV,eAAeI,QAAQH,OAAO,EAAE;QAC3C;IACF;IACA,IAAIa,eAAe,aAAa,OAAOD;IACvC,gEAAgE;IAChE,MAAME,YAAYZ,mBAAmB,aAAKC;QAASE,WAAW;;IAC9D,IAAI,CAACS,UAAUN,EAAE,EAAE,OAAOM;IAC1B,MAAMH;IACN,OAAOG;AACT;AAEA,eAAeJ,mBAAkB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/guarded-seed-write.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 * Refuse a whole-object write whose form was seeded from a read we cannot\n * trust (AGL-1356, AGL-1358, AGL-1066).\n *\n * ## The shape this exists for\n *\n * A form seeded from a Firestore LISTENER, saved with a payload that carries\n * every field rather than the one that changed. `merge: true` protects\n * nothing there — the untouched fields are all present in the payload — so\n * saving one edit rewrites the rest to whatever the seed held. If the seed\n * came from IndexedDB during a stale session, \"whatever the seed held\" can\n * be arbitrarily old, and the user's real values are destroyed by a save\n * they asked for and had every reason to expect to be safe.\n *\n * ## Why it WRAPS the write instead of preceding it\n *\n * The guards this replaces sat in front of their writes as early returns,\n * which is a shape you can have and still write — add a branch, reorder a\n * line, and the guard is decoration. Here the write is only reachable\n * THROUGH the verdict, so a call site cannot keep the guard and lose the\n * protection. It also makes the refusal testable as a refusal: assert the\n * inner function never ran.\n *\n * ## The three signals, in the order they are worth trusting\n *\n * 1. `fromCache` — the server never confirmed what is on screen (AGL-1066).\n * This is the one that catches the dangerous case, because a cache-served\n * read looks completely healthy: populated form, plausible values. It is\n * per-listener ground truth from the SDK, so it needs no threshold and no\n * window, and it clears itself the instant a server snapshot lands. It\n * leads because it is also the more ACCURATE explanation whenever it is\n * true — see the ordering note on `checkSeedFreshness`. It is also the one\n * signal that a little patience answers, so `writeGuardedBySeed` waits for\n * the confirmation before it refuses on this alone (AGL-4120).\n * 2. `unreadable` — the read FAILED and there is nothing cached behind it\n * (AGL-1143). Saving would write blanks over a populated document.\n * 3. `staleSession` — the console's own heuristic. Kept because it means\n * something the other two do not (the SESSION is dead, not merely\n * unconfirmed), but it must never be the ONLY guard: it needs two\n * distinct labelled collections denied inside 60s, which is unreachable\n * on a listener-only page. That was exactly how AGL-1356 stayed open.\n *\n * ## Why this lives in the library rather than the console (AGL-1358)\n *\n * Most of the ~forty sites wearing this shape are plugin cards in\n * `libs/plugins/**`, which cannot import from `apps/console`. The guard\n * itself is pure, and `fromCache` — the signal that actually fires —\n * originates here, on the listener hooks. What it cannot own is\n * `session-health`, which is console state.\n *\n * So the third signal is INJECTED, through the same seam\n * `firestore-denial-reporter` already uses for the reverse direction: the\n * console registers a check at startup and the guard pulls it. That keeps a\n * single guard for every call site with no new dependency edge and nothing\n * inverted — the library still knows nothing about the app. An unregistered\n * check simply reports \"not stale\", which is what the tenant runtime and the\n * unit tests want; the other two signals are unaffected, and they are the\n * ones the doc above says must carry the guard anyway.\n */\n\nimport {\n whenListenConfirmed,\n whenListensConfirmed,\n type ListenHandle,\n} from './listen-confirmation'\n\nexport type { ListenHandle } from './listen-confirmation'\n\nexport type StaleSeedReason =\n | 'unreadable'\n | 'unconfirmed'\n | 'stale-session'\n /** The server's confirmation changed the values the form was built from. */\n | 'refreshed'\n\n/**\n * The console's `session-health` verdict, injected because it is app state.\n * Null until the app registers one — see {@link setStaleSessionCheck}.\n */\nlet staleSessionCheck: (() => boolean) | null = null\n\n/**\n * Register the app's stale-session verdict. Called once, by the app that owns\n * `session-health`. Pass `null` to unregister (tests).\n *\n * Registered at module scope alongside `setFirestoreSessionReporters` rather\n * than in an effect, for the same reason: a save can be clicked before any\n * effect has run, and a guard that consults a check which does not exist yet\n * silently loses its third signal.\n */\nexport function setStaleSessionCheck(check: (() => boolean) | null): void {\n staleSessionCheck = check\n}\n\n/** The registered verdict, or `false` when nothing is registered. */\nfunction isSessionStale(): boolean {\n return staleSessionCheck ? staleSessionCheck() : false\n}\n\nexport interface GuardedSeedWriteOptions {\n /**\n * What is being saved, in the user's words — \"profile\", \"settings\".\n * Used to build the refusal message, so it reads naturally in a sentence\n * like \"Your profile could not be loaded\".\n */\n subject: string\n /** The seeding read FAILED (`status === 'error'`). */\n unreadable?: boolean\n /** The seeding snapshot came from cache (`metadata.fromCache`). */\n fromCache?: boolean\n /**\n * The listener the seed came from: `listen` on the hook that gave\n * `fromCache` (AGL-4135). With it, an unconfirmed seed waits on that read\n * alone. Without it, the save waits on every listener unconfirmed at the\n * click, so an unrelated one that is slow, refused or torn down can hold it\n * back or refuse it.\n */\n listen?: ListenHandle | null\n /**\n * Also consult `session-health`. On by default; the only reason to turn it\n * off is a surface that deliberately writes during a known-degraded\n * session.\n */\n checkSession?: boolean\n}\n\nexport interface GuardedSeedWriteResult {\n /** True when the write RAN. */\n ok: boolean\n /** Why it did not run. */\n reason?: StaleSeedReason\n /**\n * What to tell the user. Always populated when `ok` is false — a refused\n * save that says nothing is its own bug: the user retypes the form and\n * tries again, and the second attempt is refused just as silently.\n */\n message?: string\n}\n\n/**\n * Why we refused, in words that say what to DO about it.\n *\n * ## The subject is INTERPOLATED, so nothing here may agree with it (AGL-1446)\n *\n * Call sites pass \"profile\", \"SEO settings\", \"theme overrides\", \"categories\".\n * The copy used to read \"Your SEO settings **has** not been confirmed\", \"so\n * **it** cannot be saved\", \"so **this** SEO settings may be out of date\" —\n * fine for the singular subjects it was written against and wrong for half the\n * ~126 call sites. Every sentence below is number-neutral instead, and\n * `guarded-seed-write.spec.ts` pins all three verbatim against a plural\n * subject so it stays that way.\n *\n * ## What `unconfirmed` may claim (AGL-4120)\n *\n * It used to tell people a tab could be \"permanently cache-only\" and to open a\n * new one, \"because reloading cannot restore a connection this tab never\n * opened\". That theory was wrong twice over. AGL-2486 showed the Listen channel\n * open and answering all along, and AGL-4120 measured what was left: nothing\n * had disconnected, the console's own stall recovery had taken a healthy client\n * off the network. A fresh tab only looked like a cure because it had not been\n * knocked off yet.\n *\n * By the time this reads, the save has waited {@link SEED_CONFIRM_WAIT_MS} for\n * the confirmation. So it says the three things that are true, which are the\n * three a person acting on it needs: the save did not happen, what they typed\n * is still there, and trying again in a moment is the remedy.\n */\nfunction refusalMessage(subject: string, reason: StaleSeedReason): string {\n switch (reason) {\n case 'unreadable':\n return (\n `Your ${subject} could not be loaded, so there is nothing safe to ` +\n 'save — saving now would overwrite the stored copy with blanks. ' +\n 'Reload and try again.'\n )\n case 'unconfirmed':\n return (\n `We could not confirm your ${subject} with the server yet, so nothing ` +\n 'was saved. What you entered is still here. Check your connection and ' +\n 'save again in a moment.'\n )\n case 'refreshed':\n return (\n `Your ${subject} just updated from the server, so nothing was saved ` +\n 'yet. Check the latest values, then save again.'\n )\n case 'stale-session':\n return (\n `Your session went stale, so your ${subject} may be out of date — ` +\n 'saving now could overwrite newer values. Sign in again and reload.'\n )\n }\n}\n\n/** The verdict on its own, for a caller that needs it before the click. */\nexport function checkSeedFreshness(\n options: GuardedSeedWriteOptions,\n): GuardedSeedWriteResult {\n const { subject, unreadable, fromCache, checkSession = true } = options\n /**\n * `fromCache` OUTRANKS `unreadable` (AGL-1066).\n *\n * It did not, and the ordering was harmless only while a refused listen\n * could never reach `status: 'error'`. Now that it can, the common case is\n * BOTH flags true at once — the cache is serving the document and the\n * server has stopped answering for it — and taking `unreadable` there\n * tells the user their settings \"could not be loaded\" and that saving\n * \"would overwrite it with blanks\", while a populated, plausible form sits\n * in front of them. The refusal is right; that explanation is not, and a\n * refusal whose reason is visibly false is one the user works around.\n *\n * What is left to `unreadable` is the read that failed with nothing to\n * show for it, which is the AGL-1143 case it was written for and where the\n * blanks are real. The heuristic still comes last.\n */\n const reason: StaleSeedReason | undefined = fromCache\n ? 'unconfirmed'\n : unreadable\n ? 'unreadable'\n : checkSession && isSessionStale()\n ? 'stale-session'\n : undefined\n if (!reason) return { ok: true }\n return { ok: false, reason, message: refusalMessage(subject, reason) }\n}\n\n/**\n * Run `write` only if the seed can be trusted.\n *\n * Never throws on refusal — the caller reports `message` and leaves the\n * user's typed values on screen, because the whole point is that we are not\n * confident enough to touch the stored document, not that the input was bad.\n *\n * A seed that is only UNCONFIRMED is waited for before it is refused\n * (AGL-4120): the save stays in its busy state while the server answers, which\n * is normally a moment. The other reasons are facts about the read or the\n * session that waiting does not change, and they refuse at once. A save that\n * names its seed's listener (`listen`) waits on that read alone (AGL-4135).\n */\nexport async function writeGuardedBySeed(\n options: GuardedSeedWriteOptions,\n write: () => Promise<void>,\n): Promise<GuardedSeedWriteResult> {\n const verdict = checkSeedFreshness(options)\n if (verdict.ok) {\n await write()\n return verdict\n }\n if (verdict.reason !== 'unconfirmed') return verdict\n const settlement = options.listen\n ? await whenListenConfirmed(options.listen)\n : await whenListensConfirmed()\n if (settlement === 'refreshed') {\n return {\n ok: false,\n reason: 'refreshed',\n message: refusalMessage(options.subject, 'refreshed'),\n }\n }\n if (settlement !== 'confirmed') return verdict\n // The wait took time, and the session may not have survived it.\n const confirmed = checkSeedFreshness({ ...options, fromCache: false })\n if (!confirmed.ok) return confirmed\n await write()\n return confirmed\n}\n\nexport default writeGuardedBySeed\n"],"names":["whenListenConfirmed","whenListensConfirmed","staleSessionCheck","setStaleSessionCheck","check","isSessionStale","refusalMessage","subject","reason","checkSeedFreshness","options","unreadable","fromCache","checkSession","undefined","ok","message","writeGuardedBySeed","write","verdict","settlement","listen","confirmed"],"mappings":";AAAA;;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G;QACN,OAAOC;IACT;IACA,IAAIA,QAAQX,MAAM,KAAK,eAAe,OAAOW;IAC7C,MAAMC,aAAaV,QAAQW,MAAM,GAC7B,MAAMrB,oBAAoBU,QAAQW,MAAM,IACxC,MAAMpB;IACV,IAAImB,eAAe,aAAa;QAC9B,OAAO;YACLL,IAAI;YACJP,QAAQ;YACRQ,SAASV,eAAeI,QAAQH,OAAO,EAAE;QAC3C;IACF;IACA,IAAIa,eAAe,aAAa,OAAOD;IACvC,gEAAgE;IAChE,MAAMG,YAAYb,mBAAmB,aAAKC;QAASE,WAAW;;IAC9D,IAAI,CAACU,UAAUP,EAAE,EAAE,OAAOO;IAC1B,MAAMJ;IACN,OAAOI;AACT;AAEA,eAAeL,mBAAkB"}
|
|
@@ -31,10 +31,23 @@
|
|
|
31
31
|
*
|
|
32
32
|
* ## Which listeners
|
|
33
33
|
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
34
|
+
* The seed's own, when the save names it (AGL-4135). Each hook that produces
|
|
35
|
+
* `fromCache` also returns a {@link ListenHandle}, which always points at that
|
|
36
|
+
* hook's current listener, and a call site that passes it to the guard waits
|
|
37
|
+
* on that read alone ({@link whenListenConfirmed}).
|
|
38
|
+
*
|
|
39
|
+
* Otherwise all of them, because the guard cannot name its own. That errs one
|
|
40
|
+
* way only: a listener nobody is saving can make a save wait, or refuse it, by
|
|
41
|
+
* being slow, refused or torn down during the wait. It can never let a save
|
|
42
|
+
* through on an unconfirmed seed, because the seed's own listener is in the set
|
|
43
|
+
* being waited on. Measured in production with another tab starving the shared
|
|
44
|
+
* cache (AGL-4135), every listener on a page is slow at once, so waiting on all
|
|
45
|
+
* of them is waiting on the slowest one.
|
|
46
|
+
*
|
|
47
|
+
* Waiting on one listener keeps the same promise. A refusal or a teardown
|
|
48
|
+
* never counts as a confirmation: the wait goes on, for the retry that reports
|
|
49
|
+
* again or for the listener that replaces it, and ends unconfirmed at the
|
|
50
|
+
* deadline if neither comes.
|
|
38
51
|
*
|
|
39
52
|
* ## A confirmation can change what is on screen
|
|
40
53
|
*
|
|
@@ -81,6 +94,18 @@ export type ListenSettlement =
|
|
|
81
94
|
* is not one this module can vouch for. The caller's answer stands.
|
|
82
95
|
*/
|
|
83
96
|
| 'untracked';
|
|
97
|
+
declare const listenHandleBrand: unique symbol;
|
|
98
|
+
/**
|
|
99
|
+
* One hook's listener, for a save that waits on it alone (AGL-4135). Stable
|
|
100
|
+
* for the life of the hook, and always points at the hook's CURRENT listener,
|
|
101
|
+
* so a listener replaced during the wait (new deps, a reopen) is the one
|
|
102
|
+
* waited on. Opaque: a call site only hands it to `writeGuardedBySeed`.
|
|
103
|
+
*/
|
|
104
|
+
export interface ListenHandle {
|
|
105
|
+
readonly [listenHandleBrand]: true;
|
|
106
|
+
}
|
|
107
|
+
/** A handle for one hook instance. Create it once (`useState(createListenHandle)`). */
|
|
108
|
+
export declare function createListenHandle(): ListenHandle;
|
|
84
109
|
export interface ListenConfirmation {
|
|
85
110
|
/**
|
|
86
111
|
* A snapshot arrived. `changed` says a confirmation brought different values
|
|
@@ -88,17 +113,39 @@ export interface ListenConfirmation {
|
|
|
88
113
|
* it cannot have changed anything.
|
|
89
114
|
*/
|
|
90
115
|
report: (fromCache: boolean, changed?: boolean) => void;
|
|
91
|
-
/**
|
|
116
|
+
/**
|
|
117
|
+
* The listener was refused. A wait on every listener ends unconfirmed; a wait
|
|
118
|
+
* on this one goes on, for the retry.
|
|
119
|
+
*/
|
|
92
120
|
release: () => void;
|
|
121
|
+
/**
|
|
122
|
+
* The listener was torn down. As `release`, and its handle no longer points
|
|
123
|
+
* at it, so a wait on this one goes on for the listener that replaces it.
|
|
124
|
+
*/
|
|
125
|
+
close: () => void;
|
|
93
126
|
}
|
|
94
127
|
/**
|
|
95
128
|
* One listener's line in the record. Unconfirmed from the start, for the same
|
|
96
|
-
* reason every hook's `fromCache` state starts true.
|
|
129
|
+
* reason every hook's `fromCache` state starts true. With `handle`, the handle
|
|
130
|
+
* points at this listener from now on.
|
|
97
131
|
*/
|
|
98
|
-
export declare function trackListenConfirmation(): ListenConfirmation;
|
|
132
|
+
export declare function trackListenConfirmation(handle?: ListenHandle): ListenConfirmation;
|
|
99
133
|
/**
|
|
100
134
|
* Resolves when every listener unconfirmed right now has settled, or after
|
|
101
135
|
* `timeoutMs`. Never rejects.
|
|
102
136
|
*/
|
|
103
137
|
export declare function whenListensConfirmed(timeoutMs?: number): Promise<ListenSettlement>;
|
|
138
|
+
/**
|
|
139
|
+
* Resolves when the listener `handle` points at is confirmed, or after
|
|
140
|
+
* `timeoutMs` (AGL-4135). Never rejects.
|
|
141
|
+
*
|
|
142
|
+
* - **Already confirmed**: at once, `refreshed` if that confirmation changed
|
|
143
|
+
* the values on screen. The caller read `fromCache` before it landed.
|
|
144
|
+
* - **Unconfirmed, refused or torn down**: waits. A refused listener retries
|
|
145
|
+
* and reports again; a torn-down one is replaced, and the handle points at
|
|
146
|
+
* the replacement. Neither is ever taken for a confirmation.
|
|
147
|
+
* - **No listener behind the handle** (its hook has not listened, or has
|
|
148
|
+
* stopped): `untracked`, so the caller's answer stands.
|
|
149
|
+
*/
|
|
150
|
+
export declare function whenListenConfirmed(handle: ListenHandle, timeoutMs?: number): Promise<ListenSettlement>;
|
|
104
151
|
export {};
|
|
@@ -30,10 +30,23 @@
|
|
|
30
30
|
*
|
|
31
31
|
* ## Which listeners
|
|
32
32
|
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
33
|
+
* The seed's own, when the save names it (AGL-4135). Each hook that produces
|
|
34
|
+
* `fromCache` also returns a {@link ListenHandle}, which always points at that
|
|
35
|
+
* hook's current listener, and a call site that passes it to the guard waits
|
|
36
|
+
* on that read alone ({@link whenListenConfirmed}).
|
|
37
|
+
*
|
|
38
|
+
* Otherwise all of them, because the guard cannot name its own. That errs one
|
|
39
|
+
* way only: a listener nobody is saving can make a save wait, or refuse it, by
|
|
40
|
+
* being slow, refused or torn down during the wait. It can never let a save
|
|
41
|
+
* through on an unconfirmed seed, because the seed's own listener is in the set
|
|
42
|
+
* being waited on. Measured in production with another tab starving the shared
|
|
43
|
+
* cache (AGL-4135), every listener on a page is slow at once, so waiting on all
|
|
44
|
+
* of them is waiting on the slowest one.
|
|
45
|
+
*
|
|
46
|
+
* Waiting on one listener keeps the same promise. A refusal or a teardown
|
|
47
|
+
* never counts as a confirmation: the wait goes on, for the retry that reports
|
|
48
|
+
* again or for the listener that replaces it, and ends unconfirmed at the
|
|
49
|
+
* deadline if neither comes.
|
|
37
50
|
*
|
|
38
51
|
* ## A confirmation can change what is on screen
|
|
39
52
|
*
|
|
@@ -64,8 +77,15 @@ let confirmWaitMs = SEED_CONFIRM_WAIT_MS;
|
|
|
64
77
|
if (a.exists() !== b.exists()) return false;
|
|
65
78
|
return JSON.stringify(a.data()) === JSON.stringify(b.data());
|
|
66
79
|
}
|
|
80
|
+
/** A handle for one hook instance. Create it once (`useState(createListenHandle)`). */ export function createListenHandle() {
|
|
81
|
+
const state = {
|
|
82
|
+
token: null
|
|
83
|
+
};
|
|
84
|
+
return state;
|
|
85
|
+
}
|
|
67
86
|
const unconfirmed = new Set();
|
|
68
87
|
const waiters = new Set();
|
|
88
|
+
const seedWaiters = new Set();
|
|
69
89
|
function settleWaiters(token, how) {
|
|
70
90
|
for (const waiter of [
|
|
71
91
|
...waiters
|
|
@@ -78,28 +98,54 @@ function settleWaiters(token, how) {
|
|
|
78
98
|
else waiter.finish(waiter.refreshed ? 'refreshed' : 'confirmed');
|
|
79
99
|
}
|
|
80
100
|
}
|
|
101
|
+
function settleSeedWaiters(token) {
|
|
102
|
+
for (const waiter of [
|
|
103
|
+
...seedWaiters
|
|
104
|
+
]){
|
|
105
|
+
if (waiter.handle.token !== token) continue;
|
|
106
|
+
waiter.finish(token.changed ? 'refreshed' : 'confirmed');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
81
109
|
/**
|
|
82
110
|
* One listener's line in the record. Unconfirmed from the start, for the same
|
|
83
|
-
* reason every hook's `fromCache` state starts true.
|
|
84
|
-
|
|
85
|
-
|
|
111
|
+
* reason every hook's `fromCache` state starts true. With `handle`, the handle
|
|
112
|
+
* points at this listener from now on.
|
|
113
|
+
*/ export function trackListenConfirmation(handle) {
|
|
114
|
+
const token = {
|
|
115
|
+
state: 'unconfirmed',
|
|
116
|
+
changed: false
|
|
117
|
+
};
|
|
86
118
|
unconfirmed.add(token);
|
|
119
|
+
const bound = handle;
|
|
120
|
+
if (bound) bound.token = token;
|
|
121
|
+
const release = ()=>{
|
|
122
|
+
token.state = 'released';
|
|
123
|
+
token.changed = false;
|
|
124
|
+
unconfirmed.delete(token);
|
|
125
|
+
settleWaiters(token, {
|
|
126
|
+
lost: true
|
|
127
|
+
});
|
|
128
|
+
};
|
|
87
129
|
return {
|
|
88
130
|
report: (fromCache, changed = false)=>{
|
|
89
131
|
if (fromCache) {
|
|
132
|
+
token.state = 'unconfirmed';
|
|
133
|
+
token.changed = false;
|
|
90
134
|
unconfirmed.add(token);
|
|
91
135
|
return;
|
|
92
136
|
}
|
|
137
|
+
token.state = 'confirmed';
|
|
138
|
+
token.changed = changed;
|
|
93
139
|
unconfirmed.delete(token);
|
|
94
140
|
settleWaiters(token, {
|
|
95
141
|
changed
|
|
96
142
|
});
|
|
143
|
+
settleSeedWaiters(token);
|
|
97
144
|
},
|
|
98
|
-
release
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
});
|
|
145
|
+
release,
|
|
146
|
+
close: ()=>{
|
|
147
|
+
release();
|
|
148
|
+
if ((bound == null ? void 0 : bound.token) === token) bound.token = null;
|
|
103
149
|
}
|
|
104
150
|
};
|
|
105
151
|
}
|
|
@@ -123,5 +169,36 @@ function settleWaiters(token, how) {
|
|
|
123
169
|
waiters.add(waiter);
|
|
124
170
|
});
|
|
125
171
|
}
|
|
172
|
+
/**
|
|
173
|
+
* Resolves when the listener `handle` points at is confirmed, or after
|
|
174
|
+
* `timeoutMs` (AGL-4135). Never rejects.
|
|
175
|
+
*
|
|
176
|
+
* - **Already confirmed**: at once, `refreshed` if that confirmation changed
|
|
177
|
+
* the values on screen. The caller read `fromCache` before it landed.
|
|
178
|
+
* - **Unconfirmed, refused or torn down**: waits. A refused listener retries
|
|
179
|
+
* and reports again; a torn-down one is replaced, and the handle points at
|
|
180
|
+
* the replacement. Neither is ever taken for a confirmation.
|
|
181
|
+
* - **No listener behind the handle** (its hook has not listened, or has
|
|
182
|
+
* stopped): `untracked`, so the caller's answer stands.
|
|
183
|
+
*/ export function whenListenConfirmed(handle, timeoutMs = confirmWaitMs) {
|
|
184
|
+
const state = handle;
|
|
185
|
+
const token = state.token;
|
|
186
|
+
if (!token) return Promise.resolve('untracked');
|
|
187
|
+
if (token.state === 'confirmed') {
|
|
188
|
+
return Promise.resolve(token.changed ? 'refreshed' : 'confirmed');
|
|
189
|
+
}
|
|
190
|
+
return new Promise((resolve)=>{
|
|
191
|
+
const waiter = {
|
|
192
|
+
handle: state,
|
|
193
|
+
finish: (settlement)=>{
|
|
194
|
+
clearTimeout(timer);
|
|
195
|
+
seedWaiters.delete(waiter);
|
|
196
|
+
resolve(settlement);
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
const timer = setTimeout(()=>waiter.finish('unconfirmed'), timeoutMs);
|
|
200
|
+
seedWaiters.add(waiter);
|
|
201
|
+
});
|
|
202
|
+
}
|
|
126
203
|
|
|
127
204
|
//# sourceMappingURL=listen-confirmation.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/listen-confirmation.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 LISTENERS THE SERVER HAS NOT CONFIRMED YET, FOR A SAVE THAT NEEDS ONE\n * (AGL-4120).\n *\n * `writeGuardedBySeed` was handed one boolean, read when the button was\n * clicked, and refused the moment it was true. So a save made a second before\n * the server answered was thrown back at the person who made it, with an\n * instruction to reload — though nothing was wrong and waiting would have\n * done. Under load that window ran to a minute (measured in production, beta.297).\n *\n * A guard cannot watch a value it was passed by copy, and fifty-eight call\n * sites pass one. So the four hooks that produce `fromCache` report here, and\n * the guard asks this module instead of its caller: every listener that was\n * unconfirmed at the click has now heard from the server.\n *\n * ## Which listeners\n *\n * All of them, because the guard cannot name its own. That errs one way only:\n * a listener nobody is saving can make a save wait, or ask for one more click.\n * It can never let a save through on an unconfirmed seed, because the seed's\n * own listener is in the set being waited on.\n *\n * ## A confirmation can change what is on screen\n *\n * The seed being protected may be out of date, which is the whole point of the\n * guard. When a listener's confirmation brought values that differ from the\n * ones it had shown, the form the person edited was built from the old ones,\n * so writing it now would overwrite the new ones: the exact loss the guard\n * exists to stop. That settles as `refreshed` and the save is refused for one\n * click, so they see the new values first.\n */\n\n/**\n * How long a save waits for a confirmation before saying so. Past the 8 s stall\n * window, so a client that really is silent has been recovered by the time the\n * wait ends, and short enough to read as a slow save rather than a dead button.\n */\nexport const SEED_CONFIRM_WAIT_MS = 12_000\n\nlet confirmWaitMs = SEED_CONFIRM_WAIT_MS\n\n/**\n * How long a save waits. For a spec that pins what happens when the confirmation\n * never comes, which is the refusal and not the wait: pass `0`, and restore the\n * default (no argument) when done, the way `setStaleSessionCheck` is unregistered.\n */\nexport function setSeedConfirmWaitMs(ms: number = SEED_CONFIRM_WAIT_MS): void {\n confirmWaitMs = ms\n}\n\n/** The part of a document snapshot {@link sameDocument} reads. */\ninterface DocumentValues {\n exists: () => boolean\n data: () => unknown\n}\n\n/**\n * Whether two snapshots of one document hold the same values. Read only on the\n * step from a cached snapshot to a confirmed one, never on every update, because\n * the SDK hands a doc listener no list of what changed.\n */\nexport function sameDocument(a: DocumentValues, b: DocumentValues): boolean {\n if (a.exists() !== b.exists()) return false\n return JSON.stringify(a.data()) === JSON.stringify(b.data())\n}\n\n/** How the wait ended. */\nexport type ListenSettlement =\n /** Every listener that was unconfirmed at the start has heard from the server. */\n | 'confirmed'\n /** They did, and at least one brought different values from the ones it showed. */\n | 'refreshed'\n /** The wait ran out, or a listener was refused or went away before answering. */\n | 'unconfirmed'\n /**\n * No listener here was unconfirmed, so whatever said the seed is unconfirmed\n * is not one this module can vouch for. The caller's answer stands.\n */\n | 'untracked'\n\ninterface Waiter {\n pending: Set<object>\n refreshed: boolean\n lost: boolean\n finish: (settlement: ListenSettlement) => void\n}\n\nconst unconfirmed = new Set<object>()\nconst waiters = new Set<Waiter>()\n\nfunction settleWaiters(token: object, how: { changed?: boolean; lost?: boolean }) {\n for (const waiter of [...waiters]) {\n if (!waiter.pending.delete(token)) continue\n if (how.changed) waiter.refreshed = true\n if (how.lost) waiter.lost = true\n if (waiter.pending.size > 0) continue\n if (waiter.lost) waiter.finish('unconfirmed')\n else waiter.finish(waiter.refreshed ? 'refreshed' : 'confirmed')\n }\n}\n\nexport interface ListenConfirmation {\n /**\n * A snapshot arrived. `changed` says a confirmation brought different values\n * from the ones this listener had shown; a first answer showed nothing, so\n * it cannot have changed anything.\n */\n report: (fromCache: boolean, changed?: boolean) => void\n /** The listener stopped without a confirmation: refused, or torn down. */\n release: () => void\n}\n\n/**\n * One listener's line in the record. Unconfirmed from the start, for the same\n * reason every hook's `fromCache` state starts true.\n */\nexport function trackListenConfirmation(): ListenConfirmation {\n const token = {}\n unconfirmed.add(token)\n return {\n report: (fromCache, changed = false) => {\n if (fromCache) {\n unconfirmed.add(token)\n return\n }\n unconfirmed.delete(token)\n settleWaiters(token, { changed })\n },\n release: () => {\n unconfirmed.delete(token)\n settleWaiters(token, { lost: true })\n },\n }\n}\n\n/**\n * Resolves when every listener unconfirmed right now has settled, or after\n * `timeoutMs`. Never rejects.\n */\nexport function whenListensConfirmed(\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n if (unconfirmed.size === 0) return Promise.resolve('untracked')\n return new Promise((resolve) => {\n const waiter: Waiter = {\n pending: new Set(unconfirmed),\n refreshed: false,\n lost: false,\n finish: (settlement) => {\n clearTimeout(timer)\n waiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n waiters.add(waiter)\n })\n}\n"],"names":["SEED_CONFIRM_WAIT_MS","confirmWaitMs","setSeedConfirmWaitMs","ms","sameDocument","a","b","exists","JSON","stringify","data","unconfirmed","Set","waiters","settleWaiters","token","how","waiter","pending","delete","changed","refreshed","lost","size","finish","trackListenConfirmation","add","report","fromCache","release","whenListensConfirmed","timeoutMs","Promise","resolve","settlement","clearTimeout","timer","setTimeout"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GAED;;;;CAIC,GACD,OAAO,MAAMA,uBAAuB,MAAM;AAE1C,IAAIC,gBAAgBD;AAEpB;;;;CAIC,GACD,OAAO,SAASE,qBAAqBC,KAAaH,oBAAoB;IACpEC,gBAAgBE;AAClB;AAQA;;;;CAIC,GACD,OAAO,SAASC,aAAaC,CAAiB,EAAEC,CAAiB;IAC/D,IAAID,EAAEE,MAAM,OAAOD,EAAEC,MAAM,IAAI,OAAO;IACtC,OAAOC,KAAKC,SAAS,CAACJ,EAAEK,IAAI,QAAQF,KAAKC,SAAS,CAACH,EAAEI,IAAI;AAC3D;AAuBA,MAAMC,cAAc,IAAIC;AACxB,MAAMC,UAAU,IAAID;AAEpB,SAASE,cAAcC,KAAa,EAAEC,GAA0C;IAC9E,KAAK,MAAMC,UAAU;WAAIJ;KAAQ,CAAE;QACjC,IAAI,CAACI,OAAOC,OAAO,CAACC,MAAM,CAACJ,QAAQ;QACnC,IAAIC,IAAII,OAAO,EAAEH,OAAOI,SAAS,GAAG;QACpC,IAAIL,IAAIM,IAAI,EAAEL,OAAOK,IAAI,GAAG;QAC5B,IAAIL,OAAOC,OAAO,CAACK,IAAI,GAAG,GAAG;QAC7B,IAAIN,OAAOK,IAAI,EAAEL,OAAOO,MAAM,CAAC;aAC1BP,OAAOO,MAAM,CAACP,OAAOI,SAAS,GAAG,cAAc;IACtD;AACF;AAaA;;;CAGC,GACD,OAAO,SAASI;IACd,MAAMV,QAAQ,CAAC;IACfJ,YAAYe,GAAG,CAACX;IAChB,OAAO;QACLY,QAAQ,CAACC,WAAWR,UAAU,KAAK;YACjC,IAAIQ,WAAW;gBACbjB,YAAYe,GAAG,CAACX;gBAChB;YACF;YACAJ,YAAYQ,MAAM,CAACJ;YACnBD,cAAcC,OAAO;gBAAEK;YAAQ;QACjC;QACAS,SAAS;YACPlB,YAAYQ,MAAM,CAACJ;YACnBD,cAAcC,OAAO;gBAAEO,MAAM;YAAK;QACpC;IACF;AACF;AAEA;;;CAGC,GACD,OAAO,SAASQ,qBACdC,YAAoB9B,aAAa;IAEjC,IAAIU,YAAYY,IAAI,KAAK,GAAG,OAAOS,QAAQC,OAAO,CAAC;IACnD,OAAO,IAAID,QAAQ,CAACC;QAClB,MAAMhB,SAAiB;YACrBC,SAAS,IAAIN,IAAID;YACjBU,WAAW;YACXC,MAAM;YACNE,QAAQ,CAACU;gBACPC,aAAaC;gBACbvB,QAAQM,MAAM,CAACF;gBACfgB,QAAQC;YACV;QACF;QACA,MAAME,QAAQC,WAAW,IAAMpB,OAAOO,MAAM,CAAC,gBAAgBO;QAC7DlB,QAAQa,GAAG,CAACT;IACd;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/listen-confirmation.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 LISTENERS THE SERVER HAS NOT CONFIRMED YET, FOR A SAVE THAT NEEDS ONE\n * (AGL-4120).\n *\n * `writeGuardedBySeed` was handed one boolean, read when the button was\n * clicked, and refused the moment it was true. So a save made a second before\n * the server answered was thrown back at the person who made it, with an\n * instruction to reload — though nothing was wrong and waiting would have\n * done. Under load that window ran to a minute (measured in production, beta.297).\n *\n * A guard cannot watch a value it was passed by copy, and fifty-eight call\n * sites pass one. So the four hooks that produce `fromCache` report here, and\n * the guard asks this module instead of its caller: every listener that was\n * unconfirmed at the click has now heard from the server.\n *\n * ## Which listeners\n *\n * The seed's own, when the save names it (AGL-4135). Each hook that produces\n * `fromCache` also returns a {@link ListenHandle}, which always points at that\n * hook's current listener, and a call site that passes it to the guard waits\n * on that read alone ({@link whenListenConfirmed}).\n *\n * Otherwise all of them, because the guard cannot name its own. That errs one\n * way only: a listener nobody is saving can make a save wait, or refuse it, by\n * being slow, refused or torn down during the wait. It can never let a save\n * through on an unconfirmed seed, because the seed's own listener is in the set\n * being waited on. Measured in production with another tab starving the shared\n * cache (AGL-4135), every listener on a page is slow at once, so waiting on all\n * of them is waiting on the slowest one.\n *\n * Waiting on one listener keeps the same promise. A refusal or a teardown\n * never counts as a confirmation: the wait goes on, for the retry that reports\n * again or for the listener that replaces it, and ends unconfirmed at the\n * deadline if neither comes.\n *\n * ## A confirmation can change what is on screen\n *\n * The seed being protected may be out of date, which is the whole point of the\n * guard. When a listener's confirmation brought values that differ from the\n * ones it had shown, the form the person edited was built from the old ones,\n * so writing it now would overwrite the new ones: the exact loss the guard\n * exists to stop. That settles as `refreshed` and the save is refused for one\n * click, so they see the new values first.\n */\n\n/**\n * How long a save waits for a confirmation before saying so. Past the 8 s stall\n * window, so a client that really is silent has been recovered by the time the\n * wait ends, and short enough to read as a slow save rather than a dead button.\n */\nexport const SEED_CONFIRM_WAIT_MS = 12_000\n\nlet confirmWaitMs = SEED_CONFIRM_WAIT_MS\n\n/**\n * How long a save waits. For a spec that pins what happens when the confirmation\n * never comes, which is the refusal and not the wait: pass `0`, and restore the\n * default (no argument) when done, the way `setStaleSessionCheck` is unregistered.\n */\nexport function setSeedConfirmWaitMs(ms: number = SEED_CONFIRM_WAIT_MS): void {\n confirmWaitMs = ms\n}\n\n/** The part of a document snapshot {@link sameDocument} reads. */\ninterface DocumentValues {\n exists: () => boolean\n data: () => unknown\n}\n\n/**\n * Whether two snapshots of one document hold the same values. Read only on the\n * step from a cached snapshot to a confirmed one, never on every update, because\n * the SDK hands a doc listener no list of what changed.\n */\nexport function sameDocument(a: DocumentValues, b: DocumentValues): boolean {\n if (a.exists() !== b.exists()) return false\n return JSON.stringify(a.data()) === JSON.stringify(b.data())\n}\n\n/** How the wait ended. */\nexport type ListenSettlement =\n /** Every listener that was unconfirmed at the start has heard from the server. */\n | 'confirmed'\n /** They did, and at least one brought different values from the ones it showed. */\n | 'refreshed'\n /** The wait ran out, or a listener was refused or went away before answering. */\n | 'unconfirmed'\n /**\n * No listener here was unconfirmed, so whatever said the seed is unconfirmed\n * is not one this module can vouch for. The caller's answer stands.\n */\n | 'untracked'\n\n/** One listener's line in the record. */\ninterface Token {\n /** Where its last word left it. A refusal or a teardown is never `confirmed`. */\n state: 'unconfirmed' | 'confirmed' | 'released'\n /** Its latest confirmation brought values that differ from the ones it showed. */\n changed: boolean\n}\n\ninterface Waiter {\n pending: Set<Token>\n refreshed: boolean\n lost: boolean\n finish: (settlement: ListenSettlement) => void\n}\n\n/** A save waiting on one listener (AGL-4135). */\ninterface SeedWaiter {\n handle: HandleState\n finish: (settlement: ListenSettlement) => void\n}\n\ndeclare const listenHandleBrand: unique symbol\n\n/**\n * One hook's listener, for a save that waits on it alone (AGL-4135). Stable\n * for the life of the hook, and always points at the hook's CURRENT listener,\n * so a listener replaced during the wait (new deps, a reopen) is the one\n * waited on. Opaque: a call site only hands it to `writeGuardedBySeed`.\n */\nexport interface ListenHandle {\n readonly [listenHandleBrand]: true\n}\n\ninterface HandleState {\n token: Token | null\n}\n\n/** A handle for one hook instance. Create it once (`useState(createListenHandle)`). */\nexport function createListenHandle(): ListenHandle {\n const state: HandleState = { token: null }\n return state as unknown as ListenHandle\n}\n\nconst unconfirmed = new Set<Token>()\nconst waiters = new Set<Waiter>()\nconst seedWaiters = new Set<SeedWaiter>()\n\nfunction settleWaiters(token: Token, how: { changed?: boolean; lost?: boolean }) {\n for (const waiter of [...waiters]) {\n if (!waiter.pending.delete(token)) continue\n if (how.changed) waiter.refreshed = true\n if (how.lost) waiter.lost = true\n if (waiter.pending.size > 0) continue\n if (waiter.lost) waiter.finish('unconfirmed')\n else waiter.finish(waiter.refreshed ? 'refreshed' : 'confirmed')\n }\n}\n\nfunction settleSeedWaiters(token: Token) {\n for (const waiter of [...seedWaiters]) {\n if (waiter.handle.token !== token) continue\n waiter.finish(token.changed ? 'refreshed' : 'confirmed')\n }\n}\n\nexport interface ListenConfirmation {\n /**\n * A snapshot arrived. `changed` says a confirmation brought different values\n * from the ones this listener had shown; a first answer showed nothing, so\n * it cannot have changed anything.\n */\n report: (fromCache: boolean, changed?: boolean) => void\n /**\n * The listener was refused. A wait on every listener ends unconfirmed; a wait\n * on this one goes on, for the retry.\n */\n release: () => void\n /**\n * The listener was torn down. As `release`, and its handle no longer points\n * at it, so a wait on this one goes on for the listener that replaces it.\n */\n close: () => void\n}\n\n/**\n * One listener's line in the record. Unconfirmed from the start, for the same\n * reason every hook's `fromCache` state starts true. With `handle`, the handle\n * points at this listener from now on.\n */\nexport function trackListenConfirmation(\n handle?: ListenHandle,\n): ListenConfirmation {\n const token: Token = { state: 'unconfirmed', changed: false }\n unconfirmed.add(token)\n const bound = handle as unknown as HandleState | undefined\n if (bound) bound.token = token\n const release = () => {\n token.state = 'released'\n token.changed = false\n unconfirmed.delete(token)\n settleWaiters(token, { lost: true })\n }\n return {\n report: (fromCache, changed = false) => {\n if (fromCache) {\n token.state = 'unconfirmed'\n token.changed = false\n unconfirmed.add(token)\n return\n }\n token.state = 'confirmed'\n token.changed = changed\n unconfirmed.delete(token)\n settleWaiters(token, { changed })\n settleSeedWaiters(token)\n },\n release,\n close: () => {\n release()\n if (bound?.token === token) bound.token = null\n },\n }\n}\n\n/**\n * Resolves when every listener unconfirmed right now has settled, or after\n * `timeoutMs`. Never rejects.\n */\nexport function whenListensConfirmed(\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n if (unconfirmed.size === 0) return Promise.resolve('untracked')\n return new Promise((resolve) => {\n const waiter: Waiter = {\n pending: new Set(unconfirmed),\n refreshed: false,\n lost: false,\n finish: (settlement) => {\n clearTimeout(timer)\n waiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n waiters.add(waiter)\n })\n}\n\n/**\n * Resolves when the listener `handle` points at is confirmed, or after\n * `timeoutMs` (AGL-4135). Never rejects.\n *\n * - **Already confirmed**: at once, `refreshed` if that confirmation changed\n * the values on screen. The caller read `fromCache` before it landed.\n * - **Unconfirmed, refused or torn down**: waits. A refused listener retries\n * and reports again; a torn-down one is replaced, and the handle points at\n * the replacement. Neither is ever taken for a confirmation.\n * - **No listener behind the handle** (its hook has not listened, or has\n * stopped): `untracked`, so the caller's answer stands.\n */\nexport function whenListenConfirmed(\n handle: ListenHandle,\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n const state = handle as unknown as HandleState\n const token = state.token\n if (!token) return Promise.resolve('untracked')\n if (token.state === 'confirmed') {\n return Promise.resolve(token.changed ? 'refreshed' : 'confirmed')\n }\n return new Promise((resolve) => {\n const waiter: SeedWaiter = {\n handle: state,\n finish: (settlement) => {\n clearTimeout(timer)\n seedWaiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n seedWaiters.add(waiter)\n })\n}\n"],"names":["SEED_CONFIRM_WAIT_MS","confirmWaitMs","setSeedConfirmWaitMs","ms","sameDocument","a","b","exists","JSON","stringify","data","createListenHandle","state","token","unconfirmed","Set","waiters","seedWaiters","settleWaiters","how","waiter","pending","delete","changed","refreshed","lost","size","finish","settleSeedWaiters","handle","trackListenConfirmation","add","bound","release","report","fromCache","close","whenListensConfirmed","timeoutMs","Promise","resolve","settlement","clearTimeout","timer","setTimeout","whenListenConfirmed"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAED;;;;CAIC,GACD,OAAO,MAAMA,uBAAuB,MAAM;AAE1C,IAAIC,gBAAgBD;AAEpB;;;;CAIC,GACD,OAAO,SAASE,qBAAqBC,KAAaH,oBAAoB;IACpEC,gBAAgBE;AAClB;AAQA;;;;CAIC,GACD,OAAO,SAASC,aAAaC,CAAiB,EAAEC,CAAiB;IAC/D,IAAID,EAAEE,MAAM,OAAOD,EAAEC,MAAM,IAAI,OAAO;IACtC,OAAOC,KAAKC,SAAS,CAACJ,EAAEK,IAAI,QAAQF,KAAKC,SAAS,CAACH,EAAEI,IAAI;AAC3D;AAqDA,qFAAqF,GACrF,OAAO,SAASC;IACd,MAAMC,QAAqB;QAAEC,OAAO;IAAK;IACzC,OAAOD;AACT;AAEA,MAAME,cAAc,IAAIC;AACxB,MAAMC,UAAU,IAAID;AACpB,MAAME,cAAc,IAAIF;AAExB,SAASG,cAAcL,KAAY,EAAEM,GAA0C;IAC7E,KAAK,MAAMC,UAAU;WAAIJ;KAAQ,CAAE;QACjC,IAAI,CAACI,OAAOC,OAAO,CAACC,MAAM,CAACT,QAAQ;QACnC,IAAIM,IAAII,OAAO,EAAEH,OAAOI,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rC,aAAa;IAEjC,IAAIa,YAAYY,IAAI,KAAK,GAAG,OAAOa,QAAQC,OAAO,CAAC;IACnD,OAAO,IAAID,QAAQ,CAACC;QAClB,MAAMpB,SAAiB;YACrBC,SAAS,IAAIN,IAAID;YACjBU,WAAW;YACXC,MAAM;YACNE,QAAQ,CAACc;gBACPC,aAAaC;gBACb3B,QAAQM,MAAM,CAACF;gBACfoB,QAAQC;YACV;QACF;QACA,MAAME,QAAQC,WAAW,IAAMxB,OAAOO,MAAM,CAAC,gBAAgBW;QAC7DtB,QAAQe,GAAG,CAACX;IACd;AACF;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAASyB,oBACdhB,MAAoB,EACpBS,YAAoBrC,aAAa;IAEjC,MAAMW,QAAQiB;IACd,MAAMhB,QAAQD,MAAMC,KAAK;IACzB,IAAI,CAACA,OAAO,OAAO0B,QAAQC,OAAO,CAAC;IACnC,IAAI3B,MAAMD,KAAK,KAAK,aAAa;QAC/B,OAAO2B,QAAQC,OAAO,CAAC3B,MAAMU,OAAO,GAAG,cAAc;IACvD;IACA,OAAO,IAAIgB,QAAQ,CAACC;QAClB,MAAMpB,SAAqB;YACzBS,QAAQjB;YACRe,QAAQ,CAACc;gBACPC,aAAaC;gBACb1B,YAAYK,MAAM,CAACF;gBACnBoB,QAAQC;YACV;QACF;QACA,MAAME,QAAQC,WAAW,IAAMxB,OAAOO,MAAM,CAAC,gBAAgBW;QAC7DrB,YAAYc,GAAG,CAACX;IAClB;AACF"}
|
|
@@ -17,7 +17,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
17
17
|
*/ import { onSnapshot } from "firebase/firestore";
|
|
18
18
|
import { useEffect, useRef, useState } from "react";
|
|
19
19
|
import { DENIAL_STREAK_TO_REPORT, noteFirestoreServerRead, scheduleRefusedReopen, subscribeFirestoreSessionHeal } from "../firestore-denial-reporter.js";
|
|
20
|
-
import { sameDocument, trackListenConfirmation } from "./listen-confirmation.js";
|
|
20
|
+
import { createListenHandle, sameDocument, trackListenConfirmation } from "./listen-confirmation.js";
|
|
21
21
|
import { CONFIRMABLE_LISTEN_OPTIONS } from "./listen-options.js";
|
|
22
22
|
import useModifyDocCallback from "./use-modify-doc-callback.js";
|
|
23
23
|
const RETRY_DELAY_MS = 400;
|
|
@@ -46,6 +46,7 @@ const MAX_RETRIES = 5;
|
|
|
46
46
|
// Un-confirmed until a snapshot says otherwise (AGL-1066).
|
|
47
47
|
const [fromCache, setFromCache] = useState(true);
|
|
48
48
|
const [serverDenied, setServerDenied] = useState(false);
|
|
49
|
+
const [listen] = useState(createListenHandle);
|
|
49
50
|
const resolveFirstValueRef = useRef(undefined);
|
|
50
51
|
const firstValuePromiseRef = useRef(undefined);
|
|
51
52
|
if (!firstValuePromiseRef.current) {
|
|
@@ -79,7 +80,7 @@ const MAX_RETRIES = 5;
|
|
|
79
80
|
* that precedes every reopened refusal (AGL-1066). See the longer note
|
|
80
81
|
* on the same variable in `use-firestore-collection`.
|
|
81
82
|
*/ let terminal = false;
|
|
82
|
-
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation();
|
|
83
|
+
/** What a save waits on while this listener is unconfirmed (AGL-4120). */ const confirmation = trackListenConfirmation(listen);
|
|
83
84
|
/** The cached snapshot on screen, while one is (AGL-4120). */ let shownFromCache = null;
|
|
84
85
|
const subscribe = ()=>{
|
|
85
86
|
unsubscribe = onSnapshot(ref, // Without this the cache→server confirmation is never delivered and
|
|
@@ -186,7 +187,7 @@ const MAX_RETRIES = 5;
|
|
|
186
187
|
});
|
|
187
188
|
return ()=>{
|
|
188
189
|
cancelled = true;
|
|
189
|
-
confirmation.
|
|
190
|
+
confirmation.close();
|
|
190
191
|
unsubscribeHeal();
|
|
191
192
|
if (timer) clearTimeout(timer);
|
|
192
193
|
cancelRefusedReopen == null ? void 0 : cancelRefusedReopen();
|
|
@@ -206,7 +207,8 @@ const MAX_RETRIES = 5;
|
|
|
206
207
|
firstValuePromise: firstValuePromiseRef.current,
|
|
207
208
|
hasPendingWrites,
|
|
208
209
|
fromCache,
|
|
209
|
-
serverDenied
|
|
210
|
+
serverDenied,
|
|
211
|
+
listen
|
|
210
212
|
};
|
|
211
213
|
}
|
|
212
214
|
export function useDoc(ref, options) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/use-doc.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 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 onSnapshot,\n type DocumentData,\n type DocumentReference,\n type DocumentSnapshot,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState } from 'react'\nimport type { ObservableStatus, FirestoreDocOptions } from '../firebase/firebase-services'\nimport {\n DENIAL_STREAK_TO_REPORT,\n noteFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from '../firestore-denial-reporter'\nimport { sameDocument, trackListenConfirmation } from './listen-confirmation'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './listen-options'\nimport useModifyDocCallback, {\n type UseModifyDocCallback,\n} from './use-modify-doc-callback'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n// The refused cadence is shared policy — see `scheduleRefusedReopen` in\n// `firestore-denial-reporter.ts` (AGL-1066, AGL-1440, AGL-2944, AGL-2945).\n\n/**\n * Raw `onSnapshot` listener with its own retry/backoff instead of\n * reactfire's `useFirestoreDocData` — that hook caches the query's RxJS\n * Observable, and once it errors the Observable is *terminated forever*:\n * remounting the component never reopens the Firestore subscription, so a\n * single transient `permission-denied` (e.g. right after sign-in, before\n * Firestore's own credential provider has attached the user's ID token)\n * permanently breaks every caller of `useHost`/`useLayout`/`useScreen`/\n * `useScreenVersion`/`useLayoutVersion` for the rest of the session\n * (AGL-216/217/223). A fresh `onSnapshot` call each retry opens a genuinely\n * new listener, so it recovers once the token has propagated.\n */\nexport function useDocData<T>(\n ref: DocumentReference<T>,\n options?: FirestoreDocOptions<T>,\n): ObservableStatus<T> {\n const idField = options?.idField\n const initialData = options?.initialData\n const [status, setStatus] = useState<'loading' | 'error' | 'success'>(\n initialData !== undefined ? 'success' : 'loading',\n )\n const [data, setData] = useState<T>(initialData as T)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [hasEmitted, setHasEmitted] = useState(initialData !== undefined)\n const [hasPendingWrites, setHasPendingWrites] = useState(false)\n // Un-confirmed until a snapshot says otherwise (AGL-1066).\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const resolveFirstValueRef = useRef<(() => void) | undefined>(undefined)\n const firstValuePromiseRef = useRef<Promise<void> | undefined>(undefined)\n if (!firstValuePromiseRef.current) {\n firstValuePromiseRef.current = new Promise((resolve) => {\n resolveFirstValueRef.current = resolve\n })\n }\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n /**\n * Refusals since the last SERVER snapshot (AGL-1066).\n *\n * Still distinct from `attempt` after the flip: `attempt` is a BUDGET\n * that the heal broadcast may refund, whereas this is EVIDENCE about the\n * server that only a server snapshot may clear. Counted here to publish\n * `serverDenied` and to decide the slow cadence — the `session-health`\n * reporting the other two listener hooks do is a separate decision, and\n * this hook's callers (the besigner document family) are exactly the ones\n * a false verdict would hurt most.\n */\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n /**\n * The retry budget is spent and the server's last word was a refusal —\n * what keeps `status: 'error'` from being undone by the cached emission\n * that precedes every reopened refusal (AGL-1066). See the longer note\n * on the same variable in `use-firestore-collection`.\n */\n let terminal = false\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation()\n /** The cached snapshot on screen, while one is (AGL-4120). */\n let shownFromCache: DocumentSnapshot<DocumentData> | null = null\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n ref,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n // Only the SERVER answering refunds the retry budget, and only a\n // server snapshot ends a refusal (AGL-1066).\n if (!snapshot.metadata.fromCache) {\n attempt = 0\n terminal = false\n deniedStreak = 0\n setServerDenied(false)\n // Evidence only, deliberately not the reporting call: this hook\n // stays out of `session-health` (see `deniedStreak` above), but\n // its server answers are still proof the session can read, which\n // is what `refusedRetryDelayMs` splits the cadence on (AGL-1440).\n noteFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — not the AGL-1066 fault, so the budget is refunded\n // exactly as it always was. This is what keeps offline inert:\n // `unavailable` never enters `deniedStreak`.\n attempt = 0\n }\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n // Always true after ANY emission, cached included: this is what\n // tells a consumer \"I have data, the server refused\" apart from \"I\n // never had data\" — the distinction the besigner editors and the\n // host setup Theme tab blank on (AGL-1066).\n setHasEmitted(true)\n // Kept, not dropped: a snapshot that still carries this client's\n // own queued write is not evidence of what the store holds\n // (AGL-1262). Callers that record a \"last saved\" state need to\n // know the difference.\n setHasPendingWrites(snapshot.metadata.hasPendingWrites)\n setFromCache(snapshot.metadata.fromCache)\n confirmation.report(\n snapshot.metadata.fromCache,\n !snapshot.metadata.fromCache &&\n shownFromCache !== null &&\n !sameDocument(shownFromCache, snapshot),\n )\n shownFromCache = snapshot.metadata.fromCache ? snapshot : null\n const value = snapshot.exists()\n ? ({\n ...(snapshot.data() as object),\n ...(idField ? { [idField]: snapshot.id } : {}),\n } as T)\n : (undefined as T)\n setData(value)\n resolveFirstValueRef.current?.()\n },\n (err) => {\n if (cancelled) return\n confirmation.release()\n unsubscribe?.()\n // Only a refusal — a lost network produces no error callback at\n // all, and anything that does surface one carries `unavailable`,\n // which must never read as a dead session.\n if ((err as { code?: string })?.code === 'permission-denied') {\n deniedStreak += 1\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) setServerDenied(true)\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n resolveFirstValueRef.current?.()\n // A refusal streak keeps a slow road back for a recovery nobody\n // announced — see the same branch in `use-firestore-collection`.\n // The cadence splits on session-vs-ref evidence (AGL-1440), grows\n // with the streak's age (AGL-2945) and waits while the tab is\n // hidden (AGL-2944).\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n /**\n * Reopen when the session heals — see the long note on the same\n * subscription in `use-firestore-collection` (AGL-1066).\n *\n * This hook is where it counts most: its deps are `[ref.firestore,\n * ref.path]`, neither of which moves when a `stale` re-auth signs the\n * same uid back in, and it is what every besigner editor reads through.\n * Nothing else was ever going to bring those pages back without a reload.\n */\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n subscribe()\n })\n\n return () => {\n cancelled = true\n confirmation.release()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ref.firestore, ref.path])\n\n return {\n status,\n hasEmitted,\n isComplete: false,\n data,\n error,\n firstValuePromise: firstValuePromiseRef.current,\n hasPendingWrites,\n fromCache,\n serverDenied,\n }\n}\nexport type UseDocData<T> = typeof useDocData<T>\n\nexport function useDoc<T>(\n ref: DocumentReference<T>,\n options?: FirestoreDocOptions<T>,\n): {doc: ReturnType<UseDocData<T>>, setDoc: ReturnType<UseModifyDocCallback<T>>} {\n return {doc: useDocData(ref, options), setDoc: useModifyDocCallback(ref)}\n}\n\n\nexport default useDoc\n"],"names":["onSnapshot","useEffect","useRef","useState","DENIAL_STREAK_TO_REPORT","noteFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","sameDocument","trackListenConfirmation","CONFIRMABLE_LISTEN_OPTIONS","useModifyDocCallback","RETRY_DELAY_MS","MAX_RETRIES","useDocData","ref","options","idField","initialData","status","setStatus","undefined","data","setData","error","setError","hasEmitted","setHasEmitted","hasPendingWrites","setHasPendingWrites","fromCache","setFromCache","serverDenied","setServerDenied","resolveFirstValueRef","firstValuePromiseRef","current","Promise","resolve","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","terminal","confirmation","shownFromCache","subscribe","snapshot","metadata","report","value","exists","id","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout","firestore","path","isComplete","firstValuePromise","useDoc","doc","setDoc"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,QAIL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAEnD,SACEC,uBAAuB,EACvBC,uBAAuB,EACvBC,qBAAqB,EACrBC,6BAA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2C,mBAAmBhC,qBAAqBC,OAAO;QAC/CR;QACAE;QACAE;IACF;AACF;AAGA,OAAO,SAASoC,OACdrD,GAAyB,EACzBC,OAAgC;IAEhC,OAAO;QAACqD,KAAKvD,WAAWC,KAAKC;QAAUsD,QAAQ3D,qBAAqBI;IAAI;AAC1E;AAGA,eAAeqD,OAAM"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/use-doc.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2022 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 onSnapshot,\n type DocumentData,\n type DocumentReference,\n type DocumentSnapshot,\n} from 'firebase/firestore'\nimport { useEffect, useRef, useState } from 'react'\nimport type { ObservableStatus, FirestoreDocOptions } from '../firebase/firebase-services'\nimport {\n DENIAL_STREAK_TO_REPORT,\n noteFirestoreServerRead,\n scheduleRefusedReopen,\n subscribeFirestoreSessionHeal,\n} from '../firestore-denial-reporter'\nimport {\n createListenHandle,\n sameDocument,\n trackListenConfirmation,\n} from './listen-confirmation'\nimport { CONFIRMABLE_LISTEN_OPTIONS } from './listen-options'\nimport useModifyDocCallback, {\n type UseModifyDocCallback,\n} from './use-modify-doc-callback'\n\nconst RETRY_DELAY_MS = 400\nconst MAX_RETRIES = 5\n// The refused cadence is shared policy — see `scheduleRefusedReopen` in\n// `firestore-denial-reporter.ts` (AGL-1066, AGL-1440, AGL-2944, AGL-2945).\n\n/**\n * Raw `onSnapshot` listener with its own retry/backoff instead of\n * reactfire's `useFirestoreDocData` — that hook caches the query's RxJS\n * Observable, and once it errors the Observable is *terminated forever*:\n * remounting the component never reopens the Firestore subscription, so a\n * single transient `permission-denied` (e.g. right after sign-in, before\n * Firestore's own credential provider has attached the user's ID token)\n * permanently breaks every caller of `useHost`/`useLayout`/`useScreen`/\n * `useScreenVersion`/`useLayoutVersion` for the rest of the session\n * (AGL-216/217/223). A fresh `onSnapshot` call each retry opens a genuinely\n * new listener, so it recovers once the token has propagated.\n */\nexport function useDocData<T>(\n ref: DocumentReference<T>,\n options?: FirestoreDocOptions<T>,\n): ObservableStatus<T> {\n const idField = options?.idField\n const initialData = options?.initialData\n const [status, setStatus] = useState<'loading' | 'error' | 'success'>(\n initialData !== undefined ? 'success' : 'loading',\n )\n const [data, setData] = useState<T>(initialData as T)\n const [error, setError] = useState<Error | undefined>(undefined)\n const [hasEmitted, setHasEmitted] = useState(initialData !== undefined)\n const [hasPendingWrites, setHasPendingWrites] = useState(false)\n // Un-confirmed until a snapshot says otherwise (AGL-1066).\n const [fromCache, setFromCache] = useState(true)\n const [serverDenied, setServerDenied] = useState(false)\n const [listen] = useState(createListenHandle)\n const resolveFirstValueRef = useRef<(() => void) | undefined>(undefined)\n const firstValuePromiseRef = useRef<Promise<void> | undefined>(undefined)\n if (!firstValuePromiseRef.current) {\n firstValuePromiseRef.current = new Promise((resolve) => {\n resolveFirstValueRef.current = resolve\n })\n }\n\n useEffect(() => {\n setStatus('loading')\n setError(undefined)\n\n let cancelled = false\n let unsubscribe: (() => void) | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n /** Cancels a pending reopen on the refused cadence (AGL-2944). */\n let cancelRefusedReopen: (() => void) | null = null\n let attempt = 0\n /**\n * Refusals since the last SERVER snapshot (AGL-1066).\n *\n * Still distinct from `attempt` after the flip: `attempt` is a BUDGET\n * that the heal broadcast may refund, whereas this is EVIDENCE about the\n * server that only a server snapshot may clear. Counted here to publish\n * `serverDenied` and to decide the slow cadence — the `session-health`\n * reporting the other two listener hooks do is a separate decision, and\n * this hook's callers (the besigner document family) are exactly the ones\n * a false verdict would hurt most.\n */\n let deniedStreak = 0\n /** Epoch ms of the current streak's first refusal (AGL-1440). */\n let deniedStreakStartedAt = 0\n /**\n * The retry budget is spent and the server's last word was a refusal —\n * what keeps `status: 'error'` from being undone by the cached emission\n * that precedes every reopened refusal (AGL-1066). See the longer note\n * on the same variable in `use-firestore-collection`.\n */\n let terminal = false\n /** What a save waits on while this listener is unconfirmed (AGL-4120). */\n const confirmation = trackListenConfirmation(listen)\n /** The cached snapshot on screen, while one is (AGL-4120). */\n let shownFromCache: DocumentSnapshot<DocumentData> | null = null\n\n const subscribe = () => {\n unsubscribe = onSnapshot(\n ref,\n // Without this the cache→server confirmation is never delivered and\n // `fromCache` latches true for the life of the listener, refusing\n // every guarded save on the page (AGL-2486). See `listen-options.ts`.\n CONFIRMABLE_LISTEN_OPTIONS,\n (snapshot) => {\n if (cancelled) return\n // Only the SERVER answering refunds the retry budget, and only a\n // server snapshot ends a refusal (AGL-1066).\n if (!snapshot.metadata.fromCache) {\n attempt = 0\n terminal = false\n deniedStreak = 0\n setServerDenied(false)\n // Evidence only, deliberately not the reporting call: this hook\n // stays out of `session-health` (see `deniedStreak` above), but\n // its server answers are still proof the session can read, which\n // is what `refusedRetryDelayMs` splits the cadence on (AGL-1440).\n noteFirestoreServerRead()\n } else if (deniedStreak === 0) {\n // Cached, but nothing has been refused since the server last\n // answered — not the AGL-1066 fault, so the budget is refunded\n // exactly as it always was. This is what keeps offline inert:\n // `unavailable` never enters `deniedStreak`.\n attempt = 0\n }\n if (!terminal) {\n setStatus('success')\n setError(undefined)\n }\n // Always true after ANY emission, cached included: this is what\n // tells a consumer \"I have data, the server refused\" apart from \"I\n // never had data\" — the distinction the besigner editors and the\n // host setup Theme tab blank on (AGL-1066).\n setHasEmitted(true)\n // Kept, not dropped: a snapshot that still carries this client's\n // own queued write is not evidence of what the store holds\n // (AGL-1262). Callers that record a \"last saved\" state need to\n // know the difference.\n setHasPendingWrites(snapshot.metadata.hasPendingWrites)\n setFromCache(snapshot.metadata.fromCache)\n confirmation.report(\n snapshot.metadata.fromCache,\n !snapshot.metadata.fromCache &&\n shownFromCache !== null &&\n !sameDocument(shownFromCache, snapshot),\n )\n shownFromCache = snapshot.metadata.fromCache ? snapshot : null\n const value = snapshot.exists()\n ? ({\n ...(snapshot.data() as object),\n ...(idField ? { [idField]: snapshot.id } : {}),\n } as T)\n : (undefined as T)\n setData(value)\n resolveFirstValueRef.current?.()\n },\n (err) => {\n if (cancelled) return\n confirmation.release()\n unsubscribe?.()\n // Only a refusal — a lost network produces no error callback at\n // all, and anything that does surface one carries `unavailable`,\n // which must never read as a dead session.\n if ((err as { code?: string })?.code === 'permission-denied') {\n deniedStreak += 1\n if (deniedStreak === 1) deniedStreakStartedAt = Date.now()\n if (deniedStreak >= DENIAL_STREAK_TO_REPORT) setServerDenied(true)\n }\n if (attempt < MAX_RETRIES) {\n attempt += 1\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n } else {\n timer = setTimeout(subscribe, RETRY_DELAY_MS)\n }\n } else {\n terminal = true\n setStatus('error')\n setError(err)\n resolveFirstValueRef.current?.()\n // A refusal streak keeps a slow road back for a recovery nobody\n // announced — see the same branch in `use-firestore-collection`.\n // The cadence splits on session-vs-ref evidence (AGL-1440), grows\n // with the streak's age (AGL-2945) and waits while the tab is\n // hidden (AGL-2944).\n if (deniedStreak > MAX_RETRIES) {\n cancelRefusedReopen = scheduleRefusedReopen(\n subscribe,\n deniedStreakStartedAt,\n )\n }\n }\n },\n )\n }\n subscribe()\n\n /**\n * Reopen when the session heals — see the long note on the same\n * subscription in `use-firestore-collection` (AGL-1066).\n *\n * This hook is where it counts most: its deps are `[ref.firestore,\n * ref.path]`, neither of which moves when a `stale` re-auth signs the\n * same uid back in, and it is what every besigner editor reads through.\n * Nothing else was ever going to bring those pages back without a reload.\n */\n const unsubscribeHeal = subscribeFirestoreSessionHeal(() => {\n if (cancelled || deniedStreak === 0) return\n if (timer) {\n clearTimeout(timer)\n timer = null\n }\n cancelRefusedReopen?.()\n cancelRefusedReopen = null\n unsubscribe?.()\n attempt = 0\n subscribe()\n })\n\n return () => {\n cancelled = true\n confirmation.close()\n unsubscribeHeal()\n if (timer) clearTimeout(timer)\n cancelRefusedReopen?.()\n unsubscribe?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ref.firestore, ref.path])\n\n return {\n status,\n hasEmitted,\n isComplete: false,\n data,\n error,\n firstValuePromise: firstValuePromiseRef.current,\n hasPendingWrites,\n fromCache,\n serverDenied,\n listen,\n }\n}\nexport type UseDocData<T> = typeof useDocData<T>\n\nexport function useDoc<T>(\n ref: DocumentReference<T>,\n options?: FirestoreDocOptions<T>,\n): {doc: ReturnType<UseDocData<T>>, setDoc: ReturnType<UseModifyDocCallback<T>>} {\n return {doc: useDocData(ref, options), setDoc: useModifyDocCallback(ref)}\n}\n\n\nexport default useDoc\n"],"names":["onSnapshot","useEffect","useRef","useState","DENIAL_STREAK_TO_REPORT","noteFirestoreServerRead","scheduleRefusedReopen","subscribeFirestoreSessionHeal","createListenHandle","sameDocument","trackListenConfirmation","CONFIRMABLE_LISTEN_OPTIONS","useModifyDocCallback","RETRY_DELAY_MS","MAX_RETRIES","useDocData","ref","options","idField","initialData","status","setStatus","undefined","data","setData","error","setError","hasEmitted","setHasEmitted","hasPendingWrites","setHasPendingWrites","fromCache","setFromCache","serverDenied","setServerDenied","listen","resolveFirstValueRef","firstValuePromiseRef","current","Promise","resolve","cancelled","unsubscribe","timer","cancelRefusedReopen","attempt","deniedStreak","deniedStreakStartedAt","terminal","confirmation","shownFromCache","subscribe","snapshot","metadata","report","value","exists","id","err","release","code","Date","now","setTimeout","unsubscribeHeal","clearTimeout","close","firestore","path","isComplete","firstValuePromise","useDoc","doc","setDoc"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,UAAU,QAIL,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,M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xBC,uCAAAA;YACAF,+BAAAA;QACF;IACA,uDAAuD;IACzD,GAAG;QAAC1B,IAAImD,SAAS;QAAEnD,IAAIoD,IAAI;KAAC;IAE5B,OAAO;QACLhD;QACAO;QACA0C,YAAY;QACZ9C;QACAE;QACA6C,mBAAmBjC,qBAAqBC,OAAO;QAC/CT;QACAE;QACAE;QACAE;IACF;AACF;AAGA,OAAO,SAASoC,OACdvD,GAAyB,EACzBC,OAAgC;IAEhC,OAAO;QAACuD,KAAKzD,WAAWC,KAAKC;QAAUwD,QAAQ7D,qBAAqBI;IAAI;AAC1E;AAGA,eAAeuD,OAAM"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type DocumentData, type FirestoreError, type Query } from 'firebase/firestore';
|
|
2
2
|
import { type DependencyList } from 'react';
|
|
3
|
+
import { type ListenHandle } from './helpers/listen-confirmation';
|
|
3
4
|
export type FirestoreCollectionStatus = 'loading' | 'success' | 'error';
|
|
4
5
|
export interface UseFirestoreCollectionOptions {
|
|
5
6
|
idField?: string;
|
|
@@ -43,6 +44,12 @@ export interface UseFirestoreCollectionResult<T> {
|
|
|
43
44
|
* `status`.
|
|
44
45
|
*/
|
|
45
46
|
serverDenied: boolean;
|
|
47
|
+
/**
|
|
48
|
+
* This hook's listener, for a guarded save seeded from `data` to wait on
|
|
49
|
+
* alone (`writeGuardedBySeed`'s `listen`, AGL-4135). Stable for the life of
|
|
50
|
+
* the hook.
|
|
51
|
+
*/
|
|
52
|
+
listen: ListenHandle;
|
|
46
53
|
}
|
|
47
54
|
/**
|
|
48
55
|
* Collection-query counterpart to reactfire's `useFirestoreCollectionData`,
|