@blogmcp/sdk 0.10.1 → 0.11.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.
Files changed (53) hide show
  1. package/dist/community/channels.d.ts +3 -2
  2. package/dist/community/client.d.ts +129 -2
  3. package/dist/community/client.js +231 -161
  4. package/dist/community/forum.d.ts +82 -0
  5. package/dist/community/forum.js +96 -0
  6. package/dist/community/index.d.ts +14 -7
  7. package/dist/community/index.js +185 -121
  8. package/dist/community/links.d.ts +38 -0
  9. package/dist/community/links.js +98 -71
  10. package/dist/community/messages.cs.d.ts +160 -1
  11. package/dist/community/messages.cs.js +178 -1
  12. package/dist/community/messages.d.ts +19 -1
  13. package/dist/community/messages.en.d.ts +150 -1
  14. package/dist/community/messages.en.js +161 -1
  15. package/dist/community/messages.js +37 -28
  16. package/dist/community/outcome.d.ts +8 -3
  17. package/dist/community/outcome.js +61 -20
  18. package/dist/community/poll.d.ts +28 -4
  19. package/dist/community/poll.js +70 -47
  20. package/dist/community/realtime/index.d.ts +19 -3
  21. package/dist/community/realtime/index.js +175 -145
  22. package/dist/community/routes.d.ts +36 -1
  23. package/dist/community/routes.js +51 -21
  24. package/dist/community/server/bff.d.ts +25 -2
  25. package/dist/community/server/bff.js +135 -118
  26. package/dist/community/server/host-routes.d.ts +3 -0
  27. package/dist/community/server/host-routes.js +17 -0
  28. package/dist/community/server/index.d.ts +5 -1
  29. package/dist/community/shapes.d.ts +634 -7
  30. package/dist/community/shapes.js +92 -61
  31. package/dist/community/store.d.ts +15 -0
  32. package/dist/community/store.js +65 -61
  33. package/dist/community/topic.d.ts +173 -0
  34. package/dist/community/topic.js +225 -0
  35. package/package.json +3 -3
  36. package/src/community/channels.ts +3 -2
  37. package/src/community/client.ts +209 -5
  38. package/src/community/forum.ts +209 -0
  39. package/src/community/index.ts +146 -2
  40. package/src/community/links.ts +64 -4
  41. package/src/community/messages.cs.ts +179 -1
  42. package/src/community/messages.en.ts +162 -1
  43. package/src/community/messages.ts +25 -2
  44. package/src/community/outcome.ts +47 -1
  45. package/src/community/poll.ts +79 -17
  46. package/src/community/realtime/index.ts +124 -48
  47. package/src/community/routes.ts +42 -1
  48. package/src/community/server/bff.ts +89 -30
  49. package/src/community/server/host-routes.ts +20 -0
  50. package/src/community/server/index.ts +5 -1
  51. package/src/community/shapes.ts +662 -6
  52. package/src/community/store.ts +11 -5
  53. package/src/community/topic.ts +521 -0
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * The community's public client (docs/internal/m1-contracts.md §10.2): one method per operation of kb-api's public
3
3
  * API and notice form (§7.4, §7.7, §8.3), each a POST of a JSON body through the host — never to kb-api itself.
4
+ * M3 (m3-contracts.md §3.2–§3.4, §5.2): the forum (`forum.*`), the member's follows (`me.follows.*`) and a category
5
+ * moderator's operations (`moderation.*`) — the public router's, through the same host routes.
4
6
  *
5
7
  * const community = createCommunityClient({ base: '/api/community' })
6
8
  * const page = await community.discussions.list({ articleId, languageCode: 'cs' })
