@blogmcp/sdk 0.9.4 → 0.10.1

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.
Files changed (59) hide show
  1. package/dist/community/channels.d.ts +7 -6
  2. package/dist/community/channels.js +4 -4
  3. package/dist/community/client.d.ts +74 -4
  4. package/dist/community/client.js +143 -91
  5. package/dist/community/index.d.ts +11 -6
  6. package/dist/community/index.js +111 -80
  7. package/dist/community/links.d.ts +61 -1
  8. package/dist/community/links.js +94 -40
  9. package/dist/community/manifest/index.d.ts +54 -0
  10. package/dist/community/manifest/index.js +46 -0
  11. package/dist/community/mentions.d.ts +38 -0
  12. package/dist/community/mentions.js +25 -0
  13. package/dist/community/messages.cs.d.ts +73 -3
  14. package/dist/community/messages.cs.js +82 -3
  15. package/dist/community/messages.d.ts +11 -0
  16. package/dist/community/messages.en.d.ts +69 -1
  17. package/dist/community/messages.en.js +71 -1
  18. package/dist/community/messages.js +26 -16
  19. package/dist/community/outcome.d.ts +8 -3
  20. package/dist/community/outcome.js +75 -28
  21. package/dist/community/realtime/index.d.ts +118 -0
  22. package/dist/community/realtime/index.js +215 -0
  23. package/dist/community/routes.d.ts +12 -0
  24. package/dist/community/routes.js +41 -25
  25. package/dist/community/server/bff.js +25 -25
  26. package/dist/community/server/host-routes.js +12 -0
  27. package/dist/community/server/index.d.ts +1 -1
  28. package/dist/community/server/index.js +15 -14
  29. package/dist/community/server/route-decision.d.ts +8 -0
  30. package/dist/community/server/route-decision.js +28 -22
  31. package/dist/community/shapes.d.ts +214 -2
  32. package/dist/community/shapes.js +65 -25
  33. package/dist/community/store.d.ts +18 -1
  34. package/dist/community/store.js +316 -261
  35. package/dist/community/sw/index.d.ts +45 -0
  36. package/dist/community/sw/index.js +59 -0
  37. package/dist/community/ua.d.ts +12 -0
  38. package/dist/community/ua.js +9 -0
  39. package/package.json +20 -3
  40. package/src/community/channels.ts +8 -7
  41. package/src/community/client.ts +116 -5
  42. package/src/community/index.ts +59 -1
  43. package/src/community/links.ts +119 -2
  44. package/src/community/manifest/index.ts +107 -0
  45. package/src/community/mentions.ts +59 -0
  46. package/src/community/messages.cs.ts +88 -3
  47. package/src/community/messages.en.ts +77 -1
  48. package/src/community/messages.ts +19 -0
  49. package/src/community/outcome.ts +53 -1
  50. package/src/community/realtime/index.ts +522 -0
  51. package/src/community/routes.ts +16 -0
  52. package/src/community/server/bff.ts +2 -4
  53. package/src/community/server/host-routes.ts +12 -0
  54. package/src/community/server/index.ts +1 -0
  55. package/src/community/server/route-decision.ts +15 -0
  56. package/src/community/shapes.ts +256 -3
  57. package/src/community/store.ts +114 -0
  58. package/src/community/sw/index.ts +112 -0
  59. package/src/community/ua.ts +17 -0
@@ -62,6 +62,16 @@ export const COMMUNITY_UI_CODES = [
62
62
  'notMoved',
63
63
  /** kb-api could not record the change; nothing changed — retry. */
64
64
  'ledger',
65
+ /** The community's extra features are off for now (MyState `module.until` says until when): the discussions under articles keep working, this feature does not. */
66
+ 'readOnly',
67
+ /** The community is paused for now (`until` when the pause has an end): reading works, writing does not. */
68
+ 'braked',
69
+ /** M2 T3: more @mentions in one message than the member may use yet. */
70
+ 'mentionLimit',
71
+ /** M2 T4: the browser's push service is not one the community sends to (or could not be reached): no notifications on this browser. */
72
+ 'pushRefused',
73
+ /** M2 T5: live updates are not on here: the discussion keeps itself fresh by polling (pollDiscussionHead). */
74
+ 'realtimeOff',
65
75
  /** Anything else: "that did not work, try again". */
66
76
  'submit',
67
77
  ] as const
@@ -85,10 +95,15 @@ export interface CommunityFailure {
85
95
  needs?: KnownNeed[]
86
96
  /** FILTER_BLOCKED, CONFIRMATION_REQUIRED: the filter codes (CONFIRMATION_REQUIRED: the ones to confirm). */
87
97
  codes?: string[]
88
- /** POSTING_RESTRICTED, ACCOUNT_SUSPENDED: when it ends (absent: no end set). */
98
+ /** POSTING_RESTRICTED, ACCOUNT_SUSPENDED, MODULE_READ_ONLY, BRAKED: when it ends (absent: no end set). */
89
99
  until?: string
90
100
  /** VALIDATION: the paths of the refused fields (`displayName`, `body`, …), never their values. */
91
101
  fields?: string[]
102
+ /**
103
+ * VALIDATION: the codes kb-api gave some of those fields (`issues[].code`; M2 T9: `art9_refusal_read_only` on
104
+ * `art9Refused`) — a code only, never zod's message. Absent when none was given.
105
+ */
106
+ issueCodes?: string[]
92
107
  }
