@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
@@ -30,17 +30,29 @@ export const COMMUNITY_HOST_ROUTES: readonly CommunityHostRoute[] = Object.freez
30
30
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/erase/cancel' }),
31
31
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/export' }),
32
32
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/get' }),
33
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/mutes/list' }),
34
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/mutes/set' }),
33
35
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/notifications/list' }),
34
36
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/notifications/mark-read' }),
37
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/notifications/unread-count' }),
35
38
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/onboard' }),
36
39
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/profile/update' }),
40
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/push/status' }),
41
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/push/subscribe' }),
42
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/push/unsubscribe' }),
43
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/push/vapid' }),
44
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/realtime/token' }),
37
45
  Object.freeze({ method: 'POST', path: '/community/v1/public/me/reports/list' }),
46
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/settings/get' }),
47
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/settings/unsubscribe-digest' }),
48
+ Object.freeze({ method: 'POST', path: '/community/v1/public/me/settings/update' }),
38
49
  Object.freeze({ method: 'POST', path: '/community/v1/public/messages/delete' }),
39
50
  Object.freeze({ method: 'POST', path: '/community/v1/public/messages/edit' }),
40
51
  Object.freeze({ method: 'POST', path: '/community/v1/public/messages/post' }),
41
52
  Object.freeze({ method: 'POST', path: '/community/v1/public/messages/report' }),
42
53
  Object.freeze({ method: 'POST', path: '/community/v1/public/profile/get' }),
43
54
  Object.freeze({ method: 'POST', path: '/community/v1/public/reactions/set' }),
55
+ Object.freeze({ method: 'POST', path: '/community/v1/public/realtime/subscribe-token' }),
44
56
  Object.freeze({ method: 'POST', path: '/trust/v1/notices/appeal' }),
45
57
  Object.freeze({ method: 'POST', path: '/trust/v1/notices/appeal/withdraw' }),
46
58
  Object.freeze({ method: 'POST', path: '/trust/v1/notices/status' }),
@@ -39,6 +39,7 @@ export {
39
39
  COMMUNITY_HOST_ROUTES,
40
40
  isCommunityNamespacePath,
41
41
  communityRouteDecision,
42
+ isNoticeRoute,
42
43
  } from './route-decision'
43
44
  export type { CommunityHostRoute, CommunityRouteDecision } from './route-decision'
44
45
 