@@ -29,6 +31,31 @@ import {
29
31
  isKnownNeed,
30
32
  type AppealItem,
31
33
  type BlockEntry,
34
+ type BrakeSurface,
35
+ type FollowSetInput,
36
+ type FollowsPage,
37
+ type ForumCategory,
38
+ type ForumSearchInput,
39
+ type ForumTopicCreateInput,
40
+ type ForumTopicGetInput,
41
+ type ForumTopicsListInput,
42
+ type ForumTopicsPage,
43
+ type ModerationCase,
44
+ type ModerationDecideAnswer,
45
+ type ModerationDecideInput,
46
+ type ModerationEscalateInput,
47
+ type ModerationQueueInput,
48
+ type ModerationQueuePage,
49
+ type ModerationRemovalAnswer,
50
+ type ModerationRemoveInput,
51
+ type ModeratorTopicState,
52
+ type PremodReviewAnswer,
53
+ type PremodReviewInput,
54
+ type ForumSearchPage,
55
+ type Topic,
56
+ type TopicCreateAnswer,
57
+ type TopicHead,
58
+ type TopicThread,
32
59
  type CommunityPage,
33
60
  type CurrentLegalText,
34
61
  type DecisionSummary,
@@ -105,8 +132,21 @@ export interface CommunityClient {
105
132
  /** The polling signal of up to COMMUNITY_HEAD_ARTICLES_MAX articles (pollDiscussionHead). */
106
133
  head: Call<{ articleIds: readonly string[] }, { heads: DiscussionHead[] }>
107
134
  }
135
+ /**
136
+ * M3 (m3-contracts.md §3.1, A11): an operation addressed by a topic's conversation id — `messages.post { conversationId }`,
137
+ * `messages.edit|delete|report`, `reactions.set` of a topic's message — answers every refusal of the forum's gate (the
138
+ * forum switched off, the module dark, a viewer the forum is not open to, a topic the viewer may not see) as the one
139
+ * `notFound` an unknown id gets: re-read the topic (`forum.topics.get`, settleTopicFailure), which answers the
140
+ * surface's own code. An article discussion's `notFound` on `messages.post { articleId }` also covers a
141
+ * discussion-free article (D-M3-17).
142
+ */
108
143
  messages: {
144
+ /** Under an article (`articleId`) or, M3, into a forum topic (`conversationId`): exactly one of them. */
109
145
  post: Call<MessagePostInput, WriteAnswer>
146
+ /**
147
+ * M3: `title` on a topic's opening post (seq 1) by its author (≤ COMMUNITY_TOPIC_TITLE_MAX UTF-16 units: check with
148
+ * forumTopicTitleOf); the answer then carries the `topic` — apply it (TopicStore.applyTopic).
149
+ */
110
150
  edit: Call<MessageEditInput, WriteAnswer>
111
151
  /** The member's own message becomes a tombstone (a placeholder only while it has visible replies). */
112
152
  delete: Call<{ conversationId: string; seq: number }, { message: PublicMessage }>
@@ -192,6 +232,18 @@ export interface CommunityClient {
192
232
  /** As easy as giving it; later writes ask for it again where the tenant requires it. */
193
233
  withdraw: CallOptionalInput<{ kind: 'art9_consent' }, { kind: 'art9_consent'; state: string }>
194
234
  }
235
+ /**
236
+ * M3 (m3-contracts.md §3.2–§3.3, §4.3): what the member follows — a topic or an article discussion by its
237
+ * conversation id, or a category. A follow is no content: never braked or refused read-only; FOLLOW_LIMIT
238
+ * (`followLimit`) above COMMUNITY_FOLLOWS_MAX. Build the target with followTargetOf. `set { following: true }` is
239
+ * `notFound` for a target the member may not read now (say „not available"); `set { following: false }` never
240
+ * fails on its target (B16).
241
+ */
242
+ follows: {
243
+ set: Call<FollowSetInput, { following: boolean }>
244
+ /** Newest first; `title` as the member may see it now (null when they cannot). */
245
+ list: CallOptionalInput<{ cursor?: string | null }, FollowsPage>
246
+ }
195
247
  /** Every section of the member's data, `providerEntity` on every row: offer it as a JSON download. */
196
248
  export: CallNoInput<MemberExport>
197
249
  /** The profile's deletion, after the grace period (`purgeAfter`); writes are refused meanwhile. */
@@ -201,10 +253,76 @@ export interface CommunityClient {
201
253
  legal: {
202
254
  current: Call<{ kind: LegalTextKind; locale: string }, CurrentLegalText>
203
255
  }
204
- /** M2 T5: a channel's token — `disc:<conversationId>` of a discussion the viewer may read, else `notFound`. */
256
+ /**
257
+ * M2 T5: a channel's token — `disc:<conversationId>` of a discussion the viewer may read, else `notFound`. M3: a
258
+ * topic's channel only for an onboarded member who may read the topic (a visitor's host session: `notFound`; the team
259
+ * and an internal key: `signIn` — they poll `forum.topics.head`, §3.5). A change of a topic's header (a title edit,
260
+ * a lock, a move, a pin) arrives as a `resync` publication: re-read the topic.
261
+ */
205
262
  realtime: {
206
263
  subscribeToken: Call<{ channel: string }, RealtimeSubscribeToken>
207
264
  }
265
+ /**
266
+ * M3 (m3-contracts.md §3.1–§3.3): the forum — read by an onboarded member or an interactive team session only;
267
+ * anyone else is `membersOnly` (with `needs` for a member session short of its onboarding). The forum is
268
+ * switched off (`surfaceOff`) or the module is dark (`unavailable`) before anything else is looked at; a hidden
269
+ * category, a topic of one or an unknown id is `notFound`.
270
+ */
271
+ forum: {
272
+ categories: {
273
+ /** The listed categories, in their order; the team's hidden ones never reach a member. */
274
+ list: CallNoInput<{ categories: ForumCategory[] }>
275
+ }
276
+ topics: {
277
+ /** A category's topics (by `categoryId` or `categorySlug`): pinned first under `activity`, archived last. */
278
+ list: Call<ForumTopicsListInput, ForumTopicsPage>
279
+ /** One page of a topic, as `discussions.list` pages a discussion (createTopicStore keeps it). */
280
+ get: Call<ForumTopicGetInput, TopicThread>
281
+ /** The polling signal of up to COMMUNITY_HEAD_TOPICS_MAX topics (pollTopicHead); ids the viewer may not see are left out. */
282
+ head: Call<{ conversationIds: readonly string[] }, { heads: TopicHead[] }>
283
+ /**
284
+ * A new topic: its title and opening post, filtered as one text; `topicCreationClosed` where members open none.
285
+ * The same `clientMsgId` again answers the topic it created. Under pre-moderation (the category's, or away mode)
286
+ * the opening post waits for review: `message.state` is `held` with `premoderated`.
287
+ */
288
+ create: Call<ForumTopicCreateInput, TopicCreateAnswer>
289
+ }
290
+ /** Titles and visible messages of topics and article discussions (forumSearchQueryOf; pages 1..5, a quota per call). */
291
+ search: Call<ForumSearchInput, ForumSearchPage>
292
+ }
293
+ /**
294
+ * M3 (m3-contracts.md §3.4, §4.5): a category moderator's operations — a member session with an active appointment
295
+ * (MyState `moderator`). Anyone else, a category the member does not moderate, a case outside the rules line or of
296
+ * the moderator's own message: `notFound`, the same answer for each. Never refused by `read_only` or a brake.
297
+ */
298
+ moderation: {
299
+ /**
300
+ * The cases of category `rules` of the moderator's categories (or of `categoryId`) — open ones, and decided ones a
301
+ * `system` decision still holds (`caseStatus`) — and their pre-moderation items.
302
+ */
303
+ queue: CallOptionalInput<ModerationQueueInput, ModerationQueuePage>
304
+ /** A case's package, as written: no reporter, no reporter's note, no notifier contact. */
305
+ getCase: Call<{ caseId: string }, { case: ModerationCase }>
306
+ /**
307
+ * A decision through the engine, with its statement of reasons (it names the provider, and that a category
308
+ * moderator decided on its behalf — never the moderator's handle). `dryRun: true` renders the statement and writes
309
+ * nothing: show it, then decide for real. A restriction needs a contractual ground: without `contractualGround` on a
310
+ * case without a rule id it is `invalid` with `fields: ['contractualGround']` (ask for the rule).
311
+ */
312
+ decide: Call<ModerationDecideInput, ModerationDecideAnswer>
313
+ /** An own-initiative removal on the rules line (a case and a `removal` decision with its statement). */
314
+ remove: Call<ModerationRemoveInput, ModerationRemovalAnswer>
315
+ /** An illegal-line matter goes to the team (opens or joins a case); the moderator sees nothing of it afterwards. */
316
+ escalate: Call<ModerationEscalateInput, Record<string, never>>
317
+ /** Lock or reopen a topic (archiving is the team's). */
318
+ setTopicState: Call<{ conversationId: string; state: ModeratorTopicState }, { topic: Topic }>
319
+ /** Into another category the member moderates; its pre-moderation items follow. */
320
+ moveTopic: Call<{ conversationId: string; categoryId: string }, { topic: Topic }>
321
+ /** Pin or unpin; refused (`submit`, BRAND_RESTRICTED) under a preset without brand reactions. */
322
+ pinTopic: Call<{ conversationId: string; pinned: boolean }, { topic: Topic }>
323
+ /** Publish a message waiting for review (no statement), or refuse it (`ruleId` and `facts`: a removal with one). */
324
+ reviewPremod: Call<PremodReviewInput, PremodReviewAnswer>
325
+ }
208
326
  notices: {
209
327
  /** Anyone, with or without a session; `confirmations` must hold COMMUNITY_GOOD_FAITH. */
210
328
  submit: Call<NoticeSubmitInput, NoticeReceipt>
@@ -302,10 +420,45 @@ export const COMMUNITY_ANSWER_FIELDS: Readonly<Record<CommunityOpName, Readonly<
302
420
  'notices.status': fieldsOfAnswer({ status: 'string' }),
303
421
  'notices.appeal': fieldsOfAnswer({ appealId: 'string' }),
304
422
  'notices.withdrawAppeal': fieldsOfAnswer({ appealId: 'string' }),
423
+ // M3 (m3-contracts.md §3.2–§3.4).
424
+ 'forum.categories.list': fieldsOfAnswer({ categories: 'array' }),
425
+ 'forum.topics.list': fieldsOfAnswer({ category: 'record', items: 'array' }),
426
+ 'forum.topics.get': fieldsOfAnswer({ topic: 'record', messages: 'array', viewer: 'record' }),
427
+ 'forum.topics.head': fieldsOfAnswer({ heads: 'array' }),
428
+ 'forum.topics.create': fieldsOfAnswer({ topic: 'record', message: 'record', warnings: 'array' }),
429
+ 'forum.search': fieldsOfAnswer({ results: 'array', page: 'number', hasMore: 'boolean' }),
430
+ 'me.follows.set': fieldsOfAnswer({ following: 'boolean' }),
431
+ 'me.follows.list': fieldsOfAnswer({ follows: 'array' }),
432
+ 'moderation.queue': fieldsOfAnswer({ items: 'array' }),
433
+ 'moderation.getCase': fieldsOfAnswer({ case: 'record' }),
434
+ 'moderation.decide': fieldsOfAnswer({ dryRun: 'boolean', statement: 'string' }),
435
+ 'moderation.remove': fieldsOfAnswer({ decision: 'record', statement: 'string' }),
436
+ // The bare envelope `{ ok: true }` (§3.4): the moderator learns nothing of the case it opened or joined.
437
+ 'moderation.escalate': fieldsOfAnswer({}),
438
+ 'moderation.setTopicState': fieldsOfAnswer({ topic: 'record' }),
439
+ 'moderation.moveTopic': fieldsOfAnswer({ topic: 'record' }),
440
+ 'moderation.pinTopic': fieldsOfAnswer({ topic: 'record' }),
441
+ // A union: COMMUNITY_ANSWER_VARIANTS says which shapes count.
442
+ 'moderation.reviewPremod': fieldsOfAnswer({}),
443
+ })
444
+
445
+ /**
446
+ * The operations whose answer is one of several shapes (a union kb-api declares): besides its COMMUNITY_ANSWER_FIELDS,
447
+ * an answer must hold every field of at least one variant (else `unavailable`, as for a missing field).
448
+ */
449
+ export const COMMUNITY_ANSWER_VARIANTS: Readonly<Partial<Record<CommunityOpName, readonly Readonly<Record<string, CommunityAnswerField>>[]>>> = Object.freeze({
450
+ // approve → the published message; reject → the removal and its statement (§3.4, §4.2).
451
+ 'moderation.reviewPremod': Object.freeze([fieldsOfAnswer({ message: 'record' }), fieldsOfAnswer({ decision: 'record', statement: 'string' })]),
305
452
  })
306
453
 
307
- const isAnswerOf = (name: CommunityOpName, v: Rec): boolean =>
308
- Object.entries(COMMUNITY_ANSWER_FIELDS[name]).every(([field, kind]) => IS_FIELD[kind](v[field]))
454
+ const holds = (fields: Readonly<Record<string, CommunityAnswerField>>, v: Rec): boolean =>
455
+ Object.entries(fields).every(([field, kind]) => IS_FIELD[kind](v[field]))
456
+
457
+ const isAnswerOf = (name: CommunityOpName, v: Rec): boolean => {
458
+ if (!holds(COMMUNITY_ANSWER_FIELDS[name], v)) return false
459
+ const variants = COMMUNITY_ANSWER_VARIANTS[name]
460
+ return variants === undefined || variants.some((fields) => holds(fields, v))
461
+ }
309
462
 
310
463
  /** The fields of `input` the operation takes; an `undefined` one is left out (kb-api's schemas are strict). */
311
464
  function pick(input: unknown, keys: readonly string[]): Rec {
@@ -350,6 +503,20 @@ function issueCodesOf(value: unknown): string[] | undefined {
350
503
  return codes.length > 0 ? [...new Set(codes)].slice(0, MAX_LIST) : undefined
351
504
  }
352
505
 
506
+ /** A surface's name as kb-api spells one (`forum`, `article_discussions`; an open set). */
507
+ const SURFACE_RE = /^[a-z][a-z0-9_]{0,63}$/
508
+
509
+ function surfaceOf(value: unknown): BrakeSurface | undefined {
510
+ return isString(value) && SURFACE_RE.test(value) ? value : undefined
511
+ }
512
+
513
+ /** M3: a follow's target, by the field that names it — a conversation (a topic, an article discussion) or a category. */
514
+ function followTargetBody(target: unknown): unknown {
515
+ if (!isRecord(target)) return target
516
+ if ('conversationId' in target) return pick(target, ['conversationId'])
517
+ return pick(target, ['categoryId'])
518
+ }
519
+
353
520
  function secondsOf(value: unknown): number | undefined {
354
521
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.ceil(value) : undefined
355
522
  }
@@ -364,6 +531,8 @@ function refusalOf(body: Rec, answer: CommunityTransportAnswer): CommunityFailur
364
531
  const codes = codesOf(body.codes)
365
532
  if (codes) out.codes = codes
366
533
  if (isString(body.until)) out.until = body.until
534
+ const surface = surfaceOf(body.surface)
535
+ if (surface !== undefined) out.surface = surface
367
536
  const fields = fieldsOf(body.issues)
368
537
  if (fields) out.fields = fields
369
538
  const issueCodes = issueCodesOf(body.issues)
@@ -451,8 +620,9 @@ export function createCommunityClient(config: CommunityClientConfig): CommunityC
451
620
  call('discussions.head', { articleIds: isRecord(input) && isArray(input.articleIds) ? [...input.articleIds] : [] }, options),
452
621
  },
453
622
  messages: {
454
- post: fields('messages.post', ['articleId', 'body', 'replyToSeq', 'clientMsgId', 'languageCode', 'confirmations']),
455
- edit: fields('messages.edit', ['conversationId', 'seq', 'body', 'confirmations']),
623
+ // M3: `conversationId` (a topic) in place of `articleId`; the caller's type allows exactly one, and both are sent as given.
624
+ post: fields('messages.post', ['articleId', 'conversationId', 'body', 'replyToSeq', 'clientMsgId', 'languageCode', 'confirmations']),
625
+ edit: fields('messages.edit', ['conversationId', 'seq', 'body', 'title', 'confirmations']),
456
626
  delete: fields('messages.delete', ['conversationId', 'seq']),
457
627
  report: fields('messages.report', ['conversationId', 'seq', 'category', 'ruleId', 'note']),
458
628
  },
@@ -522,6 +692,14 @@ export function createCommunityClient(config: CommunityClientConfig): CommunityC
522
692
  consents: {
523
693
  withdraw: (_input, options) => call('me.consents.withdraw', { kind: 'art9_consent' }, options),
524
694
  },
695
+ follows: {
696
+ set: (input, options) => {
697
+ const body = pick(input, ['target', 'following'])
698
+ if (body.target !== undefined) body.target = followTargetBody(body.target)
699
+ return call('me.follows.set', body, options)
700
+ },
701
+ list: fields('me.follows.list', ['cursor']),
702
+ },
525
703
  export: empty('me.export'),
526
704
  erase: empty('me.erase'),
527
705
  cancelErase: empty('me.cancelErase'),
@@ -532,6 +710,32 @@ export function createCommunityClient(config: CommunityClientConfig): CommunityC
532
710
  realtime: {
533
711
  subscribeToken: fields('realtime.subscribeToken', ['channel']),
534
712
  },
713
+ forum: {
714
+ categories: {
715
+ list: empty('forum.categories.list'),
716
+ },
717
+ topics: {
718
+ // A category by its id or its slug: the caller's type allows exactly one, and what is given is sent.
719
+ list: fields('forum.topics.list', ['categoryId', 'categorySlug', 'sort', 'cursor', 'limit']),
720
+ get: fields('forum.topics.get', ['conversationId', 'languageCode', 'cursor']),
721
+ head: (input, options) =>
722
+ call('forum.topics.head', { conversationIds: isRecord(input) && isArray(input.conversationIds) ? [...input.conversationIds] : [] }, options),
723
+ create: fields('forum.topics.create', ['categoryId', 'title', 'body', 'clientMsgId', 'languageCode', 'confirmations']),
724
+ },
725
+ search: fields('forum.search', ['query', 'categoryId', 'space', 'page']),
726
+ },
727
+ moderation: {
728
+ queue: fields('moderation.queue', ['categoryId', 'cursor']),
729
+ getCase: fields('moderation.getCase', ['caseId']),
730
+ decide: fields('moderation.decide', ['caseId', 'restriction', 'basis', 'facts', 'contractualGround', 'locale', 'dryRun']),
731
+ remove: fields('moderation.remove', ['conversationId', 'seq', 'ruleId', 'facts', 'locale']),
732
+ escalate: fields('moderation.escalate', ['conversationId', 'seq', 'category']),
733
+ setTopicState: fields('moderation.setTopicState', ['conversationId', 'state']),
734
+ moveTopic: fields('moderation.moveTopic', ['conversationId', 'categoryId']),
735
+ pinTopic: fields('moderation.pinTopic', ['conversationId', 'pinned']),
736
+ // M3 FX (R3): the rev of the text the moderator read.
737
+ reviewPremod: fields('moderation.reviewPremod', ['conversationId', 'seq', 'rev', 'outcome', 'ruleId', 'facts', 'locale']),
738
+ },
535
739
  notices: {
536
740
  submit: (input, options) => {
537
741
  const body = pick(input, ['category', 'target', 'description', 'ruleId', 'turnstileToken', 'confirmations'])
@@ -0,0 +1,209 @@
1
+ /**
2
+ * The forum's helpers (m3-contracts.md §3.2–§3.5, §4.3, §4.4, §4.8, §4.9, §5.2): what a page builds before it asks
3
+ * kb-api, and what it reads out of an answer — pure functions, no I/O.
4
+ *
5
+ * followTargetOf / followKeyOf `me/follows/set`'s target from a kind and an id (the follow button's attributes);
6
+ * forumTopicTitleOf a topic's title as kb-api takes it (1..200 UTF-16 units, as its schema counts);
7
+ * forumSearchQueryOf / nextSearchPage a query kb-api takes (2..200 characters) and the next of the 5 pages;
8
+ * knownTopicItemsOf a category's rows of the kinds this SDK renders (open enum: the rest is skipped);
9
+ * surfaceInfoOf / communityAwayOf MyState's surfaces and away mode, with an older kb-api's absence handled;
10
+ * isCategoryModerator whether the viewer moderates a category now (MyState `moderator`);
11
+ * brakedSurfaceOf which surface a BRAKED refusal paused (null: the module's brake, both).
12
+ */
13
+
14
+ import type { CommunityFailure } from './outcome'
15
+ import {
16
+ COMMUNITY_SEARCH_PAGES_MAX,
17
+ COMMUNITY_SEARCH_QUERY_MAX,
18
+ COMMUNITY_SEARCH_QUERY_MIN,
19
+ COMMUNITY_TOPIC_TITLE_MAX,
20
+ } from './routes'
21
+ import {
22
+ isKnownBrakeSurface,
23
+ type CommunityAway,
24
+ type FollowTarget,
25
+ type KnownBrakeSurface,
26
+ type KnownFollowTargetKind,
27
+ type KnownTopicItem,
28
+ type ForumSearchPage,
29
+ type ModuleInfo,
30
+ type MyState,
31
+ type SurfaceInfo,
32
+ type TopicItem,
33
+ } from './shapes'
34
+
35
+ type Rec = Record<string, unknown>
36
+ const isRecord = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v)
37
+
38
+ /** kb-api's ids (UUIDs). */
39
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
40
+
41
+ // ───────────────────────── following (§3.3, §4.3) ─────────────────────────
42
+
43
+ /**
44
+ * `me/follows/set`'s target from a kind and an id — a follow button's `target-kind` and `target-id`: `conversation` (a
45
+ * topic, or an article discussion that has its conversation: the button appears once it has one) or `category`. Null
46
+ * for any other kind or for an id that is no UUID — no request is built from arbitrary text. The id goes lower case.
47
+ */
48
+ export function followTargetOf(kind: unknown, id: unknown): FollowTarget | null {
49
+ if (typeof id !== 'string' || !UUID_RE.test(id)) return null
50
+ const lower = id.toLowerCase()
51
+ if (kind === 'conversation') return Object.freeze({ conversationId: lower })
52
+ if (kind === 'category') return Object.freeze({ categoryId: lower })
53
+ return null
54
+ }
55
+
56
+ /** A follow target's kind and id (the target `me/follows/list` names back as `targetKind` / `targetId`), or null. */
57
+ export function followTargetParts(target: unknown): { readonly kind: KnownFollowTargetKind; readonly id: string } | null {
58
+ if (!isRecord(target)) return null
59
+ const { conversationId, categoryId } = target
60
+ if (typeof conversationId === 'string' && categoryId === undefined && UUID_RE.test(conversationId)) {
61
+ return Object.freeze({ kind: 'conversation', id: conversationId.toLowerCase() })
62
+ }
63
+ if (typeof categoryId === 'string' && conversationId === undefined && UUID_RE.test(categoryId)) {
64
+ return Object.freeze({ kind: 'category', id: categoryId.toLowerCase() })
65
+ }
66
+ return null
67
+ }
68
+
69
+ /**
70
+ * One key per followed thing (`conversation:<id>`, `category:<id>`, lower case) — for a page's map of what the member
71
+ * follows, built from a FollowTarget or from a `me/follows/list` row (`targetKind`, `targetId`). Null for neither.
72
+ */
73
+ export function followKeyOf(target: FollowTarget | { readonly targetKind: unknown; readonly targetId: unknown } | null | undefined): string | null {
74
+ if (!isRecord(target)) return null
75
+ if ('targetKind' in target) {
76
+ const parts = followTargetOf(target.targetKind, target.targetId)
77
+ return parts === null ? null : followKeyOf(parts)
78
+ }
79
+ const parts = followTargetParts(target)
80
+ return parts === null ? null : `${parts.kind}:${parts.id}`
81
+ }
82
+
83
+ // ───────────────────────── a topic's title (§2.1, §3.3, A20) ─────────────────────────
84
+
85
+ /** A title as it is sent: trimmed, every run of blanks (a line break too) one space. */
86
+ const foldTitle = (raw: string): string => raw.replace(/\s+/gu, ' ').trim()
87
+
88
+ /**
89
+ * The length of a title as kb-api counts it — both of its bounds, the larger: the UTF-16 units of the title as it is sent
90
+ * (forumTopicTitleOf; zod's `.max(200)`) and its characters as it is stored, NFC'd (the database's `char_length`). NFC
91
+ * may lengthen a text — U+0958 is one unit and two characters stored —, and kb-api refuses a title past either bound
92
+ * (M3 FX, the review of wave 1, R15), so a title this accepts is one kb-api accepts. For a composer's counter (an emoji
93
+ * outside the basic plane counts two).
94
+ */
95
+ export function topicTitleLength(raw: unknown): number {
96
+ if (typeof raw !== 'string') return 0
97
+ const title = foldTitle(raw)
98
+ return Math.max(title.length, [...title.normalize('NFC')].length)
99
+ }
100
+
101
+ /**
102
+ * A topic's title as kb-api takes it (`forum/topics/create`, `messages/edit { title }`): trimmed and on one line, 1 to
103
+ * COMMUNITY_TOPIC_TITLE_MAX as topicTitleLength counts — or null for anything else, so the page says so instead of asking
104
+ * (kb-api would answer `invalid` with `fields: ['title']`).
105
+ */
106
+ export function forumTopicTitleOf(raw: unknown): string | null {
107
+ if (typeof raw !== 'string') return null
108
+ const title = foldTitle(raw)
109
+ const length = topicTitleLength(title)
110
+ return length >= 1 && length <= COMMUNITY_TOPIC_TITLE_MAX ? title : null
111
+ }
112
+
113
+ // ───────────────────────── search (§3.2, §4.4) ─────────────────────────
114
+
115
+ /**
116
+ * The query as kb-api takes it: trimmed, inner runs of blanks as one space, at least COMMUNITY_SEARCH_QUERY_MIN
117
+ * characters and at most COMMUNITY_SEARCH_QUERY_MAX — counted the stricter way at each end (characters for the floor,
118
+ * UTF-16 units for the ceiling, as a schema's string length counts them), so kb-api never refuses one this accepts.
119
+ * Null for anything else — the page says so instead of asking (kb-api would answer VALIDATION and spend the quota).
120
+ */
121
+ export function forumSearchQueryOf(raw: unknown): string | null {
122
+ if (typeof raw !== 'string') return null
123
+ const query = raw.replace(/\s+/gu, ' ').trim()
124
+ return [...query].length >= COMMUNITY_SEARCH_QUERY_MIN && query.length <= COMMUNITY_SEARCH_QUERY_MAX ? query : null
125
+ }
126
+
127
+ /** The next page of a search, or null on the last one (`hasMore` false, or page COMMUNITY_SEARCH_PAGES_MAX). */
128
+ export function nextSearchPage(page: Pick<ForumSearchPage, 'page' | 'hasMore'> | null | undefined): number | null {
129
+ if (!isRecord(page) || page.hasMore !== true) return null
130
+ const current = page.page
131
+ if (typeof current !== 'number' || !Number.isSafeInteger(current) || current < 1 || current >= COMMUNITY_SEARCH_PAGES_MAX) return null
132
+ return current + 1
133
+ }
134
+
135
+ // ───────────────────────── a category's rows (§3.2) ─────────────────────────
136
+
137
+ /** A row of a kind this SDK renders: a topic or an article discussion with the fields a row needs. */
138
+ export function isKnownTopicItem(item: unknown): item is KnownTopicItem {
139
+ if (!isRecord(item) || typeof item.conversationId !== 'string') return false
140
+ if (item.kind === 'topic') return true
141
+ return item.kind === 'article' && typeof item.articleId === 'string'
142
+ }
143
+
144
+ /** A category's rows without the kinds this SDK does not know (a newer kb-api's), in order, never a throw. */
145
+ export function knownTopicItemsOf(items: readonly TopicItem[] | null | undefined): KnownTopicItem[] {
146
+ return Array.isArray(items) ? items.filter(isKnownTopicItem) : []
147
+ }
148
+
149
+ // ───────────────────────── the member's state (§3.5, §4.8, §4.9) ─────────────────────────
150
+
151
+ const SURFACE_KEYS: Readonly<Record<KnownBrakeSurface, 'forum' | 'articleDiscussions'>> = Object.freeze({
152
+ forum: 'forum',
153
+ article_discussions: 'articleDiscussions',
154
+ })
155
+
156
+ const text = (v: unknown): string => (typeof v === 'string' ? v : '')
157
+
158
+ function surfaceInfo(raw: unknown): SurfaceInfo | null {
159
+ if (!isRecord(raw)) return null
160
+ const brake = isRecord(raw.brake) && typeof raw.brake.until === 'string' ? raw.brake : null
161
+ return Object.freeze({
162
+ enabled: raw.enabled === true,
163
+ brake: brake === null ? null : Object.freeze({ kind: text(brake.kind), until: text(brake.until), reasonCode: text(brake.reasonCode) }),
164
+ })
165
+ }
166
+
167
+ /**
168
+ * One surface of MyState's `module.surfaces` — `forum` or `article_discussions` (a BRAKED refusal's spelling) — or null
169
+ * when kb-api did not report it (older than M3: no forum there). A brake without its end is no brake here: a surface
170
+ * brake always ends (≤ 24 h, the database's CHECK).
171
+ */
172
+ export function surfaceInfoOf(module: Pick<ModuleInfo, 'surfaces'> | null | undefined, surface: KnownBrakeSurface): SurfaceInfo | null {
173
+ if (!isRecord(module) || !isRecord(module.surfaces) || !isKnownBrakeSurface(surface)) return null
174
+ return surfaceInfo(module.surfaces[SURFACE_KEYS[surface]])
175
+ }
176
+
177
+ /**
178
+ * The team's away mode („nepřítomen", D-M3-9) while it lasts — MyState's `module.away` whose `until` is still ahead of
179
+ * `now` — else null (none, ended, or a kb-api older than M3). Show `state.away` meanwhile.
180
+ */
181
+ export function communityAwayOf(module: Pick<ModuleInfo, 'away'> | null | undefined, now: number = Date.now()): CommunityAway | null {
182
+ if (!isRecord(module) || !isRecord(module.away)) return null
183
+ const until = module.away.until
184
+ if (typeof until !== 'string') return null
185
+ const end = Date.parse(until)
186
+ return Number.isFinite(end) && end > now ? Object.freeze({ until }) : null
187
+ }
188
+
189
+ /**
190
+ * Whether the viewer moderates `categoryId` now (MyState `moderator.categoryIds`; ids compared in lower case). A
191
+ * page shows the moderator's menu by it; kb-api re-checks the appointment on every moderator operation.
192
+ */
193
+ export function isCategoryModerator(state: Pick<MyState, 'moderator'> | null | undefined, categoryId: string | null | undefined): boolean {
194
+ if (!isRecord(state) || !isRecord(state.moderator) || typeof categoryId !== 'string' || categoryId === '') return false
195
+ const ids = state.moderator.categoryIds
196
+ if (!Array.isArray(ids)) return false
197
+ const wanted = categoryId.toLowerCase()
198
+ return ids.some((id) => typeof id === 'string' && id.toLowerCase() === wanted)
199
+ }
200
+
201
+ /**
202
+ * Which surface a BRAKED refusal paused — `forum` or `article_discussions`: show that surface paused and leave the
203
+ * other as it is — or null for the module's brake (both paused), for a surface this SDK does not know, and for any
204
+ * other refusal.
205
+ */
206
+ export function brakedSurfaceOf(failure: Pick<CommunityFailure, 'code' | 'surface'> | null | undefined): KnownBrakeSurface | null {
207
+ if (!isRecord(failure) || failure.code !== 'braked') return null
208
+ return isKnownBrakeSurface(failure.surface) ? failure.surface : null
209
+ }