@blogmcp/sdk 0.12.0 → 0.14.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/dist/community/links.d.ts +6 -0
- package/dist/community/links.js +9 -1
- package/dist/community/outcome.d.ts +1 -1
- package/dist/community/outcome.js +60 -23
- package/dist/community/private/browser.d.ts +18 -0
- package/dist/community/private/browser.js +17 -0
- package/dist/community/private/client.d.ts +259 -0
- package/dist/community/private/client.js +98 -0
- package/dist/community/private/dm.d.ts +547 -0
- package/dist/community/private/dm.js +852 -0
- package/dist/community/private/dpop.d.ts +59 -0
- package/dist/community/private/dpop.js +46 -0
- package/dist/community/private/encoding.d.ts +17 -0
- package/dist/community/private/encoding.js +50 -0
- package/dist/community/private/host-state.d.ts +20 -0
- package/dist/community/private/host-state.js +15 -0
- package/dist/community/private/index.d.ts +51 -0
- package/dist/community/private/index.js +71 -0
- package/dist/community/private/keystore.d.ts +73 -0
- package/dist/community/private/keystore.js +91 -0
- package/dist/community/private/marker.d.ts +17 -0
- package/dist/community/private/marker.js +11 -0
- package/dist/community/private/private-routes.d.ts +6 -0
- package/dist/community/private/private-routes.js +72 -0
- package/dist/community/private/promise.d.ts +65 -0
- package/dist/community/private/promise.js +39 -0
- package/dist/community/private/realtime.d.ts +127 -0
- package/dist/community/private/realtime.js +199 -0
- package/dist/community/private/session.d.ts +175 -0
- package/dist/community/private/session.js +441 -0
- package/dist/community/private/transport.d.ts +47 -0
- package/dist/community/private/transport.js +65 -0
- package/dist/community/server/grant-handoff.d.ts +53 -0
- package/dist/community/server/grant-handoff.js +96 -0
- package/dist/community/server/grant.d.ts +100 -0
- package/dist/community/server/grant.js +165 -0
- package/dist/community/server/index.d.ts +4 -0
- package/dist/community/server/index.js +20 -16
- package/dist/community/shapes.d.ts +27 -1
- package/dist/community/shapes.js +27 -17
- package/dist/core/client.d.ts +9 -0
- package/dist/core/client.js +54 -50
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +113 -103
- package/dist/core/queries.d.ts +1 -0
- package/dist/core/queries.js +76 -71
- package/dist/core/review/types.d.ts +7 -0
- package/dist/core/style-layers.d.ts +88 -0
- package/dist/core/style-layers.js +69 -0
- package/package.json +7 -3
- package/src/community/links.ts +8 -0
- package/src/community/outcome.ts +37 -0
- package/src/community/private/browser.ts +31 -0
- package/src/community/private/client.ts +304 -0
- package/src/community/private/dm.ts +1687 -0
- package/src/community/private/dpop.ts +110 -0
- package/src/community/private/encoding.ts +71 -0
- package/src/community/private/host-state.ts +37 -0
- package/src/community/private/index.ts +169 -0
- package/src/community/private/keystore.ts +179 -0
- package/src/community/private/marker.ts +28 -0
- package/src/community/private/private-routes.ts +80 -0
- package/src/community/private/promise.ts +125 -0
- package/src/community/private/realtime.ts +431 -0
- package/src/community/private/session.ts +848 -0
- package/src/community/private/transport.ts +125 -0
- package/src/community/server/grant-handoff.ts +179 -0
- package/src/community/server/grant.ts +292 -0
- package/src/community/server/index.ts +6 -0
- package/src/community/shapes.ts +46 -1
- package/src/core/client.ts +12 -0
- package/src/core/index.ts +14 -0
- package/src/core/queries.ts +8 -0
- package/src/core/review/types.ts +8 -0
- package/src/core/style-layers.ts +169 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// GENERATED — do not edit by hand. The copy of kb-api's
|
|
2
|
+
// apps/knowledge-base/api/src/routes/community-private-routes.json (the private, account and grant surfaces kb-api
|
|
3
|
+
// serves; the test-only probe left out), written by test/community/private/private-routes.spec.ts when run with
|
|
4
|
+
// UPDATE_PRIVATE_ROUTES=1, which also fails while this copy differs from kb-api's list.
|
|
5
|
+
|
|
6
|
+
/** One operation kb-api serves on the private, account or grant surface. */
|
|
7
|
+
export interface PrivateRoute {
|
|
8
|
+
readonly method: 'POST'
|
|
9
|
+
readonly path: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const PRIVATE_ROUTES: readonly PrivateRoute[] = Object.freeze([
|
|
13
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/activation/dispute' }),
|
|
14
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/activation/end' }),
|
|
15
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/address/change/confirm' }),
|
|
16
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/address/change/request' }),
|
|
17
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/address/set' }),
|
|
18
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/address/verify' }),
|
|
19
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/device/approval/get' }),
|
|
20
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/device/approve' }),
|
|
21
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/device/list' }),
|
|
22
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/device/sign-out' }),
|
|
23
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/device/sign-out-all' }),
|
|
24
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/export/confirm' }),
|
|
25
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/export/download' }),
|
|
26
|
+
Object.freeze({ method: 'POST', path: '/community/v1/account/reads/list' }),
|
|
27
|
+
Object.freeze({ method: 'POST', path: '/community/v1/grant/issue' }),
|
|
28
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/activation/accept' }),
|
|
29
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/activation/end' }),
|
|
30
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/activation/state' }),
|
|
31
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/activation/withdraw' }),
|
|
32
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/address/link' }),
|
|
33
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/appeals/submit' }),
|
|
34
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/approval/deny' }),
|
|
35
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/approval/pending' }),
|
|
36
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/approval/redeem' }),
|
|
37
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/approval/show' }),
|
|
38
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/approval/start' }),
|
|
39
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/audience/check' }),
|
|
40
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/blocks/add' }),
|
|
41
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/blocks/list' }),
|
|
42
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/blocks/remove' }),
|
|
43
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/cases/get' }),
|
|
44
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/cases/list' }),
|
|
45
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/devices/forget' }),
|
|
46
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/devices/list' }),
|
|
47
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/devices/reads' }),
|
|
48
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/devices/sign-out' }),
|
|
49
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/devices/sign-out-all' }),
|
|
50
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/dm/clear' }),
|
|
51
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/dm/delete' }),
|
|
52
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/dm/edit' }),
|
|
53
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/dm/hide' }),
|
|
54
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/dm/list' }),
|
|
55
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/dm/messages' }),
|
|
56
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/dm/open' }),
|
|
57
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/dm/read' }),
|
|
58
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/dm/send' }),
|
|
59
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/dm/typing' }),
|
|
60
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/export/download' }),
|
|
61
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/notifications/list' }),
|
|
62
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/notifications/mark-read' }),
|
|
63
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/notifications/unread-count' }),
|
|
64
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/push/subscribe' }),
|
|
65
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/push/unsubscribe' }),
|
|
66
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/realtime/token' }),
|
|
67
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/reports/preview' }),
|
|
68
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/reports/submit' }),
|
|
69
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/requests/accept' }),
|
|
70
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/requests/block-report' }),
|
|
71
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/requests/delete' }),
|
|
72
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/requests/list' }),
|
|
73
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/session' }),
|
|
74
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/session/end' }),
|
|
75
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/session/refresh' }),
|
|
76
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/settings/get' }),
|
|
77
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/settings/set' }),
|
|
78
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/state' }),
|
|
79
|
+
Object.freeze({ method: 'POST', path: '/community/v1/private/statements/get' }),
|
|
80
|
+
] as const)
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The promise of the private surfaces as data (docs/internal/m4-contracts.md §6.1, invariant 12; community.md §9.4):
|
|
3
|
+
* the capability matrix — who receives what — by space × identity × `private_rendering`, and the wording keys the
|
|
4
|
+
* elements render from it, with the Czech sentences of §9.4. The elements (PU2) render the promise from this function
|
|
5
|
+
* only, and their "rendering the promise against the matrix" test checks that no sentence promises more than the row
|
|
6
|
+
* says; kb-api's analytics wording reads the same data (DM5).
|
|
7
|
+
*
|
|
8
|
+
* The rules the data encodes:
|
|
9
|
+
* - the participants receive the content; nobody else does in the normal course;
|
|
10
|
+
* - a reported message reaches whoever handles reports for blogmcp (T&S on the illegal line and appeals; an
|
|
11
|
+
* authorised person — possibly the website's moderator — on the rules line) with at most 10 preceding messages;
|
|
12
|
+
* - the tenant's team and server receive outcome codes and counts only;
|
|
13
|
+
* - under tenant rendering the website's page code receives the content to display it (U22: the promise says so);
|
|
14
|
+
* under `provider_page` it receives nothing — the screens are on blogmcp's account host — and that sentence goes;
|
|
15
|
+
* - a delegated sign-in (the delegated identity, or a native member whose session came through the tenant's host)
|
|
16
|
+
* adds the addendum under both renderings: the website can sign in as the member as a new device;
|
|
17
|
+
* - with the same legal person behind the website and blogmcp (U10, `same_entity`), under tenant rendering the
|
|
18
|
+
* sentence says plainly that this person writes the code that displays the messages.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/** A private space. M4 builds DMs; groups come later and their row is here so the matrix is settled once. */
|
|
22
|
+
export type PrivateSpace = 'dm' | 'group'
|
|
23
|
+
export type PrivateIdentity = 'native' | 'sso' | 'delegated'
|
|
24
|
+
export type PrivatePromiseRendering = 'tenant' | 'provider_page'
|
|
25
|
+
|
|
26
|
+
/** What one party receives. */
|
|
27
|
+
export type PrivateReceives =
|
|
28
|
+
| 'content'
|
|
29
|
+
/** Reported messages only, with at most 10 preceding messages. */
|
|
30
|
+
| 'reported_content'
|
|
31
|
+
/** Outcome codes and aggregate counts, never content or case metadata. */
|
|
32
|
+
| 'outcome_codes_and_counts'
|
|
33
|
+
/** The content, to put it on the member's screen (tenant rendering). */
|
|
34
|
+
| 'content_for_display'
|
|
35
|
+
/** A group's content, only while visibly a member with a badge. */
|
|
36
|
+
| 'content_when_visible_member'
|
|
37
|
+
| 'nothing'
|
|
38
|
+
|
|
39
|
+
export interface PrivatePromiseInput {
|
|
40
|
+
space: PrivateSpace
|
|
41
|
+
identity: PrivateIdentity
|
|
42
|
+
rendering: PrivatePromiseRendering
|
|
43
|
+
/** The website and blogmcp are run by the same legal person (the admission's `same_entity`). */
|
|
44
|
+
sameEntity?: boolean
|
|
45
|
+
/** The session came through the tenant's host (`host_tenant`): a native member there counts as delegated (§5.11). */
|
|
46
|
+
hostKind?: 'blogmcp' | 'tenant'
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface PrivatePromise {
|
|
50
|
+
readonly receivers: Readonly<{
|
|
51
|
+
participants: PrivateReceives
|
|
52
|
+
authorisedPersons: PrivateReceives
|
|
53
|
+
trustAndSafety: PrivateReceives
|
|
54
|
+
tenantTeam: PrivateReceives
|
|
55
|
+
tenantServer: PrivateReceives
|
|
56
|
+
websiteCode: PrivateReceives
|
|
57
|
+
}>
|
|
58
|
+
/** The wording keys, in the order the sentences are shown. */
|
|
59
|
+
readonly keys: readonly PrivatePromiseKey[]
|
|
60
|
+
/** Whether the delegated addendum applies. */
|
|
61
|
+
readonly delegated: boolean
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const PRIVATE_PROMISE_KEYS = Object.freeze([
|
|
65
|
+
'private.promise.dm.core',
|
|
66
|
+
'private.promise.group.core',
|
|
67
|
+
'private.promise.display.tenant',
|
|
68
|
+
'private.promise.same_entity',
|
|
69
|
+
'private.promise.reports',
|
|
70
|
+
'private.promise.orders',
|
|
71
|
+
'private.promise.not_e2e',
|
|
72
|
+
'private.promise.delegated',
|
|
73
|
+
] as const)
|
|
74
|
+
export type PrivatePromiseKey = (typeof PRIVATE_PROMISE_KEYS)[number]
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The sentences of community.md §9.4, split where a rendering or an identity drops or adds one. Placeholders:
|
|
78
|
+
* `{site}` the website's name, `{entity}` and `{ico}` the operator's name and IČO.
|
|
79
|
+
*/
|
|
80
|
+
export const PRIVATE_PROMISE_MESSAGES_CS: Readonly<Record<PrivatePromiseKey, string>> = Object.freeze({
|
|
81
|
+
'private.promise.dm.core': 'Soukromé zprávy jsou jen pro vás a druhého účastníka. Provozuje je blogmcp.',
|
|
82
|
+
'private.promise.group.core': 'Skupiny jsou jen pro členy; člen týmu je vidí jen tehdy, když je ve skupině viditelně s odznakem.',
|
|
83
|
+
'private.promise.display.tenant': 'Na obrazovku je dává web {site} a smlouva mu zakazuje je číst, ukládat nebo měřit.',
|
|
84
|
+
'private.promise.same_entity':
|
|
85
|
+
'Soukromé zprávy provozuje blogmcp. Web i blogmcp dnes provozuje stejná osoba ({entity}, IČO {ico}) a píše i kód webu, který vám zprávy zobrazuje. ' +
|
|
86
|
+
'Technicky by je tak mohla číst, zakazuje jí to zákon. Jinak se obsah mimo vaši obrazovku otevře jen u nahlášené zprávy nebo na příkaz úřadu ' +
|
|
87
|
+
'a každé takové otevření se samo zapíše.',
|
|
88
|
+
'private.promise.reports':
|
|
89
|
+
'Tým webu k nim nemá žádný nástroj, kromě vyřizování nahlášených zpráv. Když kdokoli z vás zprávu nahlásí, uvidí ji i s nejvýš 10 předchozími ' +
|
|
90
|
+
'zprávami ten, kdo hlášení vyřizuje za provozovatele soukromých zpráv. Může to být i pověřený moderátor webu {site}. Kdo hlásí, vidí jeho jméno ' +
|
|
91
|
+
'před odesláním.',
|
|
92
|
+
'private.promise.orders': 'Výjimkou jsou i údaje, které musí provozovatel vydat na příkaz soudu nebo policie.',
|
|
93
|
+
'private.promise.not_e2e': 'Nejsou šifrované koncově.',
|
|
94
|
+
'private.promise.delegated':
|
|
95
|
+
'Web, přes který se přihlašujete, se za vás technicky umí přihlásit jako nové zařízení. Starší zprávy by tam bez vašeho schválení neviděl, ' +
|
|
96
|
+
'nové ano, a mohl by i psát vaším jménem. Každé nové přihlášení vám proto ohlásíme e-mailem od blogmcp.',
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
/** The promise for one space, identity and rendering (see the module doc). */
|
|
100
|
+
export function privatePromise(input: PrivatePromiseInput): PrivatePromise {
|
|
101
|
+
const tenantRendering = input.rendering !== 'provider_page'
|
|
102
|
+
const delegated = input.identity === 'delegated' || (input.identity === 'native' && input.hostKind === 'tenant')
|
|
103
|
+
const sameEntity = input.sameEntity === true && tenantRendering
|
|
104
|
+
const keys: PrivatePromiseKey[] = []
|
|
105
|
+
if (input.space === 'group') keys.push('private.promise.group.core')
|
|
106
|
+
if (sameEntity) keys.push('private.promise.same_entity')
|
|
107
|
+
else {
|
|
108
|
+
if (input.space === 'dm') keys.push('private.promise.dm.core')
|
|
109
|
+
if (tenantRendering) keys.push('private.promise.display.tenant')
|
|
110
|
+
}
|
|
111
|
+
keys.push('private.promise.reports', 'private.promise.orders', 'private.promise.not_e2e')
|
|
112
|
+
if (delegated) keys.push('private.promise.delegated')
|
|
113
|
+
return Object.freeze({
|
|
114
|
+
receivers: Object.freeze({
|
|
115
|
+
participants: 'content',
|
|
116
|
+
authorisedPersons: 'reported_content',
|
|
117
|
+
trustAndSafety: 'reported_content',
|
|
118
|
+
tenantTeam: input.space === 'group' ? 'content_when_visible_member' : 'outcome_codes_and_counts',
|
|
119
|
+
tenantServer: 'outcome_codes_and_counts',
|
|
120
|
+
websiteCode: tenantRendering ? 'content_for_display' : 'nothing',
|
|
121
|
+
}),
|
|
122
|
+
keys: Object.freeze(keys),
|
|
123
|
+
delegated,
|
|
124
|
+
})
|
|
125
|
+
}
|
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The private realtime client (docs/internal/m4-contracts.md §6.3 "Realtime", C.8, C.9): the member's inbox on this
|
|
3
|
+
* device, as content-free events `{ k, c?, s?, r? }` — the elements' `realtime` property (`{ subscribe(listener) }`).
|
|
4
|
+
*
|
|
5
|
+
* const realtime = createPrivateRealtime({ client }) // client: createPrivateClient(…)
|
|
6
|
+
* const off = realtime.subscribe((event) => …) // event.k: 'device_new', 'resync', …
|
|
7
|
+
* // later: off(), or realtime.close()
|
|
8
|
+
*
|
|
9
|
+
* **Its own connection.** `private/realtime/token` answers a connection token whose `channels` claim names the
|
|
10
|
+
* member's inbox, `user:inbox#<memberId>` — a server-side subscription: Centrifugo subscribes the connection to it, and
|
|
11
|
+
* the client never asks for the channel (the chart's `user` namespace refuses a client's subscribe). So this client
|
|
12
|
+
* opens a Centrifuge connection of its own, beside the public client's (both `sub = memberId`, so a revocation's user
|
|
13
|
+
* disconnect closes both), reads the inbox's name from the token it was given and hands on only that channel's
|
|
14
|
+
* publications. The URL comes only from kb-api's answer; nothing here builds one from configuration.
|
|
15
|
+
*
|
|
16
|
+
* **Renewal.** The token lives 120 s (`expiresInS`) and is DPoP-bound through the private session that asks for it:
|
|
17
|
+
* `realtime.token()` runs with this device's session, its refresh and its proof retries. A fresh token is fetched
|
|
18
|
+
* `PRIVATE_RT_RENEW_MARGIN_MS` before the current one expires, so when Centrifuge asks for one (`getToken`, at the
|
|
19
|
+
* token's ttl) it is already there, and the socket never waits on a private round trip with an expired token; the
|
|
20
|
+
* renewal after that is scheduled from the token Centrifuge took, so a connection refreshes once per token (every
|
|
21
|
+
* 120 s less the margin). A
|
|
22
|
+
* device that is signed out, denied or whose mint key was retired gets its renewal refused (UNAUTHORIZED,
|
|
23
|
+
* DEVICE_REMOVED, …): the client then closes at once instead of waiting for Centrifugo to close it at the token's
|
|
24
|
+
* expiry plus its grace (≤ 145 s, which stays the server's guarantee). A transient failure (the network, a 5xx, a
|
|
25
|
+
* quota) leaves the socket to Centrifugo's own retries.
|
|
26
|
+
*
|
|
27
|
+
* **Closing.** `close()` (an unmounted view, a sign-out), the last listener leaving, a refused renewal, a server
|
|
28
|
+
* disconnect that is final (the revocation of every session, 4501; any code in Centrifugo's terminal ranges) and a
|
|
29
|
+
* token that does not name exactly one inbox end the connection for good; `onEnd` says why, once. A closed client
|
|
30
|
+
* stays closed: the host makes a new one for a new session.
|
|
31
|
+
*
|
|
32
|
+
* `centrifuge` (≥ 5.7, MIT) is the package's optional peer dependency, loaded only when a listener subscribes; a host
|
|
33
|
+
* passes the module or a loader of it as `centrifuge` (a test passes a fake). Nothing here logs or reports.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
import { assertPrivateBrowser } from './browser'
|
|
37
|
+
import { fromBase64url } from './encoding'
|
|
38
|
+
import type { PrivateCode, PrivateOutcome } from './session'
|
|
39
|
+
|
|
40
|
+
assertPrivateBrowser()
|
|
41
|
+
|
|
42
|
+
// ───────────────────────── the part of centrifuge this client uses ─────────────────────────
|
|
43
|
+
|
|
44
|
+
/** A Centrifuge client, as far as this client uses it (server-side subscriptions report on the client). */
|
|
45
|
+
export interface PrivateCentrifugeLike {
|
|
46
|
+
on(event: 'connected' | 'connecting' | 'disconnected' | 'subscribed' | 'unsubscribed' | 'publication' | 'error', listener: (ctx: any) => void): unknown
|
|
47
|
+
connect(): void
|
|
48
|
+
disconnect(): void
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** `centrifuge`'s module, as far as this client uses it. */
|
|
52
|
+
export interface PrivateCentrifugeModuleLike {
|
|
53
|
+
Centrifuge: new (
|
|
54
|
+
endpoints: Array<{ transport: 'websocket' | 'http_stream'; endpoint: string }>,
|
|
55
|
+
options: { token: string; getToken: () => Promise<string>; emulationEndpoint: string; name?: string },
|
|
56
|
+
) => PrivateCentrifugeLike
|
|
57
|
+
/** Thrown from getToken, it tells Centrifuge to stop (no retry). */
|
|
58
|
+
UnauthorizedError?: new (message?: string) => Error
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ───────────────────────── shapes ─────────────────────────
|
|
62
|
+
|
|
63
|
+
/** `private/realtime/token`'s answer (C.8). */
|
|
64
|
+
export interface PrivateRealtimeTokenAnswer {
|
|
65
|
+
readonly token: string
|
|
66
|
+
readonly url: string
|
|
67
|
+
readonly expiresInS: number
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* One inbox event (§6.3, invariant 6): a code and, at most, a conversation id, a sequence number and the device an
|
|
72
|
+
* account event is about. Nothing else of a publication is handed on.
|
|
73
|
+
*/
|
|
74
|
+
export interface PrivateRealtimeEvent {
|
|
75
|
+
readonly k: string
|
|
76
|
+
readonly c?: string
|
|
77
|
+
readonly s?: number
|
|
78
|
+
readonly r?: string
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export type PrivateRealtimeListener = (event: PrivateRealtimeEvent) => void
|
|
82
|
+
|
|
83
|
+
/** `idle` until a listener subscribes; `connecting` (again after a drop); `live` once the inbox is subscribed; `closed`. */
|
|
84
|
+
export type PrivateRealtimeMode = 'idle' | 'connecting' | 'live' | 'closed'
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Why the connection ended: `closed` (by the host, or its last listener left), `refused` (kb-api refused a token:
|
|
88
|
+
* `code` says which), `revoked` (Centrifugo cut the user for good: a revocation of every session), `off` (kb-api has
|
|
89
|
+
* no realtime for this tenant, or the private surface answers nothing), `unavailable` (no usable answer, no
|
|
90
|
+
* `centrifuge` module, or the first token could not be had).
|
|
91
|
+
*/
|
|
92
|
+
export type PrivateRealtimeEndReason = 'closed' | 'refused' | 'revoked' | 'off' | 'unavailable'
|
|
93
|
+
|
|
94
|
+
export interface PrivateRealtimeEnd {
|
|
95
|
+
readonly reason: PrivateRealtimeEndReason
|
|
96
|
+
/** kb-api's or the SDK's code for `refused`, `off` and `unavailable`; Centrifugo's disconnect code for `revoked`. */
|
|
97
|
+
readonly code: string | null
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface PrivateRealtimeOptions {
|
|
101
|
+
/** The private client (createPrivateClient), as far as this one uses it: its device's session asks for the tokens. */
|
|
102
|
+
client: { realtime: { token(): Promise<PrivateOutcome<PrivateRealtimeTokenAnswer>> } }
|
|
103
|
+
/** The `centrifuge` module, or a loader of it; default `import('centrifuge')` (the optional peer dependency). */
|
|
104
|
+
centrifuge?: PrivateCentrifugeModuleLike | (() => Promise<PrivateCentrifugeModuleLike>)
|
|
105
|
+
/** Called on every change of mode. */
|
|
106
|
+
onMode?: (mode: PrivateRealtimeMode) => void
|
|
107
|
+
/** Called once, when the connection ends for good. */
|
|
108
|
+
onEnd?: (end: PrivateRealtimeEnd) => void
|
|
109
|
+
/** How long before a token's expiry the next one is fetched (default PRIVATE_RT_RENEW_MARGIN_MS). */
|
|
110
|
+
renewMarginMs?: number
|
|
111
|
+
now?: () => number
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface PrivateRealtime {
|
|
115
|
+
readonly mode: PrivateRealtimeMode
|
|
116
|
+
/** The inbox channel the current token names, or null before the first token. */
|
|
117
|
+
readonly channel: string | null
|
|
118
|
+
/** Adds a listener (the first one connects); returns the function that removes it (the last one closes). */
|
|
119
|
+
subscribe(listener: PrivateRealtimeListener): () => void
|
|
120
|
+
/** Ends the connection for good (idempotent). */
|
|
121
|
+
close(): void
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The next token is fetched this long before the current one expires (a 120 s token: at 90 s). */
|
|
125
|
+
export const PRIVATE_RT_RENEW_MARGIN_MS = 30_000
|
|
126
|
+
/** The shortest wait before a renewal, whatever a token's lifetime. */
|
|
127
|
+
const RENEW_MIN_DELAY_MS = 5_000
|
|
128
|
+
/** How often the first token is asked again after a transient failure before the client gives up. */
|
|
129
|
+
const FIRST_TOKEN_ATTEMPTS = 3
|
|
130
|
+
const FIRST_TOKEN_BASE_MS = 1_000
|
|
131
|
+
/** kb-api's revocation of every session (`RT_DISCONNECT_CODE`): the user is disconnected for good. */
|
|
132
|
+
const REVOKED_CODE = 4501
|
|
133
|
+
|
|
134
|
+
/** A server's disconnect codes after which Centrifuge does not reconnect (3500–3999, 4500–4999). */
|
|
135
|
+
const isTerminalCode = (code: unknown): code is number => typeof code === 'number' && ((code >= 3500 && code < 4000) || (code >= 4500 && code < 5000))
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The codes after which asking again may succeed: no answer, a gateway, a busy or rate-limited kb-api. Every other
|
|
139
|
+
* refusal of `realtime/token` is final for this connection (the device signed out, denied or removed; no member; the
|
|
140
|
+
* surface or its realtime off; the identity refused).
|
|
141
|
+
*/
|
|
142
|
+
const TRANSIENT_CODES: ReadonlySet<PrivateCode> = new Set<PrivateCode>([
|
|
143
|
+
'NETWORK',
|
|
144
|
+
'BAD_ANSWER',
|
|
145
|
+
'UNAVAILABLE',
|
|
146
|
+
'INTERNAL',
|
|
147
|
+
'BUSY',
|
|
148
|
+
'TOO_FAST',
|
|
149
|
+
'QUOTA_DAILY',
|
|
150
|
+
'QUOTA_IP_HOURLY',
|
|
151
|
+
'LEDGER_UNAVAILABLE',
|
|
152
|
+
])
|
|
153
|
+
|
|
154
|
+
/** The refusals that mean "no realtime here" rather than "not for this device". */
|
|
155
|
+
const OFF_CODES: ReadonlySet<PrivateCode> = new Set<PrivateCode>(['REALTIME_OFF', 'UNKNOWN_PATH', 'MODULE_DARK'])
|
|
156
|
+
|
|
157
|
+
const INBOX_RE = /^user:inbox#[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
|
158
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
159
|
+
const CODE_RE = /^[a-z][a-z0-9_]{0,63}$/
|
|
160
|
+
|
|
161
|
+
const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* The one inbox channel a connection token names in its `channels` claim, or null. The token is kb-api's and Centrifugo
|
|
165
|
+
* verifies it; this only reads which channel the server will subscribe, so that nothing else is handed on.
|
|
166
|
+
*/
|
|
167
|
+
export function inboxChannelOfToken(token: unknown): string | null {
|
|
168
|
+
if (typeof token !== 'string' || token.length > 4096) return null
|
|
169
|
+
const parts = token.split('.')
|
|
170
|
+
if (parts.length !== 3) return null
|
|
171
|
+
const bytes = fromBase64url(parts[1]!)
|
|
172
|
+
if (!bytes) return null
|
|
173
|
+
let claims: unknown
|
|
174
|
+
try {
|
|
175
|
+
claims = JSON.parse(new TextDecoder().decode(bytes))
|
|
176
|
+
} catch {
|
|
177
|
+
return null
|
|
178
|
+
}
|
|
179
|
+
if (!isRecord(claims) || !Array.isArray(claims.channels) || claims.channels.length !== 1) return null
|
|
180
|
+
const channel = claims.channels[0]
|
|
181
|
+
return typeof channel === 'string' && INBOX_RE.test(channel) ? channel : null
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** kb-api's connection URL without a trailing slash: an absolute http(s) URL with no credentials, query or fragment. */
|
|
185
|
+
export function privateRealtimeUrlOf(url: unknown): string | null {
|
|
186
|
+
if (typeof url !== 'string' || url.length > 2048) return null
|
|
187
|
+
let parsed: URL
|
|
188
|
+
try {
|
|
189
|
+
parsed = new URL(url)
|
|
190
|
+
} catch {
|
|
191
|
+
return null
|
|
192
|
+
}
|
|
193
|
+
if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || parsed.username || parsed.password || parsed.search || parsed.hash) return null
|
|
194
|
+
return parsed.href.replace(/\/+$/, '')
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* A publication's data as an inbox event, or null: `k` a code, `c` and `r` ids, `s` a non-negative integer; any other
|
|
199
|
+
* key, or a value of another kind, is not passed on (the inbox carries no content, invariant 6).
|
|
200
|
+
*/
|
|
201
|
+
export function privateRealtimeEventOf(data: unknown): PrivateRealtimeEvent | null {
|
|
202
|
+
if (!isRecord(data) || typeof data.k !== 'string' || !CODE_RE.test(data.k)) return null
|
|
203
|
+
const event: { k: string; c?: string; s?: number; r?: string } = { k: data.k }
|
|
204
|
+
if (typeof data.c === 'string' && UUID_RE.test(data.c)) event.c = data.c.toLowerCase()
|
|
205
|
+
if (typeof data.s === 'number' && Number.isSafeInteger(data.s) && data.s >= 0) event.s = data.s
|
|
206
|
+
if (typeof data.r === 'string' && UUID_RE.test(data.r)) event.r = data.r.toLowerCase()
|
|
207
|
+
return Object.freeze(event)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async function loadCentrifuge(option: PrivateRealtimeOptions['centrifuge']): Promise<PrivateCentrifugeModuleLike | null> {
|
|
211
|
+
try {
|
|
212
|
+
const mod = typeof option === 'function' ? await option() : option ? option : ((await import('centrifuge')) as unknown as PrivateCentrifugeModuleLike)
|
|
213
|
+
return mod && typeof mod.Centrifuge === 'function' ? mod : null
|
|
214
|
+
} catch {
|
|
215
|
+
return null
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
interface HeldToken {
|
|
220
|
+
token: string
|
|
221
|
+
/** Local epoch ms at which it expires. */
|
|
222
|
+
exp: number
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function createPrivateRealtime(options: PrivateRealtimeOptions): PrivateRealtime {
|
|
226
|
+
const { client } = options
|
|
227
|
+
const now = options.now ?? Date.now
|
|
228
|
+
const margin = typeof options.renewMarginMs === 'number' && options.renewMarginMs >= 0 ? options.renewMarginMs : PRIVATE_RT_RENEW_MARGIN_MS
|
|
229
|
+
const listeners = new Set<PrivateRealtimeListener>()
|
|
230
|
+
let mode: PrivateRealtimeMode = 'idle'
|
|
231
|
+
let channel: string | null = null
|
|
232
|
+
let centrifuge: PrivateCentrifugeLike | null = null
|
|
233
|
+
/** The token fetched ahead of Centrifuge's `getToken`, when there is one. */
|
|
234
|
+
let next: HeldToken | null = null
|
|
235
|
+
let renewTimer: ReturnType<typeof setTimeout> | null = null
|
|
236
|
+
let renewing: Promise<void> | null = null
|
|
237
|
+
|
|
238
|
+
/** Read through a function: the mode changes across every await (TypeScript would narrow a direct read). */
|
|
239
|
+
const closed = (): boolean => mode === 'closed'
|
|
240
|
+
|
|
241
|
+
const setMode = (value: PrivateRealtimeMode): void => {
|
|
242
|
+
if (mode === value || closed()) return
|
|
243
|
+
mode = value
|
|
244
|
+
try {
|
|
245
|
+
options.onMode?.(value)
|
|
246
|
+
} catch {
|
|
247
|
+
// A host's handler must not break the connection.
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function end(reason: PrivateRealtimeEndReason, code: string | null): void {
|
|
252
|
+
if (closed()) return
|
|
253
|
+
if (renewTimer) clearTimeout(renewTimer)
|
|
254
|
+
renewTimer = null
|
|
255
|
+
next = null
|
|
256
|
+
const c = centrifuge
|
|
257
|
+
centrifuge = null
|
|
258
|
+
try {
|
|
259
|
+
c?.disconnect()
|
|
260
|
+
} catch {
|
|
261
|
+
// A socket that is going anyway.
|
|
262
|
+
}
|
|
263
|
+
mode = 'closed'
|
|
264
|
+
try {
|
|
265
|
+
options.onMode?.('closed')
|
|
266
|
+
} catch {
|
|
267
|
+
// As setMode.
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
options.onEnd?.({ reason, code })
|
|
271
|
+
} catch {
|
|
272
|
+
// As setMode.
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** The end a refused token answer means. */
|
|
277
|
+
function endFor(code: PrivateCode): void {
|
|
278
|
+
end(OFF_CODES.has(code) ? 'off' : 'refused', code)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const expiryOf = (answer: PrivateRealtimeTokenAnswer): number => {
|
|
282
|
+
const s = typeof answer.expiresInS === 'number' && Number.isFinite(answer.expiresInS) && answer.expiresInS > 0 ? answer.expiresInS : 120
|
|
283
|
+
return now() + s * 1000
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Schedule the fetch of the next token `margin` before `exp`. */
|
|
287
|
+
function scheduleRenewal(exp: number): void {
|
|
288
|
+
if (renewTimer) clearTimeout(renewTimer)
|
|
289
|
+
const delay = Math.max(RENEW_MIN_DELAY_MS, exp - now() - margin)
|
|
290
|
+
renewTimer = setTimeout(() => {
|
|
291
|
+
renewTimer = null
|
|
292
|
+
void renew()
|
|
293
|
+
}, delay)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Fetch the next token ahead of Centrifuge (see the module doc). A refusal that is final ends the connection now; a
|
|
298
|
+
* transient one leaves `getToken` to ask again when Centrifuge needs the token.
|
|
299
|
+
*/
|
|
300
|
+
function renew(): Promise<void> {
|
|
301
|
+
if (renewing) return renewing
|
|
302
|
+
renewing = (async () => {
|
|
303
|
+
try {
|
|
304
|
+
if (closed()) return
|
|
305
|
+
const r = await client.realtime.token()
|
|
306
|
+
if (closed()) return
|
|
307
|
+
if (!r.ok) {
|
|
308
|
+
if (!TRANSIENT_CODES.has(r.code)) endFor(r.code)
|
|
309
|
+
return
|
|
310
|
+
}
|
|
311
|
+
if (inboxChannelOfToken(r.value.token) !== channel) return end('unavailable', 'BAD_ANSWER')
|
|
312
|
+
// The next renewal is scheduled once Centrifuge takes this token (getToken), so a token that waits for a
|
|
313
|
+
// reconnect is not renewed again behind it: one token per refresh of the connection.
|
|
314
|
+
next = { token: r.value.token, exp: expiryOf(r.value) }
|
|
315
|
+
} finally {
|
|
316
|
+
renewing = null
|
|
317
|
+
}
|
|
318
|
+
})()
|
|
319
|
+
return renewing
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function start(): Promise<void> {
|
|
323
|
+
setMode('connecting')
|
|
324
|
+
let first: PrivateOutcome<PrivateRealtimeTokenAnswer> | null = null
|
|
325
|
+
for (let attempt = 0; attempt < FIRST_TOKEN_ATTEMPTS; attempt++) {
|
|
326
|
+
if (attempt > 0) await new Promise((settle) => setTimeout(settle, FIRST_TOKEN_BASE_MS * 2 ** (attempt - 1)))
|
|
327
|
+
if (closed()) return
|
|
328
|
+
first = await client.realtime.token()
|
|
329
|
+
if (closed()) return
|
|
330
|
+
if (first.ok || !TRANSIENT_CODES.has(first.code)) break
|
|
331
|
+
}
|
|
332
|
+
if (!first) return end('unavailable', null)
|
|
333
|
+
if (!first.ok) return TRANSIENT_CODES.has(first.code) ? end('unavailable', first.code) : endFor(first.code)
|
|
334
|
+
const url = privateRealtimeUrlOf(first.value.url)
|
|
335
|
+
const inbox = inboxChannelOfToken(first.value.token)
|
|
336
|
+
if (!url || !inbox) return end('unavailable', 'BAD_ANSWER')
|
|
337
|
+
channel = inbox
|
|
338
|
+
const mod = await loadCentrifuge(options.centrifuge)
|
|
339
|
+
if (closed()) return
|
|
340
|
+
if (!mod) return end('unavailable', null)
|
|
341
|
+
const stop = (message: string): Error => (mod.UnauthorizedError ? new mod.UnauthorizedError(message) : new Error(message))
|
|
342
|
+
|
|
343
|
+
const getToken = async (): Promise<string> => {
|
|
344
|
+
const held = next
|
|
345
|
+
next = null
|
|
346
|
+
if (held && held.exp - now() > RENEW_MIN_DELAY_MS) {
|
|
347
|
+
scheduleRenewal(held.exp)
|
|
348
|
+
return held.token
|
|
349
|
+
}
|
|
350
|
+
const r = await client.realtime.token()
|
|
351
|
+
if (closed()) throw stop('closed')
|
|
352
|
+
if (r.ok) {
|
|
353
|
+
if (inboxChannelOfToken(r.value.token) !== channel) {
|
|
354
|
+
queueMicrotask(() => end('unavailable', 'BAD_ANSWER'))
|
|
355
|
+
throw stop('BAD_ANSWER')
|
|
356
|
+
}
|
|
357
|
+
scheduleRenewal(expiryOf(r.value))
|
|
358
|
+
return r.value.token
|
|
359
|
+
}
|
|
360
|
+
// Transient: Centrifuge asks again with its backoff. Final: it stops, and so does this client.
|
|
361
|
+
if (TRANSIENT_CODES.has(r.code)) throw new Error(r.code)
|
|
362
|
+
queueMicrotask(() => endFor(r.code))
|
|
363
|
+
throw stop(r.code)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const base = url
|
|
367
|
+
const c = new mod.Centrifuge(
|
|
368
|
+
[
|
|
369
|
+
{ transport: 'websocket', endpoint: `${base.replace(/^http/, 'ws')}/connection/websocket` },
|
|
370
|
+
{ transport: 'http_stream', endpoint: `${base}/connection/http_stream` },
|
|
371
|
+
],
|
|
372
|
+
{ token: first.value.token, getToken, emulationEndpoint: `${base}/emulation`, name: 'blogmcp-private' },
|
|
373
|
+
)
|
|
374
|
+
centrifuge = c
|
|
375
|
+
c.on('connecting', () => {
|
|
376
|
+
if (c === centrifuge && mode === 'live') setMode('connecting')
|
|
377
|
+
})
|
|
378
|
+
c.on('subscribed', (ctx: unknown) => {
|
|
379
|
+
if (c === centrifuge && isRecord(ctx) && ctx.channel === channel) setMode('live')
|
|
380
|
+
})
|
|
381
|
+
c.on('unsubscribed', (ctx: unknown) => {
|
|
382
|
+
// The server took the inbox away while the connection stays: nothing more can arrive on it.
|
|
383
|
+
if (c === centrifuge && isRecord(ctx) && ctx.channel === channel) end('refused', null)
|
|
384
|
+
})
|
|
385
|
+
c.on('publication', (ctx: unknown) => {
|
|
386
|
+
if (c !== centrifuge || !isRecord(ctx) || ctx.channel !== channel) return
|
|
387
|
+
const event = privateRealtimeEventOf(ctx.data)
|
|
388
|
+
if (!event) return
|
|
389
|
+
for (const listener of [...listeners]) {
|
|
390
|
+
try {
|
|
391
|
+
listener(event)
|
|
392
|
+
} catch {
|
|
393
|
+
// One listener's failure does not keep the event from the others.
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
})
|
|
397
|
+
c.on('disconnected', (ctx: unknown) => {
|
|
398
|
+
if (c !== centrifuge) return
|
|
399
|
+
const code = isRecord(ctx) ? ctx.code : undefined
|
|
400
|
+
// 1: a getToken that threw UnauthorizedError (the refusal already ended it, or does so in a microtask).
|
|
401
|
+
if (code === 1) return end('refused', null)
|
|
402
|
+
if (code === REVOKED_CODE || isTerminalCode(code)) return end('revoked', String(code))
|
|
403
|
+
})
|
|
404
|
+
scheduleRenewal(expiryOf(first.value))
|
|
405
|
+
c.connect()
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
return {
|
|
409
|
+
get mode() {
|
|
410
|
+
return mode
|
|
411
|
+
},
|
|
412
|
+
get channel() {
|
|
413
|
+
return channel
|
|
414
|
+
},
|
|
415
|
+
subscribe(listener) {
|
|
416
|
+
if (closed() || typeof listener !== 'function') return () => {}
|
|
417
|
+
listeners.add(listener)
|
|
418
|
+
if (mode === 'idle') void start().catch(() => end('unavailable', null))
|
|
419
|
+
let subscribed = true
|
|
420
|
+
return () => {
|
|
421
|
+
if (!subscribed) return
|
|
422
|
+
subscribed = false
|
|
423
|
+
listeners.delete(listener)
|
|
424
|
+
if (listeners.size === 0) end('closed', null)
|
|
425
|
+
}
|
|
426
|
+
},
|
|
427
|
+
close() {
|
|
428
|
+
end('closed', null)
|
|
429
|
+
},
|
|
430
|
+
}
|
|
431
|
+
}
|