@@ -224,3 +224,18 @@ export function decideCommunityRoute(
224
224
  export function communityRouteDecision(method: string, path: string): CommunityRouteDecision {
225
225
  return decideCommunityRoute(COMMUNITY_HOST_ROUTES, method, path)
226
226
  }
227
+
228
+ /** kb-api's notice form under its `/trust` namespace: the routes a host session may reach without a member. */
229
+ const NOTICE_ROUTE_PREFIX = '/trust/v1/notices/'
230
+
231
+ /**
232
+ * M2 T10: whether `path` (relative to kb-api's root, as communityRouteDecision takes it) is one of kb-api's notice
233
+ * routes (`/trust/v1/notices/*`) — in every spelling the route decision ALLOWS: with or without the leading `/` and
234
+ * one `api/` segment; a query or fragment is cut first, as the decision cuts it, and the rest decides. A spelling the
235
+ * decision denies (upper case, an escape, a dot segment, an empty segment) and any other path are not: the hosts' one retry under the notice key (m2-contracts.md §12.4) and the BFF's credential rule
236
+ * apply only to a request that is forwarded at all. Never throws.
237
+ */
238
+ export function isNoticeRoute(path: string): boolean {
239
+ const decision = communityRouteDecision('POST', path)
240
+ return decision.kind === 'allow' && decision.upstreamPath.startsWith(NOTICE_ROUTE_PREFIX)
241
+ }
@@ -41,11 +41,33 @@ export type RestrictionKind = Open<KnownRestrictionKind>
41
41
  export const isKnownRestrictionKind = (kind: unknown): kind is KnownRestrictionKind => has(RESTRICTION_KINDS, kind)
42
42
 
43
43
  /** In-app notifications: codes and ids only (`appeal_resolved` is a decision that supersedes another). */
44
- export const NOTIFICATION_CODES = Object.freeze(['decision', 'appeal_resolved', 'erasure_scheduled', 'inactivity_warning'] as const)
44
+ export const NOTIFICATION_CODES = Object.freeze([
45
+ 'decision',
46
+ 'appeal_resolved',
47
+ 'erasure_scheduled',
48
+ 'inactivity_warning',
49
+ // M2 (m2-contracts.md §3.1): the module went read_only; a platform pause without an end.
50
+ 'module_read_only',
51
+ 'module_braked',
52
+ // M2 T3 (§3.3): a reply to the member's message, an @mention; T4: push was reset; T9: the age limit rose.
53
+ 'reply',
54
+ 'mention',
55
+ 'module_push_reset',
56
+ 'age_limit_changed',
57
+ ] as const)
45
58
  export type KnownNotificationCode = (typeof NOTIFICATION_CODES)[number]
46
59
  export type NotificationCode = Open<KnownNotificationCode>
47
60
  export const isKnownNotificationCode = (code: unknown): code is KnownNotificationCode => has(NOTIFICATION_CODES, code)
48
61
 
62
+ /**
63
+ * A member's trust level as its public name (m2-contracts.md §3.2; kb-api's TRUST_LABELS, pinned by
64
+ * test/community/codes-drift.spec.ts), TL0 … TL3 in order. Open: a label a newer kb-api adds reads as no label.
65
+ */
66
+ export const TRUST_LABELS = Object.freeze(['new', 'member', 'regular', 'trusted'] as const)
67
+ export type KnownTrustLabel = (typeof TRUST_LABELS)[number]
68
+ export type TrustLabel = Open<KnownTrustLabel>
69
+ export const isKnownTrustLabel = (label: unknown): label is KnownTrustLabel => has(TRUST_LABELS, label)
70
+
49
71
  // ───────────────────────── closed vocabularies (kb-api validates them) ─────────────────────────
50
72
 
51
73
  /** The report and notice categories (kb-api's CASE_CATEGORIES; test/community/codes-drift.spec.ts pins them). */
@@ -251,6 +273,13 @@ export interface PublicProfile {
251
273
  /** `YYYY-MM` (UTC). */
252
274
  readonly memberSince: string
253
275
  readonly bio: string | null
276
+ /**
277
+ * M2: the member's trust level as its public name (TRUST_LABELS: `new`, `member`, `regular`, `trusted`; an open
278
+ * set — an unknown one reads as no label; its text is trustLabelMessageKey's). Never the number: that is the
279
+ * member's own (MyState.trustLevel). Absent from a kb-api older than M2, and while the community module is `dark`
280
+ * (no level is computed then).
281
+ */
282
+ readonly trustLabel?: TrustLabel
254
283
  }
255
284
 
256
285
  /** The member's own profile (MyState, `me/profile/update`). */
@@ -264,24 +293,214 @@ export interface OwnProfile {
264
293
 
265
294
  // ───────────────────────── the member's own surface (§7.3, §7.4, §8.3) ─────────────────────────
266
295
 
296
+ /** The community module's state (m2-contracts.md §3.1). An unknown state reads as `dark`. */
297
+ export const MODULE_STATES = Object.freeze(['dark', 'live', 'read_only', 'braked'] as const)
298
+ export type KnownModuleState = (typeof MODULE_STATES)[number]
299
+ export type ModuleState = Open<KnownModuleState>
300
+ export const isKnownModuleState = (state: unknown): state is KnownModuleState => has(MODULE_STATES, state)
301
+
302
+ /** MyState's `module`: the state, its end and reason, the pause in effect, what it switches on. */
303
+ export interface ModuleInfo {
304
+ readonly state: ModuleState
305
+ /** read_only or braked: when it ends (absent: no end set). */
306
+ readonly until?: string
307
+ /** read_only: why (a code: plan_lost, kill_switch, tenant_off, …). */
308
+ readonly reason?: string
309
+ /** The pause in effect, whatever the state (a tenant without the module may pause its discussions). */
310
+ readonly brake?: { readonly kind: string; readonly until?: string; readonly reasonCode: string }
311
+ readonly features: { readonly realtime: boolean; readonly push: boolean; readonly notifications: boolean; readonly profiles: boolean }
312
+ }
313
+
314
+ /**
315
+ * How the art. 9 consent is asked (m2-contracts.md §3.8; community.md §9.8 question 8): `joint` one consent, `split`
316
+ * one per controller of the consent text (`art9ControllersOf`) on the same screen. An unknown value reads as `joint`.
317
+ */
318
+ export const ART9_CONSENT_LAYOUTS = Object.freeze(['joint', 'split'] as const)
319
+ export type Art9ConsentLayout = (typeof ART9_CONSENT_LAYOUTS)[number]
320
+ /**
321
+ * What a refused art. 9 consent leaves (§3.8): `read_only` reading only (no refusal is offered — a reader who closes
322
+ * the step keeps reading), `public_write` writing in the public discussion too. An unknown value reads as `read_only`.
323
+ */
324
+ export const ART9_REFUSALS = Object.freeze(['read_only', 'public_write'] as const)
325
+ export type Art9Refusal = (typeof ART9_REFUSALS)[number]
326
+
327
+ /** The layout `me/get` names, `joint` when it names none or one this SDK does not know (an older kb-api). */
328
+ export const art9ConsentLayoutOf = (value: unknown): Art9ConsentLayout => (value === 'split' ? 'split' : 'joint')
329
+ /** The refusal `me/get` names, `read_only` when it names none or one this SDK does not know (an older kb-api). */
330
+ export const art9RefusalOf = (value: unknown): Art9Refusal => (value === 'public_write' ? 'public_write' : 'read_only')
331
+
332
+ /**
333
+ * The tenant's art. 9 settings `me/get` carries next to the member's switches (M2 T9, §3.8); absent from a kb-api
334
+ * older than T9 — read them through art9ConsentLayoutOf / art9RefusalOf.
335
+ */
336
+ export interface CommunityConsentSettings {
337
+ readonly art9ConsentLayout?: Art9ConsentLayout
338
+ readonly art9Refusal?: Art9Refusal
339
+ }
340
+
267
341
  /** `me/get` and `me/onboard`. Anonymous: `member: null`, `needs: ['sign_in']`. */
268
342
  export interface MyState {
269
343
  readonly member: { readonly memberId: string; readonly status: string; readonly identity: string; readonly ageBand: AgeBand | null } | null
270
344
  readonly profile: OwnProfile | null
271
- readonly acceptances: { readonly rules: AcceptanceState; readonly art9Consent: AcceptanceState | null }
345
+ readonly acceptances: {
346
+ readonly rules: AcceptanceState
347
+ readonly art9Consent: AcceptanceState | null
348
+ /**
349
+ * M2 T9 (§3.8): the member refused the art. 9 consent under `art9Refusal = public_write` and has not given it
350
+ * since — `needs` then carries no `art9_consent`. Absent from a kb-api older than T9 (read: false).
351
+ */
352
+ readonly art9Refused?: boolean
353
+ }
272
354
  readonly needs: readonly Need[]
273
355
  readonly restrictions: readonly RestrictionInEffect[]
274
356
  readonly unreadDecisions: number
275
357
  readonly preset: string | null
276
358
  /** The tenant's own deep links (community.settings), when it set them. */
277
359
  readonly links: { readonly statementPath: string | null; readonly myCommunityPath: string | null }
360
+ /** M2: the community module's state (absent from a kb-api older than M2). */
361
+ readonly module?: ModuleInfo
362
+ /**
363
+ * M2: the member's own trust level, 0..3 (0 without a member). Absent from a kb-api older than M2, and while the
364
+ * community module is `dark` (no level is computed then; `caps` stays, TL0's).
365
+ */
366
+ readonly trustLevel?: number
367
+ /**
368
+ * M2 T3: the member's notification switches (the defaults without a member; absent from a kb-api older than M2);
369
+ * M2 T9: with the tenant's art. 9 layout and refusal beside them (CommunityConsentSettings).
370
+ */
371
+ readonly settings?: MemberSettings & CommunityConsentSettings
372
+ /**
373
+ * M2 T10: what the member's trust level allows in one message — `mentionsPerMessage` distinct `@handle`s (kb-api's
374
+ * TRUST_LEVEL_CAPS; 0 without a member). A composer warns before posting more; kb-api still refuses MENTION_LIMIT.
375
+ * Absent from a kb-api older than T10.
376
+ */
377
+ readonly caps?: MemberCaps
378
+ }
379
+
380
+ /** MyState's `caps` (M2 T10). */
381
+ export interface MemberCaps {
382
+ readonly mentionsPerMessage: number
383
+ }
384
+
385
+ /**
386
+ * The member's notification switches (m2-contracts.md §3.3): replies, mentions, topic updates (off by default),
387
+ * push (the master switch), the daily e-mail digest, the night's quiet hours for push (22–7, the site's time).
388
+ */
389
+ export interface MemberSettings {
390
+ readonly notifyReply: boolean
391
+ readonly notifyMention: boolean
392
+ readonly notifyTopic: boolean
393
+ readonly pushEnabled: boolean
394
+ readonly digestEmail: boolean
395
+ readonly quietHours: boolean
396
+ }
397
+
398
+ /** `me/settings/update`: the switches to change; the others keep their value. */
399
+ export type MemberSettingsUpdate = Partial<MemberSettings>
400
+
401
+ /** What a member may mute: a conversation (a discussion) or another member. */
402
+ export const MUTE_TARGET_KINDS = Object.freeze(['conversation', 'member'] as const)
403
+ export type MuteTargetKind = (typeof MUTE_TARGET_KINDS)[number]
404
+
405
+ /** One of the member's mutes (private: nobody else learns of it). */
406
+ export interface MuteEntry {
407
+ readonly targetKind: MuteTargetKind
408
+ readonly targetId: string
409
+ readonly mutedAt: string
410
+ }
411
+
412
+ /** What a browser says it is when it subscribes to push (M2 T4; never the raw user agent). */
413
+ export const PUSH_USER_AGENT_CLASSES = Object.freeze(['android', 'ios', 'desktop', 'other'] as const)
414
+ export type PushUserAgentClass = (typeof PUSH_USER_AGENT_CLASSES)[number]
415
+
416
+ /** `me/push/vapid` (M2 T4): the key `pushManager.subscribe({ applicationServerKey })` takes, and its id. */
417
+ export interface PushVapidKey {
418
+ /** base64url of the uncompressed P-256 point. */
419
+ readonly publicKey: string
420
+ /** The key's id (16 hex): a subscription made for another id is gone after a rotation. */
421
+ readonly keyId: string
422
+ }
423
+
424
+ /** `me/push/subscribe`: the browser's PushSubscription.toJSON() (endpoint and keys) and, optionally, its class. */
425
+ export interface PushSubscribeInput {
426
+ readonly endpoint: string
427
+ readonly keys: { readonly p256dh: string; readonly auth: string }
428
+ readonly userAgentClass?: PushUserAgentClass | null
429
+ }
430
+
431
+ /** `me/push/subscribe`'s answer: the subscription is kept for this key. */
432
+ export interface PushSubscribeAnswer {
433
+ readonly subscribed: true
434
+ readonly keyId: string
435
+ }
436
+
437
+ /** `me/push/unsubscribe`'s answer: whether the member had a subscription of that endpoint (never refused). */
438
+ export interface PushUnsubscribeAnswer {
439
+ readonly unsubscribed: boolean
440
+ }
441
+
442
+ /**
443
+ * `me/push/status { endpoint }` (M2 T10, D-M2-10): whether kb-api holds a subscription of that endpoint (compared in
444
+ * the canonical form `subscribe` stores) for the member viewing — false for another member's, a deleted one (a
445
+ * revoked session, „Odhlásit všude", a dead endpoint) or one kb-api never had. Never the endpoint back.
446
+ */
447
+ export interface PushStatusAnswer {
448
+ readonly subscribed: boolean
449
+ }
450
+
451
+ /**
452
+ * `me/realtime/token` (M2 T5): the connection token for community-rt and the URL to connect to — kb-api's answer is
453
+ * the only source of that URL (a page never builds it from its own configuration).
454
+ */
455
+ export interface RealtimeToken {
456
+ readonly token: string
457
+ /** `https://<instance host>/rt` — the websocket endpoint is `${url}/connection/websocket`. */
458
+ readonly url: string
459
+ readonly expiresInS: number
460
+ }
461
+
462
+ /** `realtime/subscribe-token` (M2 T5): the token of one channel, `disc:<conversationId>`. */
463
+ export interface RealtimeSubscribeToken {
464
+ readonly token: string
465
+ }
466
+
467
+ /** What a discussion's channel carries (M2 T5, m2-contracts.md §3.5): the public projection, by kind. */
468
+ export const REALTIME_EVENT_KINDS = Object.freeze(['message', 'edit', 'delete', 'reaction', 'resync'] as const)
469
+ export type RealtimeEventKind = (typeof REALTIME_EVENT_KINDS)[number]
470
+
471
+ /**
472
+ * One publication of a `disc:` channel. `rev`: message, edit → the message's rev (0 on a placeholder); delete → the
473
+ * row's rev after the delete; reaction → the message's rev (0 for the article's own reactions, no `seq`); resync →
474
+ * the conversation's last seq (re-read the discussion).
475
+ */
476
+ export interface RealtimeEvent {
477
+ readonly kind: RealtimeEventKind | (string & {})
478
+ readonly rev: number
479
+ readonly seq?: number
480
+ readonly message?: PublicMessage
481
+ readonly reactions?: ReactionSummary
482
+ }
483
+
484
+ /** `me/notifications/list`'s filter (M2 T3): only unread ones, only these codes. */
485
+ export interface NotificationListInput {
486
+ readonly cursor?: string | null
487
+ readonly unreadOnly?: boolean
488
+ readonly codes?: readonly string[]
278
489
  }
279
490
 
280
491
  export interface NotificationItem {
281
492
  readonly id: string
282
493
  readonly code: NotificationCode
283
494
  readonly conversationId: string | null
495
+ /** The message the row is about (a `reply`: the reply; a `mention`: the message that mentions), else null. */
284
496
  readonly seq: number | null
497
+ /**
498
+ * M2 T10: the article of the conversation a `reply` or `mention` row is about, else null (absent from a kb-api
499
+ * older than T10). With `articleSlug` and `seq`, a page links the message on the article (communityMessageLink).
500
+ */
501
+ readonly articleId?: string | null
502
+ /** M2 T10: that article's slug (never its title), else null; absent from a kb-api older than T10. */
503
+ readonly articleSlug?: string | null
285
504
  readonly caseId: string | null
286
505
  readonly decisionId: string | null
287
506
  readonly createdAt: string
@@ -368,7 +587,8 @@ export interface CurrentLegalText {
368
587
  readonly body: string
369
588
  /**
370
589
  * The machine-readable form (DSA art. 14(1)); for `rules` `{ version, rules: [{ id, title, summary?, anchor }] }`
371
- * (communityRulesOf), for `terms` and `privacy` `{ sections: [{ id, title, anchor }] }` (communityLegalSectionsOf).
590
+ * (communityRulesOf), for `terms` and `privacy` `{ sections: [{ id, title, anchor }] }` (communityLegalSectionsOf),
591
+ * for `art9_consent` null or `{ controllers: [{ entity, label }] }` with one or two controllers (art9ControllersOf).
372
592
  */
373
593
  readonly bodyJson: Readonly<Record<string, unknown>> | null
374
594
  readonly reconsentRequired: boolean
@@ -398,6 +618,34 @@ export function communityRulesOf(bodyJson: unknown): CommunityRule[] {
398
618
  return out
399
619
  }
400
620
 
621
+ /** One controller an `art9_consent` text names (m2-contracts.md §3.8): its registry ref and the name a reader sees. */
622
+ export interface Art9Controller {
623
+ readonly entity: string
624
+ readonly label: string
625
+ }
626
+
627
+ /** At most this many controllers a consent text names (kb-api refuses a third: BODY_JSON_INVALID). */
628
+ export const ART9_CONTROLLERS_MAX = 2
629
+
630
+ /**
631
+ * The controllers of an `art9_consent` text's `bodyJson` (`{ controllers: [{ entity, label }] }`), in order, at most
632
+ * ART9_CONTROLLERS_MAX; an entry without a non-empty string entity and label is skipped. None (an empty list) for a
633
+ * text without them: the consent is the tenant's alone, as before T9.
634
+ */
635
+ export function art9ControllersOf(bodyJson: unknown): Art9Controller[] {
636
+ const controllers = typeof bodyJson === 'object' && bodyJson !== null ? (bodyJson as { controllers?: unknown }).controllers : undefined
637
+ if (!Array.isArray(controllers)) return []
638
+ const out: Art9Controller[] = []
639
+ for (const c of controllers) {
640
+ if (out.length >= ART9_CONTROLLERS_MAX) break
641
+ if (typeof c !== 'object' || c === null) continue
642
+ const { entity, label } = c as Record<string, unknown>
643
+ if (typeof entity !== 'string' || typeof label !== 'string' || entity.trim() === '' || label.trim() === '') continue
644
+ out.push(Object.freeze({ entity, label: label.trim() }))
645
+ }
646
+ return out
647
+ }
648
+
401
649
  /** One section of a `terms` or `privacy` text: what the page's contents list and link. */
402
650
  export interface CommunityLegalSection {
403
651
  readonly id: string
@@ -510,6 +758,11 @@ export interface OnboardInput {
510
758
  rulesTextId: string
511
759
  /** The current `art9_consent` text's id, when the tenant asks for the consent. */
512
760
  art9TextId?: string | null
761
+ /**
762
+ * M2 T9 (§3.8): the reader refuses the art. 9 consent — only with no `art9TextId`, and only where the tenant's
763
+ * `art9Refusal` is `public_write` (else VALIDATION on `art9Refused`, issue code `art9_refusal_read_only`).
764
+ */
765
+ art9Refused?: boolean
513
766
  /** Required on a member's first onboarding (no profile yet). */
514
767
  displayName?: string | null
515
768
  /** Generated from the display name when absent. */
@@ -9,6 +9,9 @@
9
9
  * applyHead a `discussions/head` answer: true when it is newer than what is loaded (→ refresh);
10
10
  * applyReaction a reaction summary (the server's, or reactionAfter's optimistic one);
11
11
  * collapse a member blocked or unblocked: their messages collapse or open;
12
+ * applyEvent M2 T5: a publication of the discussion's `disc:` channel, by its `rev` (m2-contracts.md §3.5):
13
+ * dropped when it is not newer than what is loaded, applied when it is the next revision, and
14
+ * answered `resync` (re-read: refreshDiscussion) when something between was missed;
12
15
  * viewerNeeds what the composer still waits for.
13
16
  *
14
17
  * Open enums (community.md §3.7): a message whose author kind or state this SDK does not know is dropped — with the
@@ -34,6 +37,7 @@ import {
34
37
  type PublicMessage,
35
38
  type ReactionSummary,
36
39
  type ReactionTarget,
40
+ type RealtimeEvent,
37
41
  } from './shapes'
38
42
 
39
43
  /** A message as the store keeps it: a known author and state, and the optimistic change that waits, if any. */
@@ -117,6 +121,9 @@ export type MessageChange =
117
121
  /** A row from the server outside an optimistic change: replaces the loaded one of its conversation and seq, if any. */
118
122
  | { readonly type: 'server'; readonly message: PublicMessage }
119
123
 
124
+ /** What applyEvent did with a channel's publication: applied, dropped (stale, unknown, nothing loaded), or `resync`. */
125
+ export type RealtimeEventOutcome = 'applied' | 'dropped' | 'resync'
126
+
120
127
  export interface DiscussionStore {
121
128
  getState(): DiscussionState
122
129
  /** Called after every change with the new state; returns the unsubscribe. */
@@ -129,6 +136,18 @@ export interface DiscussionStore {
129
136
  applyReaction(target: ReactionTarget, reactions: ReactionSummary): void
130
137
  /** The viewer blocked (true) or unblocked (false) a member. */
131
138
  collapse(memberId: string, blocked: boolean): void
139
+ /**
140
+ * M2 T5: a publication of the discussion's channel (`@blogmcp/sdk/community/realtime` hands each one over). By kind:
141
+ * `message`/`edit` — dropped when `rev` is not newer than the loaded row's (0 for one not loaded: a placeholder never
142
+ * applies), applied when it is the next one, `resync` when revisions were missed (or a reply's parent is not loaded);
143
+ * `delete` — applied to a loaded row with an older rev; `reaction` — the counts of a loaded row at that very rev (the
144
+ * viewer's own `mine` is kept: the channel never says whose a reaction is); `resync` — always `resync`. A publication
145
+ * is viewer-blind: a row applied keeps the viewer's view — collapsed when its author is blocked (the blocks the pages
146
+ * and collapse() told the store), the loaded row's `mine`, `repliesTruncated` and warnings. While a post of the
147
+ * viewer waits for its answer, every new row of the viewer's own is dropped (the answer shows that post; a post
148
+ * from another tab of theirs in that window comes with the next re-read).
149
+ */
150
+ applyEvent(event: RealtimeEvent): RealtimeEventOutcome
132
151
  /** Back to the empty state (another article); the answers still on their way are dropped when they come. */
133
152
  reset(): void
134
153
  }
@@ -321,6 +340,10 @@ const keepsPlaceholder = (m: DiscussionMessage): boolean => m.replyToSeq === nul
321
340
  /** kb-api answers ids in lower case; a host may pass them in upper case. */
322
341
  const sameId = (a: string, b: string): boolean => a.toLowerCase() === b.toLowerCase()
323
342
 
343
+ /** A member author's id (lower case), the key of the viewer's blocks; null for the team, the system and the deleted. */
344
+ const authorKey = (m: Pick<DiscussionMessage, 'author'>): string | null =>
345
+ m.author.kind === 'member' && m.author.memberId !== null ? m.author.memberId.toLowerCase() : null
346
+
324
347
  // ───────────────────────── the store ─────────────────────────
325
348
 
326
349
  interface PendingChange {
@@ -346,10 +369,17 @@ export function createDiscussionStore(): DiscussionStore {
346
369
  const retired = new Set<string>()
347
370
  let generation = 0
348
371
  let nextPendingSeq = -1
372
+ /**
373
+ * The members the viewer has blocked, as far as this store knows: from the pages (a `collapsed` row) and from
374
+ * collapse(). A channel's publication is viewer-blind (`collapsed` false, `mine` null): applyEvent restores the
375
+ * viewer's view of it from here and from the loaded row.
376
+ */
377
+ const blockedAuthors = new Set<string>()
349
378
 
350
379
  /** Another discussion from here on: the changes that wait are dropped, and their answers with them. */
351
380
  const nextGeneration = (): void => {
352
381
  generation += 1
382
+ blockedAuthors.clear()
353
383
  for (const id of pending.keys()) {
354
384
  retired.delete(id)
355
385
  retired.add(id)
@@ -390,6 +420,15 @@ export function createDiscussionStore(): DiscussionStore {
390
420
  const m = messageOf(raw, true)
391
421
  if (m && m.seq > lo && m.seq <= hi) incoming.set(m.seq, m)
392
422
  }
423
+ // What the page says of the viewer's blocks (a row with a body is collapsed exactly when its author is blocked).
424
+ for (const m of incoming.values()) {
425
+ for (const x of [m, ...m.replies]) {
426
+ const author = authorKey(x)
427
+ if (author === null || x.body === null) continue
428
+ if (x.collapsed) blockedAuthors.add(author)
429
+ else blockedAuthors.delete(author)
430
+ }
431
+ }
393
432
  // An optimistic edit or delete stays over the server's row until it settles; its undo becomes that row.
394
433
  const pendingRows = new Map<number, DiscussionMessage>()
395
434
  for (const m of base.messages) {
@@ -612,6 +651,8 @@ export function createDiscussionStore(): DiscussionStore {
612
651
  function collapse(memberId: string, blocked: boolean): void {
613
652
  if (typeof memberId !== 'string' || memberId === '') return
614
653
  const id = memberId.toLowerCase()
654
+ if (blocked) blockedAuthors.add(id)
655
+ else blockedAuthors.delete(id)
615
656
  const messages = mapAll(state.messages, (m) =>
616
657
  m.author.kind === 'member' && m.author.memberId !== null && m.author.memberId.toLowerCase() === id && m.body !== null && m.collapsed !== blocked
617
658
  ? Object.freeze({ ...m, collapsed: blocked })
@@ -620,6 +661,78 @@ export function createDiscussionStore(): DiscussionStore {
620
661
  if (messages !== state.messages) set({ ...state, messages })
621
662
  }
622
663
 
664
+ /**
665
+ * A channel's row as this viewer sees it: collapsed when its author is blocked, the viewer's own reaction (`mine`)
666
+ * and a top-level row's `repliesTruncated` (and the write's warnings) kept from the loaded row it replaces.
667
+ */
668
+ function asViewerSees(row: DiscussionMessage, loaded: DiscussionMessage | null): DiscussionMessage {
669
+ const author = authorKey(row)
670
+ const collapsed = row.body !== null && author !== null && blockedAuthors.has(author)
671
+ const mine = loaded ? loaded.reactions.mine : null
672
+ const reactions = mine === row.reactions.mine ? row.reactions : Object.freeze({ counts: row.reactions.counts, mine })
673
+ const truncated = loaded?.repliesTruncated === true && row.replyToSeq === null
674
+ const warnings = loaded?.warnings
675
+ if (collapsed === row.collapsed && reactions === row.reactions && !truncated && !warnings) return row
676
+ return Object.freeze({
677
+ ...row,
678
+ collapsed,
679
+ reactions,
680
+ ...(truncated ? { repliesTruncated: true } : {}),
681
+ ...(warnings ? { warnings } : {}),
682
+ })
683
+ }
684
+
685
+ function applyEvent(event: RealtimeEvent): RealtimeEventOutcome {
686
+ if (!isRecord(event) || !state.loaded) return 'dropped'
687
+ const rev = typeof event.rev === 'number' && Number.isSafeInteger(event.rev) && event.rev >= 0 ? event.rev : null
688
+ if (event.kind === 'resync') return 'resync'
689
+ if (rev === null) return 'dropped'
690
+ if (event.kind === 'reaction') {
691
+ if (event.seq === undefined) {
692
+ const summary = reactionsOf(event.reactions)
693
+ set({ ...state, articleReactions: Object.freeze({ counts: summary.counts, mine: state.articleReactions.mine }) })
694
+ return 'applied'
695
+ }
696
+ if (!isSeq(event.seq)) return 'dropped'
697
+ const seq = event.seq
698
+ const m = findIn(state.messages, (x) => x.seq === seq)
699
+ if (!m || m.pending) return 'dropped'
700
+ if (rev < m.rev) return 'dropped'
701
+ if (rev > m.rev) return 'resync'
702
+ const summary = reactionsOf(event.reactions)
703
+ const reactions = Object.freeze({ counts: summary.counts, mine: m.reactions.mine })
704
+ set({ ...state, messages: mapAll(state.messages, (x) => (x === m ? Object.freeze({ ...x, reactions }) : x)) })
705
+ return 'applied'
706
+ }
707
+ if (event.kind !== 'message' && event.kind !== 'edit' && event.kind !== 'delete') return 'dropped'
708
+ const raw = event.message
709
+ const row = messageOf(raw, raw?.replyToSeq === null || raw?.replyToSeq === undefined)
710
+ if (!row || !ofThisConversation(row)) return 'dropped'
711
+ const loaded = findIn(state.messages, (x) => x.seq === row.seq)
712
+ if (loaded?.pending) return 'dropped'
713
+ const known = loaded?.rev ?? 0
714
+ if (event.kind === 'delete') {
715
+ if (!loaded || rev <= known) return 'dropped'
716
+ const wasVisible = loaded.state === 'visible' && loaded.body !== null
717
+ const messages = mapAll(state.messages, (x) =>
718
+ x.seq !== row.seq ? x : keepsPlaceholder(x) ? Object.freeze({ ...row, replies: x.replies }) : null,
719
+ )
720
+ set({ ...state, messages, count: wasVisible ? Math.max(0, state.count - 1) : state.count, lastSeq: Math.max(state.lastSeq, row.seq) })
721
+ return 'applied'
722
+ }
723
+ // The viewer's own new post while one waits for its answer: the answer (confirm) shows it.
724
+ const own = row.author.kind === 'member' && row.author.memberId !== null && row.author.memberId === state.viewer.memberId
725
+ if (!loaded && own && [...pending.values()].some((p) => p.type === 'post')) return 'dropped'
726
+ if (rev <= known) return 'dropped'
727
+ if (rev > known + 1) return 'resync'
728
+ if (!loaded && row.replyToSeq !== null && !state.messages.some((x) => x.seq === row.replyToSeq)) return 'resync'
729
+ const viewed = asViewerSees(row, loaded)
730
+ const messages = loaded ? replaceBySeq(state.messages, viewed) : upsert(state.messages, viewed)
731
+ const count = !loaded && row.state === 'visible' ? state.count + 1 : state.count
732
+ set({ ...state, messages, count, lastSeq: Math.max(state.lastSeq, row.seq) })
733
+ return 'applied'
734
+ }
735
+
623
736
  const store: DiscussionStore = {
624
737
  getState: () => state,
625
738
  subscribe(listener) {
@@ -633,6 +746,7 @@ export function createDiscussionStore(): DiscussionStore {
633
746
  applyHead,
634
747
  applyReaction,
635
748
  collapse,
749
+ applyEvent,
636
750
  reset() {
637
751
  nextGeneration()
638
752
  set(EMPTY)