93
108
 
94
109
  /** What every client method resolves to; none of them throws. */
@@ -125,6 +140,19 @@ export const COMMUNITY_API_CODES = [
125
140
  'STAFF_POSTING_OFF',
126
141
  'PRESET_CONFLICT',
127
142
  'INTERNAL',
143
+ 'MODULE_DARK',
144
+ 'MODULE_READ_ONLY',
145
+ 'BRAKED',
146
+ 'BRAKE_PLATFORM',
147
+ 'MODULE_CONDITIONS',
148
+ 'TRUST_LEVEL_INVALID',
149
+ 'MENTION_LIMIT',
150
+ 'DIGEST_UNSUBSCRIBE_INVALID',
151
+ 'PUSH_ENDPOINT_REFUSED',
152
+ 'PUSH_LIMIT',
153
+ 'REALTIME_OFF',
154
+ 'BUSY',
155
+ 'BRAKE_KIND_MISMATCH',
128
156
  'NOT_A_MEMBER_SESSION',
129
157
  'IDENTITY_NOT_ADMITTED',
130
158
  'ACCOUNT_NOT_ELIGIBLE',
@@ -148,6 +176,7 @@ export const COMMUNITY_API_CODES = [
148
176
  'INVALID_INPUT',
149
177
  'LEGAL_HOLD',
150
178
  'TEXT_MISSING',
179
+ 'AGE16_NOT_ALLOWED',
151
180
  'QUOTA_DAILY',
152
181
  'QUOTA_IP_HOURLY',
153
182
  ] as const
@@ -191,6 +220,27 @@ export const COMMUNITY_OUTCOME_OF_KB: Readonly<Record<CommunityApiCode, Communit
191
220
  STAFF_POSTING_OFF: 'submit',
192
221
  PRESET_CONFLICT: 'submit',
193
222
  INTERNAL: 'unavailable',
223
+ // M2 (m2-contracts.md §3.1): a Pro surface of a tenant without the module answers as one that is not there.
224
+ MODULE_DARK: 'unavailable',
225
+ MODULE_READ_ONLY: 'readOnly',
226
+ BRAKED: 'braked',
227
+ // The team's and the platform's own refusals: no public operation produces them.
228
+ BRAKE_PLATFORM: 'submit',
229
+ MODULE_CONDITIONS: 'submit',
230
+ // M2 T2: the team's members/set-trust-level with a level outside 0..3 (no public operation produces it).
231
+ TRUST_LEVEL_INVALID: 'invalid',
232
+ // M2 T3 (§3.3): too many @handles for the member's trust level; an unsubscribe link that is not (or no longer) valid.
233
+ MENTION_LIMIT: 'mentionLimit',
234
+ DIGEST_UNSUBSCRIBE_INVALID: 'invalid',
235
+ // M2 T4 (§3.4): a push endpoint kb-api will not send to; more than 10 subscriptions, or the push quota spent (retryAfterS).
236
+ PUSH_ENDPOINT_REFUSED: 'pushRefused',
237
+ PUSH_LIMIT: 'quota',
238
+ // M2 T5 (§3.5): the module is neither live nor braked, or live updates are not configured — poll instead.
239
+ REALTIME_OFF: 'realtimeOff',
240
+ // F-W0-M4: the team router's lock timeout or deadlock (module/enable's first ranking) — no public operation produces it.
241
+ BUSY: 'submit',
242
+ // M2 follow-up F3: the platform's brakes/lift found another kind of brake (no public operation produces it).
243
+ BRAKE_KIND_MISMATCH: 'submit',
194
244
  // A session that is not a reader's (the team, a key) or an identity the tenant does not admit: sign in as a reader.
195
245
  NOT_A_MEMBER_SESSION: 'signIn',
196
246
  IDENTITY_NOT_ADMITTED: 'signIn',
@@ -219,6 +269,8 @@ export const COMMUNITY_OUTCOME_OF_KB: Readonly<Record<CommunityApiCode, Communit
219
269
  LEGAL_HOLD: 'submit',
220
270
  // The tenant has not published the text a join needs: the community cannot be joined yet.
221
271
  TEXT_MISSING: 'unavailable',
272
+ // M2 T9: the team's settings/update only (the age limit 16 for a tenant its size class does not allow it).
273
+ AGE16_NOT_ALLOWED: 'submit',
222
274
  QUOTA_DAILY: 'quota',
223
275
  QUOTA_IP_HOURLY: 'quota',
224
276
  } satisfies Record<CommunityApiCode, CommunityUiCode>)
@@ -0,0 +1,522 @@
1
+ /**
2
+ * `@blogmcp/sdk/community/realtime` — live updates of one article discussion (docs/internal/m2-contracts.md §3.5
3
+ * "The client", §3.10; community.md §7.4). A separate entry with the peer dependency `centrifuge` (≥ 5.7, MIT),
4
+ * optional for the PACKAGE, not for this entry: a host that never imports this entry ships no socket code and needs
5
+ * no `centrifuge`; a host that imports it installs `centrifuge` (a bundler resolves the entry's `import('centrifuge')`
6
+ * at build time and fails without it). Without a bundler, or with the module passed as `centrifuge`, an import that
7
+ * fails at run time keeps the session polling.
8
+ *
9
+ * const session = createRealtimeSession({ client, store }) // after the first discussions/list
10
+ * // on unmount: session.stop()
11
+ *
12
+ * What it does:
13
+ * - asks `me/realtime/token` for a connection token AND the URL to connect to — the only source of that URL (this
14
+ * entry builds none from configuration: the endpoints are `${url}/connection/websocket`, `${url}/connection/
15
+ * http_stream` and `${url}/emulation` of kb-api's answer);
16
+ * - subscribes to `disc:<conversationId>` (the store's conversation, or `channel`) with `realtime/subscribe-token`;
17
+ * Centrifuge asks again when a token expires (`getToken`), and a connection the server ends as unauthorized is
18
+ * opened again with a fresh token (with jitter, a few times);
19
+ * - hands every publication to `store.applyEvent` (the delta by `rev`); an answer `resync`, a `resync` publication,
20
+ * every successful subscribe (the first one and each after a reconnect), the page shown again
21
+ * (`visibilitychange → visible`) and `online` re-read the discussion (refreshDiscussion: the pages loaded);
22
+ * - the viewer's own post is shown by its write's answer (its `clientMsgId`), not by the channel;
23
+ * - a change of the viewer (the store's `viewer.memberId`: a host session's first join turns its `v:` subject into
24
+ * the member) opens the connection again with a fresh token — Centrifugo binds a connection to its user, so the
25
+ * member's tokens would be refused on the visitor's connection, and a disconnect of the member must reach it;
26
+ * - falls back to `pollDiscussionHead` when kb-api answers `realtimeOff` (outside a live or braked module, or where
27
+ * live updates are not configured), `signIn` (an anonymous reader: tokens are for host sessions), a subscribe
28
+ * token is refused, `centrifuge` is not installed, or the server cuts the connection for good;
29
+ * - M2 T10, the watchdog: when the subscription is not live within REALTIME_WATCHDOG_MS (15 s) of connecting — the
30
+ * first time or after the connection dropped (the realtime endpoint unreachable, a proxy that drops the upgrade) — the discussion
31
+ * polls (`polling`) while Centrifuge keeps reconnecting on its own, and goes `live` again (the poller stopped, the
32
+ * discussion re-read) once it subscribes;
33
+ * - M2 T10, a revoked session (the server's 4501: the back channel or a self-service cut-off disconnected the
34
+ * user): `me/realtime/token` is asked ONCE more and the connection opened again only when it answers — a member
35
+ * whose own password change cut the old session keeps a live page under the new one; a refusal, or a second
36
+ * 4501 in this session, polls for good.
37
+ */
38
+
39
+ import type { CommunityCallOptions, CommunityClient } from '../client'
40
+ import { COMMUNITY_CHANNELS } from '../channels'
41
+ import { pollDiscussionHead, type DiscussionHeadPoller, type PollDiscussionHeadOptions } from '../poll'
42
+ import type { RealtimeEvent, RealtimeToken } from '../shapes'
43
+ import { refreshDiscussion, type DiscussionStore } from '../store'
44
+
45
+ // ───────────────────────── the part of centrifuge this entry uses ─────────────────────────
46
+
47
+ /** A Centrifuge subscription, as far as this entry uses it. */
48
+ export interface RealtimeSubscriptionLike {
49
+ on(event: 'publication' | 'subscribed' | 'unsubscribed' | 'error', listener: (ctx: any) => void): unknown
50
+ subscribe(): void
51
+ unsubscribe(): void
52
+ }
53
+
54
+ /** A Centrifuge client, as far as this entry uses it. */
55
+ export interface RealtimeClientLike {
56
+ on(event: 'connected' | 'connecting' | 'disconnected' | 'error', listener: (ctx: any) => void): unknown
57
+ newSubscription(channel: string, options: { getToken: (ctx: { channel: string }) => Promise<string>; token?: string }): RealtimeSubscriptionLike
58
+ connect(): void
59
+ disconnect(): void
60
+ removeSubscription?(sub: RealtimeSubscriptionLike | null): void
61
+ }
62
+
63
+ export type RealtimeTransportEndpoint = { transport: 'websocket' | 'http_stream'; endpoint: string }
64
+
65
+ /** `centrifuge`'s module, as far as this entry uses it (tests pass a fake one). */
66
+ export interface CentrifugeModuleLike {
67
+ Centrifuge: new (
68
+ endpoints: RealtimeTransportEndpoint[],
69
+ options: { token?: string; getToken: () => Promise<string>; emulationEndpoint: string; name?: string },
70
+ ) => RealtimeClientLike
71
+ /** Thrown from getToken, it tells Centrifuge to stop (no retry). */
72
+ UnauthorizedError?: new (message?: string) => Error
73
+ }
74
+
75
+ // ───────────────────────── the session ─────────────────────────
76
+
77
+ export type RealtimeMode = 'connecting' | 'live' | 'polling' | 'stopped'
78
+
79
+ export interface RealtimeSessionOptions {
80
+ client: Pick<CommunityClient, 'discussions' | 'me' | 'realtime'>
81
+ store: DiscussionStore
82
+ /**
83
+ * `disc:<conversationId>`; default the store's conversation (a discussion without one polls until it has one). The id
84
+ * is used in lower case (kb-api publishes to, and mints tokens for, the lower-case channel).
85
+ */
86
+ channel?: string
87
+ /** The discussion's language, for the re-reads (as the page's discussions/list asks). */
88
+ languageCode?: string | null
89
+ /** The `centrifuge` module, or a loader of it (tests); default `import('centrifuge')`. */
90
+ centrifuge?: CentrifugeModuleLike | (() => Promise<CentrifugeModuleLike>)
91
+ /** Whether the discussion is seen now (default: the document is visible); the fallback polls only then. */
92
+ visible?: () => boolean
93
+ /** The fallback poller's interval (pollDiscussionHead's default otherwise). */
94
+ pollIntervalMs?: number
95
+ /** Called on every change of mode. */
96
+ onMode?: (mode: RealtimeMode) => void
97
+ /** Aborting it stops the session. */
98
+ signal?: AbortSignal
99
+ }
100
+
101
+ export interface RealtimeSession {
102
+ readonly mode: RealtimeMode
103
+ /** Re-reads the discussion now (coalesced with one already on its way). */
104
+ resync(): Promise<void>
105
+ /** Ends the session: no socket, no poller, no listener. */
106
+ stop(): void
107
+ }
108
+
109
+ /**
110
+ * How long a connection may take to become live (subscribed) before the discussion polls meanwhile (M2 T10). The
111
+ * poll stops again on the next subscribe; Centrifuge's own reconnects (with its backoff) go on underneath.
112
+ */
113
+ export const REALTIME_WATCHDOG_MS = 15_000
114
+ /** Centrifugo's „session revoked" (kb-api's disconnectRealtimeUser): one fresh token is tried before polling. */
115
+ const REVOKED_CODE = 4501
116
+
117
+ /** A server's disconnect codes after which Centrifugo does not reconnect (3500–3999, 4500–4999). */
118
+ const isTerminalCode = (code: unknown): boolean => typeof code === 'number' && ((code >= 3500 && code < 4000) || (code >= 4500 && code < 5000))
119
+ /** How often an unauthorized connection is opened again with a fresh token before the session polls. */
120
+ const REMINT_MAX = 3
121
+ const REMINT_BASE_MS = 1_000
122
+
123
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
124
+
125
+ /**
126
+ * The connection URL of kb-api's answer, without a trailing slash — an absolute http(s) URL with no credentials, or
127
+ * null (then the session polls).
128
+ */
129
+ export function realtimeUrlOf(url: unknown): string | null {
130
+ if (typeof url !== 'string' || url.length > 2048) return null
131
+ let parsed: URL
132
+ try {
133
+ parsed = new URL(url)
134
+ } catch {
135
+ return null
136
+ }
137
+ if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || parsed.username || parsed.password || parsed.search || parsed.hash) return null
138
+ return parsed.href.replace(/\/+$/, '')
139
+ }
140
+
141
+ /** Centrifuge's endpoints under kb-api's URL (websocket first, http_stream as the fallback). */
142
+ export function realtimeEndpointsOf(url: string): { endpoints: RealtimeTransportEndpoint[]; emulationEndpoint: string } {
143
+ return {
144
+ endpoints: [
145
+ { transport: 'websocket', endpoint: `${url.replace(/^http/, 'ws')}/connection/websocket` },
146
+ { transport: 'http_stream', endpoint: `${url}/connection/http_stream` },
147
+ ],
148
+ emulationEndpoint: `${url}/emulation`,
149
+ }
150
+ }
151
+
152
+ async function loadCentrifuge(option: RealtimeSessionOptions['centrifuge']): Promise<CentrifugeModuleLike | null> {
153
+ try {
154
+ if (typeof option === 'function') return await option()
155
+ if (option) return option
156
+ // The optional peer dependency: absent, the import fails and the session polls.
157
+ const mod = (await import('centrifuge')) as unknown as CentrifugeModuleLike
158
+ return mod && typeof mod.Centrifuge === 'function' ? mod : null
159
+ } catch {
160
+ return null
161
+ }
162
+ }
163
+
164
+ export function createRealtimeSession(options: RealtimeSessionOptions): RealtimeSession {
165
+ const { client, store } = options
166
+ const visible = options.visible ?? ((): boolean => typeof document === 'undefined' || document.visibilityState !== 'hidden')
167
+ let mode: RealtimeMode = 'connecting'
168
+ let stopped = false
169
+ let centrifuge: RealtimeClientLike | null = null
170
+ let sub: RealtimeSubscriptionLike | null = null
171
+ let poller: DiscussionHeadPoller | null = null
172
+ let unsubscribeStore: (() => void) | null = null
173
+ let remints = 0
174
+ let remintTimer: ReturnType<typeof setTimeout> | null = null
175
+ /** The connect watchdog (M2 T10): armed while connecting, cleared by a subscribe. */
176
+ let watchdog: ReturnType<typeof setTimeout> | null = null
177
+ /** Polling only while the socket reconnects (the watchdog fired); a subscribe ends it. */
178
+ let fallback = false
179
+ /** The one retry after a revoked session (4501) is spent. */
180
+ let revokedRetried = false
181
+ let reading: Promise<void> | null = null
182
+ let readAgain = false
183
+ /** The connect attempt that is current: an older one still on its way (a token, the module) gives up. */
184
+ let attempt = 0
185
+ let viewerMember: string | null = store.getState().viewer.memberId
186
+ let unsubscribeViewer: (() => void) | null = null
187
+ const controller = new AbortController()
188
+ const call: CommunityCallOptions = { signal: controller.signal }
189
+
190
+ const setMode = (next: RealtimeMode): void => {
191
+ if (mode === next) return
192
+ mode = next
193
+ try {
194
+ options.onMode?.(next)
195
+ } catch {
196
+ // The page's handler must not stop the session.
197
+ }
198
+ }
199
+
200
+ const articleId = (): string | null => store.getState().articleId
201
+
202
+ async function readOnce(): Promise<void> {
203
+ const id = articleId()
204
+ if (!id || stopped) return
205
+ await refreshDiscussion(store, client, { articleId: id, languageCode: options.languageCode ?? null }, call)
206
+ }
207
+
208
+ function resync(): Promise<void> {
209
+ if (stopped) return Promise.resolve()
210
+ if (reading) {
211
+ readAgain = true
212
+ return reading
213
+ }
214
+ reading = (async () => {
215
+ try {
216
+ do {
217
+ readAgain = false
218
+ await readOnce()
219
+ } while (readAgain && !stopped)
220
+ } finally {
221
+ reading = null
222
+ }
223
+ })()
224
+ return reading
225
+ }
226
+
227
+ function clearWatchdog(): void {
228
+ if (watchdog) clearTimeout(watchdog)
229
+ watchdog = null
230
+ }
231
+
232
+ function closeSocket(): void {
233
+ if (remintTimer) clearTimeout(remintTimer)
234
+ remintTimer = null
235
+ clearWatchdog()
236
+ fallback = false
237
+ const c = centrifuge
238
+ centrifuge = null
239
+ const s = sub
240
+ sub = null
241
+ try {
242
+ s?.unsubscribe()
243
+ c?.removeSubscription?.(s)
244
+ c?.disconnect()
245
+ } catch {
246
+ // A socket that is going anyway.
247
+ }
248
+ }
249
+
250
+ /** The head poller over the store's article, when there is one and none runs yet. */
251
+ function startPoller(): void {
252
+ const id = articleId()
253
+ if (!id || poller || stopped) return
254
+ const pollOptions: PollDiscussionHeadOptions = {
255
+ visible,
256
+ signal: controller.signal,
257
+ onChange: (heads) => {
258
+ if (heads.some((h) => store.applyHead(h))) void resync()
259
+ },
260
+ }
261
+ if (options.pollIntervalMs !== undefined) pollOptions.intervalMs = options.pollIntervalMs
262
+ poller = pollDiscussionHead(client, [id], pollOptions)
263
+ }
264
+
265
+ /** Polling for good: the socket goes, the head poller runs (once the store names its article). */
266
+ function poll(): void {
267
+ if (stopped) return
268
+ closeSocket()
269
+ setMode('polling')
270
+ if (poller) return
271
+ startPoller()
272
+ if (!poller && !unsubscribeStore) unsubscribeStore = store.subscribe(() => startPoller())
273
+ }
274
+
275
+ /**
276
+ * The watchdog of one connection (M2 T10): not live within REALTIME_WATCHDOG_MS → poll meanwhile, the socket kept
277
+ * (Centrifuge reconnects by itself). Armed on subscribe and on every `connecting` (a dropped connection); a no-op
278
+ * while the meanwhile-poll already runs, and while there is no subscription to wait for — a discussion without a
279
+ * conversation yet polls on its own and its healthy socket is never 'live' until the first message (centrifuge-js
280
+ * emits `connecting` on every connect(), so arming there unconditionally would flip it to polling after 15 s).
281
+ */
282
+ function armWatchdog(c: RealtimeClientLike): void {
283
+ if (stopped || fallback || c !== centrifuge || sub === null) return
284
+ clearWatchdog()
285
+ watchdog = setTimeout(() => {
286
+ watchdog = null
287
+ if (stopped || c !== centrifuge || sub === null || mode === 'live' || mode === 'polling') return
288
+ fallback = true
289
+ setMode('polling')
290
+ startPoller()
291
+ }, REALTIME_WATCHDOG_MS)
292
+ }
293
+
294
+ /** Subscribed (again): the watchdog and a meanwhile-poll end, the discussion is live. */
295
+ function becameLive(): void {
296
+ clearWatchdog()
297
+ if (fallback) {
298
+ fallback = false
299
+ poller?.stop()
300
+ poller = null
301
+ }
302
+ setMode('live')
303
+ }
304
+
305
+ /**
306
+ * The server revoked the session (4501): the socket goes; one fresh `me/realtime/token` — answered, the session
307
+ * connects again with it (a new session of the same member: its own password change); refused, polling for good.
308
+ */
309
+ async function afterRevoked(): Promise<void> {
310
+ closeSocket()
311
+ // As reconnect(): the old connection's head poller (a no-conversation wait or a watchdog fallback) and its store
312
+ // wait go with it — connect() starts its own, and poll() its own on a refusal.
313
+ poller?.stop()
314
+ poller = null
315
+ unsubscribeStore?.()
316
+ unsubscribeStore = null
317
+ setMode('connecting')
318
+ const mine = attempt
319
+ const r = await client.me.realtime.token(call)
320
+ if (stopped || mine !== attempt) return
321
+ if (!r.ok) return poll()
322
+ await connect(r.value)
323
+ }
324
+
325
+ const channelOf = (): string | null => {
326
+ if (typeof options.channel === 'string' && options.channel !== '') return options.channel.toLowerCase()
327
+ const id = store.getState().conversationId
328
+ return id ? COMMUNITY_CHANNELS.discussion(id) : null
329
+ }
330
+
331
+ /** One connection: the module, a token (or the one `afterRevoked` already has), the socket, the subscription. */
332
+ async function connect(minted?: RealtimeToken): Promise<void> {
333
+ const mine = ++attempt
334
+ const current = (): boolean => mine === attempt && !stopped
335
+ const mod = await loadCentrifuge(options.centrifuge)
336
+ if (!current()) return
337
+ if (!mod) return poll()
338
+ const first = minted ? { ok: true as const, value: minted } : await client.me.realtime.token(call)
339
+ if (!current()) return
340
+ if (!first.ok) return poll()
341
+ const url = realtimeUrlOf(first.value.url)
342
+ if (!url) return poll()
343
+ const stop = (message: string): Error => (mod.UnauthorizedError ? new mod.UnauthorizedError(message) : new Error(message))
344
+
345
+ const getToken = async (): Promise<string> => {
346
+ const r = await client.me.realtime.token(call)
347
+ if (r.ok) return r.value.token
348
+ if (r.code === 'realtimeOff' || r.code === 'signIn') {
349
+ // Not ours to retry: polling from here on.
350
+ queueMicrotask(poll)
351
+ throw stop(r.code)
352
+ }
353
+ throw new Error(r.code)
354
+ }
355
+ const { endpoints, emulationEndpoint } = realtimeEndpointsOf(url)
356
+ const c = new mod.Centrifuge(endpoints, { token: first.value.token, getToken, emulationEndpoint, name: 'blogmcp-community' })
357
+ centrifuge = c
358
+
359
+ c.on('connected', () => {
360
+ if (c !== centrifuge) return
361
+ remints = 0
362
+ })
363
+ c.on('connecting', () => {
364
+ if (c !== centrifuge || stopped) return
365
+ // A dropped connection Centrifuge opens again: not live meanwhile, and the watchdog watches the way back.
366
+ if (mode === 'live') setMode('connecting')
367
+ armWatchdog(c)
368
+ })
369
+ c.on('disconnected', (ctx: unknown) => {
370
+ if (c !== centrifuge || stopped) return
371
+ const code = isRecord(ctx) ? ctx.code : undefined
372
+ // Unauthorized (an expired or refused token): a fresh token, a few times, then polling.
373
+ if (code === 1 || code === 3500) {
374
+ if (remints >= REMINT_MAX) return poll()
375
+ remints += 1
376
+ if (mode === 'live') setMode('connecting')
377
+ armWatchdog(c)
378
+ const delay = REMINT_BASE_MS * 2 ** (remints - 1) * (0.5 + Math.random())
379
+ remintTimer = setTimeout(() => {
380
+ remintTimer = null
381
+ if (c === centrifuge && !stopped) c.connect()
382
+ }, delay)
383
+ return
384
+ }
385
+ // A revoked session: one fresh token (the member's own new session keeps the page live), then for good.
386
+ if (code === REVOKED_CODE && !revokedRetried) {
387
+ revokedRetried = true
388
+ void afterRevoked().catch(() => poll())
389
+ return
390
+ }
391
+ // Cut for good by the server: no reconnect, the discussion polls.
392
+ if (isTerminalCode(code)) poll()
393
+ })
394
+
395
+ const subscribe = (channel: string): void => {
396
+ const s = c.newSubscription(channel, {
397
+ getToken: async (ctx) => {
398
+ const r = await client.realtime.subscribeToken({ channel: ctx?.channel ?? channel }, call)
399
+ if (r.ok) return r.value.token
400
+ if (r.code === 'notFound' || r.code === 'realtimeOff' || r.code === 'signIn' || r.code === 'surfaceOff') {
401
+ queueMicrotask(poll)
402
+ throw stop(r.code)
403
+ }
404
+ throw new Error(r.code)
405
+ },
406
+ })
407
+ sub = s
408
+ armWatchdog(c)
409
+ s.on('publication', (ctx: unknown) => {
410
+ if (s !== sub || stopped) return
411
+ const data = isRecord(ctx) ? ctx.data : undefined
412
+ if (!isRecord(data)) return
413
+ if (store.applyEvent(data as unknown as RealtimeEvent) === 'resync') void resync()
414
+ })
415
+ s.on('subscribed', () => {
416
+ if (s !== sub || stopped) return
417
+ becameLive()
418
+ // After the subscription is in place: nothing published before it is missed.
419
+ void resync()
420
+ })
421
+ s.on('unsubscribed', (ctx: unknown) => {
422
+ if (s !== sub || stopped) return
423
+ // Refused (unauthorized) or cut by the server: polling.
424
+ if (isRecord(ctx) && ctx.code !== 0) poll()
425
+ })
426
+ s.subscribe()
427
+ }
428
+
429
+ const channel = channelOf()
430
+ if (channel) subscribe(channel)
431
+ else {
432
+ // No conversation yet: poll until the first message creates one, then subscribe.
433
+ const wait = store.subscribe(() => {
434
+ const next = channelOf()
435
+ if (!next || c !== centrifuge || stopped) return
436
+ wait()
437
+ poller?.stop()
438
+ poller = null
439
+ subscribe(next)
440
+ })
441
+ const previous = unsubscribeStore
442
+ unsubscribeStore = () => {
443
+ wait()
444
+ previous?.()
445
+ }
446
+ const id = articleId()
447
+ if (id) {
448
+ const pollOptions: PollDiscussionHeadOptions = {
449
+ visible,
450
+ signal: controller.signal,
451
+ onChange: (heads) => {
452
+ if (heads.some((h) => store.applyHead(h))) void resync()
453
+ },
454
+ }
455
+ if (options.pollIntervalMs !== undefined) pollOptions.intervalMs = options.pollIntervalMs
456
+ poller = pollDiscussionHead(client, [id], pollOptions)
457
+ }
458
+ }
459
+ c.connect()
460
+ }
461
+
462
+ /** Another viewer (the first join, a sign-in, a sign-out): the socket and the poller go, and the session starts over. */
463
+ function reconnect(): void {
464
+ if (stopped) return
465
+ closeSocket()
466
+ poller?.stop()
467
+ poller = null
468
+ unsubscribeStore?.()
469
+ unsubscribeStore = null
470
+ remints = 0
471
+ setMode('connecting')
472
+ void connect().catch(() => poll())
473
+ }
474
+
475
+ const onVisibility = (): void => {
476
+ if (visible() && mode === 'live') void resync()
477
+ }
478
+ const onOnline = (): void => {
479
+ if (mode === 'live') void resync()
480
+ }
481
+
482
+ function stop(): void {
483
+ if (stopped) return
484
+ stopped = true
485
+ closeSocket()
486
+ poller?.stop()
487
+ poller = null
488
+ unsubscribeStore?.()
489
+ unsubscribeStore = null
490
+ unsubscribeViewer?.()
491
+ unsubscribeViewer = null
492
+ controller.abort()
493
+ if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', onVisibility)
494
+ if (typeof window !== 'undefined') window.removeEventListener('online', onOnline)
495
+ options.signal?.removeEventListener('abort', stop)
496
+ setMode('stopped')
497
+ }
498
+
499
+ if (options.signal?.aborted) {
500
+ stopped = true
501
+ mode = 'stopped'
502
+ } else {
503
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', onVisibility)
504
+ if (typeof window !== 'undefined') window.addEventListener('online', onOnline)
505
+ options.signal?.addEventListener('abort', stop, { once: true })
506
+ unsubscribeViewer = store.subscribe((state) => {
507
+ const next = state.viewer.memberId
508
+ if (next === viewerMember) return
509
+ viewerMember = next
510
+ reconnect()
511
+ })
512
+ void connect().catch(() => poll())
513
+ }
514
+
515
+ return {
516
+ get mode() {
517
+ return mode
518
+ },
519
+ resync,
520
+ stop,
521
+ }
522
+ }
@@ -47,6 +47,22 @@ export const COMMUNITY_OPS = Object.freeze({
47
47
  'me.updateProfile': op('me.updateProfile', 'public', '/community/v1/public/me/profile/update'),
48
48
  'me.notifications.list': op('me.notifications.list', 'public', '/community/v1/public/me/notifications/list'),
49
49
  'me.notifications.markRead': op('me.notifications.markRead', 'public', '/community/v1/public/me/notifications/mark-read'),
50
+ // M2 T3 (m2-contracts.md §3.3, §5.1): the badge, the member's switches and its mutes.
51
+ 'me.notifications.unreadCount': op('me.notifications.unreadCount', 'public', '/community/v1/public/me/notifications/unread-count'),
52
+ 'me.settings.get': op('me.settings.get', 'public', '/community/v1/public/me/settings/get'),
53
+ 'me.settings.update': op('me.settings.update', 'public', '/community/v1/public/me/settings/update'),
54
+ 'me.settings.unsubscribeDigest': op('me.settings.unsubscribeDigest', 'public', '/community/v1/public/me/settings/unsubscribe-digest'),
55
+ 'me.mutes.set': op('me.mutes.set', 'public', '/community/v1/public/me/mutes/set'),
56
+ 'me.mutes.list': op('me.mutes.list', 'public', '/community/v1/public/me/mutes/list'),
57
+ // M2 T4 (m2-contracts.md §3.4, §5.1): web push — the VAPID key, a browser's subscription, its removal.
58
+ 'me.push.vapid': op('me.push.vapid', 'public', '/community/v1/public/me/push/vapid'),
59
+ 'me.push.subscribe': op('me.push.subscribe', 'public', '/community/v1/public/me/push/subscribe'),
60
+ 'me.push.unsubscribe': op('me.push.unsubscribe', 'public', '/community/v1/public/me/push/unsubscribe'),
61
+ // M2 T10 (m2-contracts.md Appendix A D-M2-10): whether kb-api still holds this browser's subscription for the member.
62
+ 'me.push.status': op('me.push.status', 'public', '/community/v1/public/me/push/status'),
63
+ // M2 T5 (m2-contracts.md §3.5, §5.1): live updates — the connection token (with the URL to connect to) and a channel's.
64
+ 'me.realtime.token': op('me.realtime.token', 'public', '/community/v1/public/me/realtime/token'),
65
+ 'realtime.subscribeToken': op('realtime.subscribeToken', 'public', '/community/v1/public/realtime/subscribe-token'),
50
66
  'me.decisions.list': op('me.decisions.list', 'public', '/community/v1/public/me/decisions/list'),
51
67
  'me.decisions.get': op('me.decisions.get', 'public', '/community/v1/public/me/decisions/get'),
52
68
  'me.appeals.file': op('me.appeals.file', 'public', '/community/v1/public/me/appeals/file'),
@@ -58,7 +58,7 @@ import {
58
58
  type CommunityJsonRefusal,
59
59
  type CommunityResponse,
60
60
  } from './http'
61
- import { communityRouteDecision } from './route-decision'
61
+ import { communityRouteDecision, isNoticeRoute } from './route-decision'
62
62
  import { communityUnknownPath } from './unknown-path'
63
63
 
64
64
  /**
@@ -174,8 +174,6 @@ const BASE_PATH_RE = /^(?:\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)*\/?$/
174
174
  /** A kb-api code as it may appear in a log line; anything else is `other`. */
175
175
  const LOGGABLE_CODE_RE = /^[A-Z][A-Z0-9_]{0,63}$/
176
176
 
177
- const NOTICE_ROUTE_PREFIX = '/trust/v1/notices/'
178
-
179
177
  // ───────────────────────── configuration ─────────────────────────
180
178
 
181
179
  /**
@@ -501,7 +499,7 @@ export function createCommunityBff(c: CommunityBffConfig): CommunityBff {
501
499
 
502
500
  // 5. The upstream call.
503
501
  if (base === null) return unavailable(request.op)
504
- const noticeRoute = decision.upstreamPath.startsWith(NOTICE_ROUTE_PREFIX)
502
+ const noticeRoute = isNoticeRoute(decision.upstreamPath)
505
503
  const credential = await credentialOf(http, noticeRoute)
506
504
  if (credential.kind === 'unavailable') return unavailable(request.op)
507
505
  const clientIp = clientIpFrom(http, { header: clientIpHeader })