@blogmcp/sdk 0.13.0 → 0.14.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 (67) hide show
  1. package/dist/community/index.d.ts +4 -1
  2. package/dist/community/index.js +39 -36
  3. package/dist/community/legal-text.d.ts +65 -0
  4. package/dist/community/legal-text.js +247 -0
  5. package/dist/community/links.d.ts +6 -0
  6. package/dist/community/links.js +9 -1
  7. package/dist/community/outcome.d.ts +1 -1
  8. package/dist/community/outcome.js +60 -23
  9. package/dist/community/private/browser.d.ts +18 -0
  10. package/dist/community/private/browser.js +17 -0
  11. package/dist/community/private/client.d.ts +259 -0
  12. package/dist/community/private/client.js +98 -0
  13. package/dist/community/private/dm.d.ts +547 -0
  14. package/dist/community/private/dm.js +852 -0
  15. package/dist/community/private/dpop.d.ts +59 -0
  16. package/dist/community/private/dpop.js +46 -0
  17. package/dist/community/private/encoding.d.ts +17 -0
  18. package/dist/community/private/encoding.js +50 -0
  19. package/dist/community/private/host-state.d.ts +20 -0
  20. package/dist/community/private/host-state.js +15 -0
  21. package/dist/community/private/index.d.ts +51 -0
  22. package/dist/community/private/index.js +71 -0
  23. package/dist/community/private/keystore.d.ts +73 -0
  24. package/dist/community/private/keystore.js +91 -0
  25. package/dist/community/private/marker.d.ts +17 -0
  26. package/dist/community/private/marker.js +11 -0
  27. package/dist/community/private/private-routes.d.ts +6 -0
  28. package/dist/community/private/private-routes.js +72 -0
  29. package/dist/community/private/promise.d.ts +65 -0
  30. package/dist/community/private/promise.js +39 -0
  31. package/dist/community/private/realtime.d.ts +127 -0
  32. package/dist/community/private/realtime.js +199 -0
  33. package/dist/community/private/session.d.ts +175 -0
  34. package/dist/community/private/session.js +441 -0
  35. package/dist/community/private/transport.d.ts +47 -0
  36. package/dist/community/private/transport.js +65 -0
  37. package/dist/community/server/grant-handoff.d.ts +53 -0
  38. package/dist/community/server/grant-handoff.js +96 -0
  39. package/dist/community/server/grant.d.ts +100 -0
  40. package/dist/community/server/grant.js +165 -0
  41. package/dist/community/server/index.d.ts +4 -0
  42. package/dist/community/server/index.js +20 -16
  43. package/dist/community/shapes.d.ts +27 -1
  44. package/dist/community/shapes.js +27 -17
  45. package/package.json +7 -3
  46. package/src/community/index.ts +6 -1
  47. package/src/community/legal-text.ts +438 -0
  48. package/src/community/links.ts +8 -0
  49. package/src/community/outcome.ts +37 -0
  50. package/src/community/private/browser.ts +31 -0
  51. package/src/community/private/client.ts +304 -0
  52. package/src/community/private/dm.ts +1687 -0
  53. package/src/community/private/dpop.ts +110 -0
  54. package/src/community/private/encoding.ts +71 -0
  55. package/src/community/private/host-state.ts +37 -0
  56. package/src/community/private/index.ts +169 -0
  57. package/src/community/private/keystore.ts +179 -0
  58. package/src/community/private/marker.ts +28 -0
  59. package/src/community/private/private-routes.ts +80 -0
  60. package/src/community/private/promise.ts +125 -0
  61. package/src/community/private/realtime.ts +431 -0
  62. package/src/community/private/session.ts +848 -0
  63. package/src/community/private/transport.ts +125 -0
  64. package/src/community/server/grant-handoff.ts +179 -0
  65. package/src/community/server/grant.ts +292 -0
  66. package/src/community/server/index.ts +6 -0
  67. package/src/community/shapes.ts +46 -1
@@ -0,0 +1,1687 @@
1
+ /**
2
+ * The DM client (docs/internal/m4-contracts.md §7.8 DM8a): the member's 1:1 messages over the private session
3
+ * (session.ts) — the inbox, opening a conversation, the messages with their delta by `rev`, sending under a
4
+ * `clientMsgId` with endless retries and jitter, edit, delete for everyone, hide for me, clear, read, typing, the
5
+ * requests, private blocks, the audience check, reports with their preview, the member's private cases, statements and
6
+ * appeals, and the private export. The elements (`@blogmcp/community/private`, DM8b) render on it; a host that renders
7
+ * its own UI uses it directly.
8
+ *
9
+ * ```ts
10
+ * const client = createPrivateClient({ kbOrigin, grantPath, member })
11
+ * const dm = createPrivateDmClient(client)
12
+ * const thread = dm.thread(conversationId)
13
+ * thread.subscribe((state) => render(state.messages, state.pending))
14
+ * await thread.loadLatest()
15
+ * thread.send('Dobrý den') // retried until kb-api takes it or refuses it for good
16
+ * realtime.subscribe((event) => dm.apply(event)) // the inbox's content-free events move the open threads
17
+ * // …and in the host's sign-out flow, before privateSignOut(client):
18
+ * dm.close()
19
+ * ```
20
+ *
21
+ * **Nothing leaves the device but the call itself.** A draft lives in this tab's memory only (`drafts`): never in
22
+ * IndexedDB, `sessionStorage`, `localStorage`, a cookie or a request — the member's unsent words are not the server's,
23
+ * and an unsent draft that outlived the tab on a shared browser would be readable by the next person. Sending moves the
24
+ * text into the outbox (memory too), which holds it only until kb-api takes it. Decrypted messages exist in this
25
+ * client's memory for as long as a thread is open and are dropped by `thread.close()` and `close()`. Nothing here logs,
26
+ * tracks or reports (§9.3): a refusal is a code, never a text.
27
+ *
28
+ * **Sending.** `send()` names the message with a fresh `clientMsgId` (a v4 uuid) that every retry repeats, so kb-api
29
+ * stores it once however many attempts reach it (`UNIQUE (conversation_id, author_member_id, client_msg_id)`). An
30
+ * outage a retry can cure — no answer, a timeout, a gateway's 5xx page, `BUSY`, `UNAVAILABLE`, `LEDGER_UNAVAILABLE` —
31
+ * is retried without end, after an exponentially growing wait with jitter (`PRIVATE_DM_RETRY`), so that the member's
32
+ * phone in a tunnel delivers the message once it is out of it, and a thousand phones coming back at once do not knock
33
+ * in step. A refusal that may or may not pass by itself — `TOO_FAST`, `INTERNAL`, an edge's 408 or 429 page — is
34
+ * retried only while the waits after such refusals add up to less than `PRIVATE_DM_RETRY.boundedMs` — an outage in
35
+ * between does not start the count again, so refusals that alternate with outages still end — and then it stops as
36
+ * `failed` with its code:
37
+ * kb-api answers `TOO_FAST` both for its per-second and per-minute limiters and for caps that last the day (the
38
+ * per-recipient message cap, the request caps; §5.1, §7.3), without a Retry-After, so an endless retry of a day-long
39
+ * cap would knock all day, spend the private session's limiter, fire the cap's alert on every attempt and deliver the
40
+ * message a day late without the member knowing; a deterministic 500 on one message would loop for as long as the tab
41
+ * stays open. The member's `outbox.retry()` starts a new count. Any other refusal is final at once (`failed`, with
42
+ * its code): `DM_NOT_ALLOWED`, `VALIDATION`, a quota, a device that is pending, removed or restricted, a session the
43
+ * host no longer has. The messages of one conversation go out one at a time and in order; a message retried by hand
44
+ * keeps its place. `cancel()` stops the retries of one message (it may already be stored, if an earlier attempt
45
+ * reached kb-api and its answer was lost); `retryNow()` (the browser came back online) wakes every waiting message at
46
+ * once.
47
+ *
48
+ * **The delta by `rev`.** A thread keeps each message at the highest `rev` it has seen: an answer that carries an older
49
+ * revision than the one shown never replaces it, whatever order answers arrive in. The inbox's events (`{ k, c, s }`,
50
+ * Appendix A.3) carry no content: `m` reads what is newer than the newest loaded message, `e` and `d` re-read the one
51
+ * message (`sinceRev`: the revision already shown), `rd` moves the read mark, `t` shows „píše…“ for a few seconds, and
52
+ * `resync` re-reads every loaded message, because the socket missed events while it was away.
53
+ *
54
+ * The operations are kb-api's private surface (Appendix A.2): DM3 serves the conversations, requests, blocks, the
55
+ * audience check and the settings, DM4 the messages, DM5 the reports, cases, statements and appeals, DM7b the export.
56
+ * Until kb-api serves an operation it sits in `PRIVATE_DM_OPS_AHEAD` (the drift spec's ledger, as `PRIVATE_OPS_AHEAD`
57
+ * in client.ts). DM3's and DM4's answers follow their routes (`routes/private/{dm,requests,blocks,audience,dm-messages}.ts`); the others
58
+ * follow the contract's text until their slice pins them. Every answer is checked before it is passed on: a single
59
+ * answer outside the vocabulary is `BAD_ANSWER`, a list row this client cannot read is left out.
60
+ */
61
+
62
+ import type { DeletedMemberAuthor, MemberAuthor } from '../shapes'
63
+ import { assertPrivateBrowser } from './browser'
64
+ import type { PrivateRealtimeEvent } from './realtime'
65
+ import type { PrivateCode, PrivateFailure, PrivateOutcome, PrivateSession } from './session'
66
+
67
+ assertPrivateBrowser()
68
+
69
+ // ───────────────────────── the operations ─────────────────────────
70
+
71
+ /** Every DM operation this client calls (the path after `/community/v1/private/`, Appendix A.2). */
72
+ export const PRIVATE_DM_OPS = Object.freeze([
73
+ 'dm/list',
74
+ 'dm/open',
75
+ 'dm/messages',
76
+ 'dm/send',
77
+ 'dm/edit',
78
+ 'dm/delete',
79
+ 'dm/hide',
80
+ 'dm/clear',
81
+ 'dm/read',
82
+ 'dm/typing',
83
+ 'requests/list',
84
+ 'requests/accept',
85
+ 'requests/delete',
86
+ 'requests/block-report',
87
+ 'blocks/add',
88
+ 'blocks/remove',
89
+ 'blocks/list',
90
+ 'audience/check',
91
+ 'reports/preview',
92
+ 'reports/submit',
93
+ 'cases/list',
94
+ 'cases/get',
95
+ 'statements/get',
96
+ 'appeals/submit',
97
+ 'export/download',
98
+ ] as const)
99
+ export type PrivateDmOp = (typeof PRIVATE_DM_OPS)[number]
100
+
101
+ /** The slice of the contract that serves an operation kb-api does not serve yet. */
102
+ export type PrivateDmSlice = 'DM3' | 'DM4' | 'DM5' | 'DM7b'
103
+
104
+ /**
105
+ * The operations built ahead of kb-api, by the slice that serves them (§7.3–§7.7). The drift spec fails on an entry
106
+ * kb-api already serves (the copy `PRIVATE_ROUTES` names it) and on one Appendix A.2 does not name; the integration
107
+ * that regenerates `PRIVATE_ROUTES` after a slice lands removes that slice's entries here.
108
+ */
109
+ export const PRIVATE_DM_OPS_AHEAD: Readonly<Partial<Record<PrivateDmOp, PrivateDmSlice>>> = Object.freeze({
110
+ })
111
+
112
+ // ───────────────────────── constants ─────────────────────────
113
+
114
+ /** `dm/messages` takes at most this many messages per page (§7.4). */
115
+ export const PRIVATE_DM_PAGE_MAX = 50
116
+
117
+ /** At most one `dm/typing` per conversation in this interval: kb-api publishes at most one per 3 s (§7.4). */
118
+ export const PRIVATE_DM_TYPING_INTERVAL_MS = 3_000
119
+
120
+ /** How long a counterpart's „píše…“ shows after their last `t` event (a little over two of their intervals). */
121
+ export const PRIVATE_DM_TYPING_SHOW_MS = 7_000
122
+
123
+ /**
124
+ * The send retries' wait: before attempt n+1 (n ≥ 1) a ceiling of `min(maxMs, baseMs · 2^(n−1))`, of which the wait
125
+ * is a random half to whole (the jitter keeps clients that failed together from retrying together). `boundedMs`: how
126
+ * long a run of bounded refusals (`isBoundedDmFailure`) is retried before the send stops — two minutes, so that a
127
+ * per-minute limiter (`private_messages_per_minute`) has passed by the last attempt, and a day-long cap costs nine to
128
+ * thirteen attempts (with the jitter) instead of thousands.
129
+ */
130
+ export const PRIVATE_DM_RETRY = Object.freeze({ baseMs: 1_000, maxMs: 30_000, boundedMs: 120_000 })
131
+
132
+ /** A thread re-reads at most this many pages at once (a `resync`, a long gap after `m`); the rest on the next event. */
133
+ export const PRIVATE_DM_REREAD_PAGES = 20
134
+
135
+ /**
136
+ * The refusals a retry can cure. `NETWORK` (no answer, a timeout, CORS) and a `BAD_ANSWER` with no status, a 5xx (a
137
+ * gateway's page), a 408 or a 429 (an edge's timeout or rate-limit page) included; every other code is final.
138
+ */
139
+ export const PRIVATE_DM_RETRYABLE: ReadonlySet<string> = Object.freeze(
140
+ new Set(['NETWORK', 'BUSY', 'UNAVAILABLE', 'TOO_FAST', 'INTERNAL', 'LEDGER_UNAVAILABLE']),
141
+ ) as ReadonlySet<string>
142
+
143
+ /**
144
+ * The retryable refusals that are retried only for `PRIVATE_DM_RETRY.boundedMs` in a row (see the module doc):
145
+ * `TOO_FAST` may be a day-long cap, and `INTERNAL` may be a fault that every attempt meets again.
146
+ */
147
+ export const PRIVATE_DM_RETRY_BOUNDED: ReadonlySet<string> = Object.freeze(new Set(['TOO_FAST', 'INTERNAL'])) as ReadonlySet<string>
148
+
149
+ /** True when a send that failed with this refusal is to be tried again. */
150
+ export function isRetryableDmFailure(failure: Pick<PrivateFailure, 'code' | 'status'>): boolean {
151
+ if (PRIVATE_DM_RETRYABLE.has(failure.code)) return true
152
+ return failure.code === 'BAD_ANSWER' && (failure.status === null || failure.status >= 500 || failure.status === 408 || failure.status === 429)
153
+ }
154
+
155
+ /**
156
+ * True when a retryable refusal is retried only within `PRIVATE_DM_RETRY.boundedMs`: an edge's 408 or 429, and a
157
+ * `BAD_ANSWER` with no status. The last is never kb-api's: the session reports it for a fault of its own on this device
158
+ * (a base the grant did not name, an access token it cannot use), which every attempt meets again, so an endless retry
159
+ * of it would knock for as long as the tab stays open.
160
+ */
161
+ export function isBoundedDmFailure(failure: Pick<PrivateFailure, 'code' | 'status'>): boolean {
162
+ if (PRIVATE_DM_RETRY_BOUNDED.has(failure.code)) return true
163
+ return failure.code === 'BAD_ANSWER' && (failure.status === null || failure.status === 408 || failure.status === 429)
164
+ }
165
+
166
+ // ───────────────────────── the shapes (§7.3–§7.7) ─────────────────────────
167
+
168
+ /** The SDK's own code for a send the member or the host stopped (`cancel()`, `close()`). */
169
+ export type PrivateDmClientCode = 'CANCELLED'
170
+
171
+ export type PrivateDmFailure = PrivateFailure | { ok: false; code: PrivateDmClientCode; status: null }
172
+
173
+ /** What a send resolves to: kb-api's stored message, a final refusal, or `CANCELLED`. */
174
+ export type PrivateDmSendOutcome = { ok: true; value: { message: PrivateDmMessage } } | PrivateDmFailure
175
+
176
+ /**
177
+ * The other member of a conversation: their profile card, never more (§7.3) — the public surface's author shape, as
178
+ * DM3 answers it; an erased member, or one without a profile, is the deleted placeholder.
179
+ */
180
+ export type PrivateDmCounterpart = MemberAuthor | DeletedMemberAuthor
181
+
182
+ /** A conversation of the inbox (`dm/list`): its counterpart, its last activity and the unread count — never a body. */
183
+ export interface PrivateDmConversation {
184
+ readonly conversationId: string
185
+ /** `request`: a request the member sent that is not accepted yet (a received one is in `requests.list`). */
186
+ readonly state: 'open' | 'request'
187
+ readonly counterpart: PrivateDmCounterpart
188
+ /** The later of the last message and the conversation's creation. */
189
+ readonly lastActivityAt: string
190
+ readonly lastSeq: number
191
+ /** The counterpart's messages after the member's read mark (kb-api stops counting at 99). */
192
+ readonly unread: number
193
+ }
194
+
195
+ /** `dm/open`: the member's one conversation with that person — a new or an existing one. */
196
+ export interface PrivateDmOpened {
197
+ readonly conversationId: string
198
+ readonly state: 'open' | 'request'
199
+ }
200
+
201
+ /**
202
+ * A message as a participant reads it. `deleted`: its author deleted it for everyone (a tombstone, no text);
203
+ * `removed`: a decision removed it („odstraněno“ for both, no text, the row kept for the case).
204
+ */
205
+ export const PRIVATE_DM_MESSAGE_STATES = Object.freeze(['visible', 'deleted', 'removed'] as const)
206
+ export type PrivateDmMessageState = (typeof PRIVATE_DM_MESSAGE_STATES)[number]
207
+
208
+ export interface PrivateDmMessage {
209
+ readonly conversationId: string
210
+ readonly seq: number
211
+ readonly id: string
212
+ readonly rev: number
213
+ /** The member wrote it. */
214
+ readonly mine: boolean
215
+ readonly replyToSeq: number | null
216
+ readonly state: PrivateDmMessageState
217
+ /** The decrypted text; null on a tombstone and on a removed message. */
218
+ readonly text: string | null
219
+ /** „upraveno“. */
220
+ readonly editedMark: boolean
221
+ readonly createdAt: string
222
+ readonly editedAt: string | null
223
+ /** The member's own message: the id its send named, when kb-api echoes it (it lets a pending copy settle early). */
224
+ readonly clientMsgId: string | null
225
+ }
226
+
227
+ /** `dm/messages`' body: the newest page, a page before `beforeSeq`, or the messages after `afterSeq`. */
228
+ export interface PrivateDmMessagesQuery {
229
+ readonly conversationId: string
230
+ readonly afterSeq?: number
231
+ readonly beforeSeq?: number
232
+ /** 1…50 (default 50). */
233
+ readonly limit?: number
234
+ /** The revision already shown: kb-api may leave out a message whose `rev` is not newer. */
235
+ readonly sinceRev?: number
236
+ }
237
+
238
+ export interface PrivateDmPage {
239
+ /** Ascending by `seq`; a row this client cannot read (a state it does not know, a malformed one) is left out. */
240
+ readonly messages: readonly PrivateDmMessage[]
241
+ /** More beyond this page in the direction asked (the page was full when kb-api did not say). */
242
+ readonly hasMore: boolean
243
+ /**
244
+ * How far the counterpart has read, when read receipts are mutual (DM4's `counterpartReadSeq`); null when they are
245
+ * not — nothing is told —, and undefined when the answer did not say (a kb-api before DM4's field).
246
+ */
247
+ readonly counterpartReadSeq?: number | null
248
+ }
249
+
250
+ /** A read mark's outcome: whether `dm/read` was asked, and how many of the conversation's notifications it read. */
251
+ export interface PrivateDmReadResult {
252
+ readonly sent: boolean
253
+ /**
254
+ * The conversation's unread `dm_message`/`dm_request` notifications kb-api marked read with the cursor (0 when
255
+ * nothing was asked): the host refreshes its unread dot only when this is more than 0.
256
+ */
257
+ readonly notificationsRead: number
258
+ }
259
+
260
+ export interface PrivateDmSendInput {
261
+ readonly conversationId: string
262
+ readonly text: string
263
+ readonly replyToSeq?: number
264
+ }
265
+
266
+ export interface PrivateDmEditInput {
267
+ readonly conversationId: string
268
+ readonly seq: number
269
+ /** The revision the member edited: kb-api refuses an edit of a text that changed since. */
270
+ readonly rev: number
271
+ readonly text: string
272
+ }
273
+
274
+ /**
275
+ * One message on its way out (memory only): `queued` behind an earlier message of its conversation (nothing was asked
276
+ * yet), `sending` (an attempt is out), `waiting` for its next attempt, or `failed` for good.
277
+ */
278
+ export interface PrivateDmPendingSend {
279
+ readonly clientMsgId: string
280
+ readonly conversationId: string
281
+ readonly text: string
282
+ readonly replyToSeq: number | null
283
+ readonly state: 'queued' | 'sending' | 'waiting' | 'failed'
284
+ readonly attempts: number
285
+ /** The last refusal (a `waiting` message says why it waits; a `failed` one why it stopped). */
286
+ readonly lastCode: PrivateCode | null
287
+ }
288
+
289
+ /** A send in progress: its id at once, its end when kb-api takes it or refuses it for good. */
290
+ export interface PrivateDmSending {
291
+ readonly clientMsgId: string
292
+ readonly done: Promise<PrivateDmSendOutcome>
293
+ /** Stop retrying (see the module doc: an earlier attempt may already have been stored). */
294
+ cancel(): void
295
+ }
296
+
297
+ /** A request the member received (`requests/list`): the sender's card, for „Přijmout“ / „Smazat“ / „Zablokovat a nahlásit“. */
298
+ export interface PrivateDmRequest {
299
+ readonly conversationId: string
300
+ /** The sender. */
301
+ readonly from: PrivateDmCounterpart
302
+ readonly createdAt: string
303
+ readonly lastMessageAt: string | null
304
+ }
305
+
306
+ /** A private-context block (`blocks/list`). */
307
+ export interface PrivateDmBlock {
308
+ readonly memberId: string
309
+ readonly author: PrivateDmCounterpart
310
+ readonly blockedAt: string
311
+ }
312
+
313
+ /** `audience/check`: whether the member may write to that handle directly, only by a request, or not at all. */
314
+ export interface PrivateDmAudience {
315
+ readonly canWrite: 'direct' | 'request' | 'no'
316
+ }
317
+
318
+ /** The report's line: the tenant's rules (the authorised persons under U18, else blogmcp T&S) or illegal content. */
319
+ export type PrivateDmReportLine = 'rules' | 'illegal'
320
+
321
+ export interface PrivateDmReportTarget {
322
+ readonly conversationId: string
323
+ /** The reported message: the package is the contiguous range that ends with it. */
324
+ readonly seq: number
325
+ readonly line: PrivateDmReportLine
326
+ }
327
+
328
+ /** Who receives the package („kdo to dostane“): the authorised persons by name, or blogmcp's T&S. */
329
+ export type PrivateDmReportRecipients =
330
+ | { readonly kind: 'authorised_persons'; readonly names: readonly string[] }
331
+ | { readonly kind: 'platform_ts' }
332
+
333
+ /** `reports/preview`: exactly what goes to whom (§7.5). */
334
+ export interface PrivateDmReportPreview {
335
+ readonly messages: readonly PrivateDmMessage[]
336
+ readonly recipients: PrivateDmReportRecipients
337
+ }
338
+
339
+ export interface PrivateDmReportInput extends PrivateDmReportTarget {
340
+ readonly category: string
341
+ /** The reporter's note (kb-api keeps it encrypted under the case's key). */
342
+ readonly text?: string
343
+ /**
344
+ * Block the reported sender too. The form shows the box ticked (§7.5: "the sender is blocked automatically (can be
345
+ * unticked …)"), so the SDK sends `true` unless the reporter unticked it.
346
+ */
347
+ readonly block?: boolean
348
+ }
349
+
350
+ export interface PrivateDmBlockReportInput {
351
+ readonly conversationId: string
352
+ readonly category: string
353
+ readonly text?: string
354
+ }
355
+
356
+ /** One of the member's private cases (`cases/list`, `cases/get`): codes and times only, the fields DM5 pins. */
357
+ export interface PrivateDmCase {
358
+ readonly caseId: string
359
+ readonly state: string
360
+ readonly line: PrivateDmReportLine
361
+ readonly openedAt: string
362
+ /** The decision's id once decided (`statements/get`, `appeals/submit` take it). */
363
+ readonly decisionId: string | null
364
+ }
365
+
366
+ /** A statement of reasons about a private case (`statements/get`). */
367
+ export interface PrivateDmStatement {
368
+ readonly decisionId: string
369
+ readonly statement: string
370
+ readonly decidedAt: string
371
+ /** Until when an appeal is taken (`private_appeal_window_months`). */
372
+ readonly closesAt: string | null
373
+ }
374
+
375
+ /**
376
+ * `export/download`: on a managed blog the export itself; on a headless site only `{ confirmSent: true }` — the
377
+ * export is confirmed from the e-mail and downloaded on the account host, never through the tenant's origin (§7.7).
378
+ * The session's `call` reads JSON only: an export that kb-api streams (§7.7, a managed blog) needs a streaming read
379
+ * that DM7b pins with its route; until then the client reads a JSON answer and anything else is `BAD_ANSWER`.
380
+ */
381
+ export type PrivateDmExport = { readonly confirmSent: true } | { readonly confirmSent?: false; readonly export: Readonly<Record<string, unknown>> }
382
+
383
+ /** The member's drafts, in this tab's memory only (see the module doc). */
384
+ export interface PrivateDmDrafts {
385
+ get(conversationId: string): string
386
+ /** An empty text deletes the draft. */
387
+ set(conversationId: string, text: string): void
388
+ delete(conversationId: string): void
389
+ /** Every draft of this client. */
390
+ clear(): void
391
+ }
392
+
393
+ /** What a thread shows. */
394
+ export interface PrivateDmThreadState {
395
+ readonly conversationId: string
396
+ /** Ascending by `seq`, each at the highest revision seen; hidden and cleared ones are gone. */
397
+ readonly messages: readonly PrivateDmMessage[]
398
+ /**
399
+ * The member's messages still on their way, in the order they were sent (a message retried by hand keeps its
400
+ * place; the ones written after it may have gone out while it stood failed).
401
+ */
402
+ readonly pending: readonly PrivateDmPendingSend[]
403
+ /** Older messages remain (`loadOlder`). */
404
+ readonly hasOlder: boolean
405
+ readonly loading: boolean
406
+ /** The newest page was read at least once. */
407
+ readonly loaded: boolean
408
+ /**
409
+ * How far the counterpart has read (receipts flow only when both members turned them on, §7.4): from the pages'
410
+ * `counterpartReadSeq` — so „Přečteno“ shows as soon as the thread opens — and moved forward by each live `rd`. A page
411
+ * that says receipts are not mutual (null) clears it.
412
+ */
413
+ readonly readUpTo: number | null
414
+ /** The counterpart is typing („píše…“). */
415
+ readonly typing: boolean
416
+ /** The last refusal of a load (null after a load that succeeded). */
417
+ readonly error: PrivateCode | null
418
+ }
419
+
420
+ export type PrivateDmThreadListener = (state: PrivateDmThreadState) => void
421
+
422
+ export interface PrivateDmThread {
423
+ readonly conversationId: string
424
+ state(): PrivateDmThreadState
425
+ /** Called at once with the current state and on every change; returns the unsubscribe. */
426
+ subscribe(listener: PrivateDmThreadListener): () => void
427
+ /** The newest page. */
428
+ loadLatest(): Promise<PrivateOutcome<null>>
429
+ /** The page before the oldest loaded message. */
430
+ loadOlder(): Promise<PrivateOutcome<null>>
431
+ /** Everything after the newest loaded message. */
432
+ loadNewer(): Promise<PrivateOutcome<null>>
433
+ /** Re-read every loaded message (after a `resync`). */
434
+ refresh(): Promise<PrivateOutcome<null>>
435
+ /** One inbox event about this conversation (`dm.apply` routes them here). */
436
+ apply(event: PrivateRealtimeEvent): void
437
+ /** Send into this conversation; the draft of it goes (its text moved into the outbox). */
438
+ send(text: string, options?: { replyToSeq?: number }): PrivateDmSending
439
+ /** `dm/read` up to the newest loaded message (only ever forward). */
440
+ markRead(): Promise<PrivateOutcome<PrivateDmReadResult>>
441
+ /** Forget this thread's messages (pending sends go on). */
442
+ close(): void
443
+ }
444
+
445
+ /** What an inbox event asks of a host besides the open threads (`dmEventEffect`). */
446
+ export type PrivateDmEventEffect =
447
+ /** The inbox list and its unread counts may have changed: re-read them. */
448
+ | 'inbox'
449
+ /** Only an open thread changes (an edit): the inbox's counts stay. */
450
+ | 'thread'
451
+ /** „píše…“: nothing to re-read. */
452
+ | 'typing'
453
+ /** A read receipt: nothing to re-read. */
454
+ | 'receipt'
455
+ /** Not a DM event (an account event of §6.3): the private view's own business. */
456
+ | 'other'
457
+
458
+ /** The DM kinds of the inbox channel's events (Appendix A.3). */
459
+ export const PRIVATE_DM_EVENT_KINDS = Object.freeze(['m', 'e', 'd', 't', 'rq', 'rd', 'resync'] as const)
460
+
461
+ /**
462
+ * What a host does with one inbox event beyond `dm.apply`: only `m`, `d`, `rq` and `resync` can move the inbox's list
463
+ * or its unread counts — a typing or a read event re-reads nothing, so a busy conversation never spends the private
464
+ * session's limiter on counts that did not move.
465
+ */
466
+ export function dmEventEffect(event: Pick<PrivateRealtimeEvent, 'k'>): PrivateDmEventEffect {
467
+ switch (event.k) {
468
+ case 'm':
469
+ case 'd':
470
+ case 'rq':
471
+ case 'resync':
472
+ return 'inbox'
473
+ case 'e':
474
+ return 'thread'
475
+ case 't':
476
+ return 'typing'
477
+ case 'rd':
478
+ return 'receipt'
479
+ default:
480
+ return 'other'
481
+ }
482
+ }
483
+
484
+ // ───────────────────────── the client ─────────────────────────
485
+
486
+ export interface PrivateDmClientOptions {
487
+ /** The send retries' wait and the bounded refusals' window (default `PRIVATE_DM_RETRY`). */
488
+ retry?: { baseMs?: number; maxMs?: number; boundedMs?: number }
489
+ /** For the jitter (default `Math.random`). */
490
+ random?: () => number
491
+ /** For `clientMsgId` (default `crypto.randomUUID`). */
492
+ randomUUID?: () => string
493
+ now?: () => number
494
+ /**
495
+ * The member's own id (the host's `me/get`), when the host knows it. An `rd` event whose `r` names the member is the
496
+ * member's own read on another device, not the counterpart's receipt: it moves this client's read mark and never
497
+ * the thread's `readUpTo`, which says how far the OTHER participant has read.
498
+ */
499
+ self?: () => string | null
500
+ }
501
+
502
+ export interface PrivateDmClient {
503
+ /**
504
+ * One page of the inbox, newest activity first (a pending device sees only conversations active since it exists,
505
+ * §5.10); `nextCursor` asks for the next page. A row this client cannot read is left out.
506
+ */
507
+ inbox(cursor?: string): Promise<PrivateOutcome<{ items: readonly PrivateDmConversation[]; nextCursor: string | null }>>
508
+ /** The conversation with the member behind `handle`: an existing one, a new one, or a request (§7.3). */
509
+ open(handle: string): Promise<PrivateOutcome<PrivateDmOpened>>
510
+ /** One page of messages (the threads use it; a host that keeps its own state may too). */
511
+ messages(query: PrivateDmMessagesQuery): Promise<PrivateOutcome<PrivateDmPage>>
512
+ /** Send with retries (see the module doc). */
513
+ send(input: PrivateDmSendInput): PrivateDmSending
514
+ edit(input: PrivateDmEditInput): Promise<PrivateOutcome<{ message: PrivateDmMessage }>>
515
+ /** Delete for everyone, within `private_delete_for_all_hours` (`DELETE_WINDOW` after it: offer `hide`). */
516
+ delete(input: { conversationId: string; seq: number }): Promise<PrivateOutcome<{ message: PrivateDmMessage }>>
517
+ /** Delete for me („smazat u mě“). */
518
+ hide(input: { conversationId: string; seq: number }): Promise<PrivateOutcome<null>>
519
+ /** Clear the conversation for me. */
520
+ clear(conversationId: string): Promise<PrivateOutcome<null>>
521
+ /**
522
+ * Move the member's read mark to `seq`; a mark that is not further than the last one sent asks nothing. kb-api reads
523
+ * the conversation's own notifications up to the mark with it (`notificationsRead`).
524
+ */
525
+ read(conversationId: string, seq: number): Promise<PrivateOutcome<PrivateDmReadResult>>
526
+ /** „píše…“: at most one call per conversation in `PRIVATE_DM_TYPING_INTERVAL_MS`; the others ask nothing. */
527
+ typing(conversationId: string): Promise<PrivateOutcome<{ sent: boolean }>>
528
+ readonly requests: {
529
+ /** The requests the member received, a page at a time (a row this client cannot read is left out). */
530
+ list(cursor?: string): Promise<PrivateOutcome<{ items: readonly PrivateDmRequest[]; nextCursor: string | null }>>
531
+ accept(conversationId: string): Promise<PrivateOutcome<null>>
532
+ /** The request goes, with its conversation (§7.3). */
533
+ delete(conversationId: string): Promise<PrivateOutcome<null>>
534
+ /** „Zablokovat a nahlásit“: the snapshot, the case, the block, then the request goes (§7.5). */
535
+ blockReport(input: PrivateDmBlockReportInput): Promise<PrivateOutcome<{ caseId: string }>>
536
+ }
537
+ readonly blocks: {
538
+ add(memberId: string): Promise<PrivateOutcome<null>>
539
+ remove(memberId: string): Promise<PrivateOutcome<null>>
540
+ list(): Promise<PrivateOutcome<{ blocks: readonly PrivateDmBlock[] }>>
541
+ }
542
+ readonly audience: {
543
+ check(handle: string): Promise<PrivateOutcome<PrivateDmAudience>>
544
+ }
545
+ readonly reports: {
546
+ preview(target: PrivateDmReportTarget): Promise<PrivateOutcome<PrivateDmReportPreview>>
547
+ submit(input: PrivateDmReportInput): Promise<PrivateOutcome<{ caseId: string }>>
548
+ }
549
+ readonly cases: {
550
+ list(cursor?: string): Promise<PrivateOutcome<{ items: readonly PrivateDmCase[]; nextCursor: string | null }>>
551
+ get(caseId: string): Promise<PrivateOutcome<{ case: PrivateDmCase }>>
552
+ }
553
+ readonly statements: {
554
+ get(decisionId: string): Promise<PrivateOutcome<PrivateDmStatement>>
555
+ }
556
+ readonly appeals: {
557
+ submit(input: { decisionId: string; text: string }): Promise<PrivateOutcome<{ appealId: string; submittedAt: string }>>
558
+ }
559
+ readonly export: {
560
+ download(): Promise<PrivateOutcome<PrivateDmExport>>
561
+ }
562
+ readonly drafts: PrivateDmDrafts
563
+ readonly outbox: {
564
+ /** The pending sends, of one conversation or of all. */
565
+ pending(conversationId?: string): readonly PrivateDmPendingSend[]
566
+ /** Try every waiting message now (the browser came back online, the realtime socket reconnected). */
567
+ retryNow(): void
568
+ /**
569
+ * Send a `failed` message again under its `clientMsgId`, in its old place in the conversation's order: the new
570
+ * send (its `done` is the retried message's end), or null when no failed message has that id.
571
+ */
572
+ retry(clientMsgId: string): PrivateDmSending | null
573
+ /** Drop a `failed` message (or stop and drop a pending one). */
574
+ discard(clientMsgId: string): boolean
575
+ }
576
+ /** The thread of one conversation (one per conversation while it is open). */
577
+ thread(conversationId: string): PrivateDmThread
578
+ /** One inbox event: routed to the open thread it names, `resync` to every open thread. */
579
+ apply(event: PrivateRealtimeEvent): PrivateDmEventEffect
580
+ /**
581
+ * Drop everything this client holds — drafts, the outbox (its sends end `CANCELLED`), every thread's messages — and
582
+ * stop its timers. Hosts call it when the private view unmounts and before `privateSignOut`.
583
+ */
584
+ close(): void
585
+ }
586
+
587
+ /** The one thing the DM client needs of the private client: its session's `call`. */
588
+ export type PrivateDmClientSource = { readonly session: Pick<PrivateSession, 'call'> }
589
+
590
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
591
+ const MESSAGE_STATES: ReadonlySet<string> = new Set(PRIVATE_DM_MESSAGE_STATES)
592
+
593
+ const invalid = (): PrivateFailure => ({ ok: false, code: 'VALIDATION', status: null })
594
+ const badAnswer = (): PrivateFailure => ({ ok: false, code: 'BAD_ANSWER', status: 200 })
595
+ const cancelled = (): PrivateDmFailure => ({ ok: false, code: 'CANCELLED', status: null })
596
+ const isId = (v: unknown): v is string => typeof v === 'string' && UUID_RE.test(v)
597
+ const isSeq = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 1
598
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
599
+
600
+ /**
601
+ * One message of an answer as the thread keeps it, or null for a row this client cannot read: a state it does not
602
+ * know (an open enum: a later kb-api may add one), a visible row without text, a malformed id, seq or rev, or a row of
603
+ * another conversation.
604
+ */
605
+ export function privateDmMessageOf(raw: unknown, conversationId?: string): PrivateDmMessage | null {
606
+ if (!isRecord(raw)) return null
607
+ const cid = typeof raw.conversationId === 'string' ? raw.conversationId.toLowerCase() : null
608
+ if (cid === null || !UUID_RE.test(cid) || (conversationId !== undefined && cid !== conversationId.toLowerCase())) return null
609
+ if (!isSeq(raw.seq) || typeof raw.id !== 'string' || raw.id === '') return null
610
+ if (typeof raw.rev !== 'number' || !Number.isSafeInteger(raw.rev) || raw.rev < 0) return null
611
+ if (typeof raw.state !== 'string' || !MESSAGE_STATES.has(raw.state)) return null
612
+ const state = raw.state as PrivateDmMessageState
613
+ const text = state === 'visible' ? raw.text : null
614
+ if (state === 'visible' && typeof text !== 'string') return null
615
+ if (typeof raw.createdAt !== 'string') return null
616
+ return Object.freeze({
617
+ conversationId: cid,
618
+ seq: raw.seq,
619
+ id: raw.id,
620
+ rev: raw.rev,
621
+ mine: raw.mine === true,
622
+ replyToSeq: isSeq(raw.replyToSeq) ? raw.replyToSeq : null,
623
+ state,
624
+ text: text as string | null,
625
+ editedMark: raw.editedMark === true,
626
+ createdAt: raw.createdAt,
627
+ editedAt: typeof raw.editedAt === 'string' ? raw.editedAt : null,
628
+ clientMsgId: isId(raw.clientMsgId) ? raw.clientMsgId.toLowerCase() : null,
629
+ })
630
+ }
631
+
632
+ function messagesOf(raw: unknown, conversationId: string): PrivateDmMessage[] | null {
633
+ if (!Array.isArray(raw)) return null
634
+ const out: PrivateDmMessage[] = []
635
+ for (const row of raw) {
636
+ const m = privateDmMessageOf(row, conversationId)
637
+ if (m) out.push(m)
638
+ }
639
+ return out.sort((a, b) => a.seq - b.seq)
640
+ }
641
+
642
+ const isCount = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0
643
+ const isText = (v: unknown): v is string => typeof v === 'string' && v !== ''
644
+ const stringOrNull = (v: unknown): string | null | undefined => (v === null || v === undefined ? null : typeof v === 'string' ? v : undefined)
645
+ const isOpenState = (v: unknown): v is 'open' | 'request' => v === 'open' || v === 'request'
646
+ const isLine = (v: unknown): v is PrivateDmReportLine => v === 'rules' || v === 'illegal'
647
+
648
+ const DELETED_COUNTERPART: DeletedMemberAuthor = Object.freeze({
649
+ kind: 'member',
650
+ memberId: null,
651
+ handle: null,
652
+ displayName: null,
653
+ avatarPreset: null,
654
+ deleted: true,
655
+ })
656
+
657
+ /** A counterpart's card, the deleted placeholder for an erased member, or null for anything else. */
658
+ function counterpartOf(raw: unknown): PrivateDmCounterpart | null {
659
+ if (!isRecord(raw) || raw.kind !== 'member') return null
660
+ if (raw.deleted === true && raw.memberId === null) return DELETED_COUNTERPART
661
+ if (!isId(raw.memberId) || !isText(raw.handle) || !isText(raw.displayName)) return null
662
+ const avatarPreset = stringOrNull(raw.avatarPreset)
663
+ if (avatarPreset === undefined) return null
664
+ return Object.freeze({ kind: 'member', memberId: raw.memberId.toLowerCase(), handle: raw.handle, displayName: raw.displayName, avatarPreset })
665
+ }
666
+
667
+ function conversationOf(raw: unknown): PrivateDmConversation | null {
668
+ if (!isRecord(raw) || !isId(raw.conversationId) || !isOpenState(raw.state)) return null
669
+ const counterpart = counterpartOf(raw.counterpart)
670
+ if (!counterpart || !isText(raw.lastActivityAt) || !isCount(raw.lastSeq) || !isCount(raw.unread)) return null
671
+ return Object.freeze({
672
+ conversationId: raw.conversationId.toLowerCase(),
673
+ state: raw.state,
674
+ counterpart,
675
+ lastActivityAt: raw.lastActivityAt,
676
+ lastSeq: raw.lastSeq,
677
+ unread: raw.unread,
678
+ })
679
+ }
680
+
681
+ function requestOf(raw: unknown): PrivateDmRequest | null {
682
+ if (!isRecord(raw) || !isId(raw.conversationId) || !isText(raw.createdAt)) return null
683
+ const from = counterpartOf(raw.from)
684
+ const lastMessageAt = stringOrNull(raw.lastMessageAt)
685
+ if (!from || lastMessageAt === undefined) return null
686
+ return Object.freeze({ conversationId: raw.conversationId.toLowerCase(), from, createdAt: raw.createdAt, lastMessageAt })
687
+ }
688
+
689
+ function blockOf(raw: unknown): PrivateDmBlock | null {
690
+ if (!isRecord(raw) || !isId(raw.memberId) || !isText(raw.blockedAt)) return null
691
+ const author = counterpartOf(raw.author)
692
+ return author ? Object.freeze({ memberId: raw.memberId.toLowerCase(), author, blockedAt: raw.blockedAt }) : null
693
+ }
694
+
695
+ function caseOf(raw: unknown): PrivateDmCase | null {
696
+ if (!isRecord(raw) || !isId(raw.caseId) || !isText(raw.state) || !isLine(raw.line) || !isText(raw.openedAt)) return null
697
+ if (raw.decisionId !== undefined && raw.decisionId !== null && !isId(raw.decisionId)) return null
698
+ return Object.freeze({
699
+ caseId: raw.caseId.toLowerCase(),
700
+ state: raw.state,
701
+ line: raw.line,
702
+ openedAt: raw.openedAt,
703
+ decisionId: isId(raw.decisionId) ? raw.decisionId.toLowerCase() : null,
704
+ })
705
+ }
706
+
707
+ /** The rows of a list answer that this client can read, or null when the answer holds no list at all. */
708
+ function rowsOf<T>(raw: unknown, of: (row: unknown) => T | null): T[] | null {
709
+ if (!Array.isArray(raw)) return null
710
+ const out: T[] = []
711
+ for (const row of raw) {
712
+ const r = of(row)
713
+ if (r) out.push(r)
714
+ }
715
+ return out
716
+ }
717
+
718
+ /** A trimmed, non-empty handle (kb-api decides whether it names anyone: `NOT_FOUND` either way, §7.3). */
719
+ function handleOf(value: unknown): string | null {
720
+ if (typeof value !== 'string') return null
721
+ const h = value.trim().replace(/^@/, '')
722
+ return h === '' || h.length > 64 ? null : h
723
+ }
724
+
725
+ /** A text the member wrote: kept as written (kb-api applies its own limits), refused only when blank. */
726
+ function textOf(value: unknown): string | null {
727
+ return typeof value === 'string' && value.trim() !== '' ? value : null
728
+ }
729
+
730
+ interface OutboxEntry {
731
+ readonly clientMsgId: string
732
+ readonly conversationId: string
733
+ readonly text: string
734
+ readonly replyToSeq: number | null
735
+ state: 'queued' | 'sending' | 'waiting' | 'failed'
736
+ attempts: number
737
+ lastCode: PrivateCode | null
738
+ /** Set when the entry leaves the outbox (sent, cancelled, discarded, closed). */
739
+ gone: boolean
740
+ /** Resolves the entry's wait early (`retryNow`, `cancel`, `close`). */
741
+ wake: (() => void) | null
742
+ timer: ReturnType<typeof setTimeout> | null
743
+ settle: (outcome: PrivateDmSendOutcome) => void
744
+ readonly done: Promise<PrivateDmSendOutcome>
745
+ }
746
+
747
+ export function createPrivateDmClient(source: PrivateDmClientSource, options: PrivateDmClientOptions = {}): PrivateDmClient {
748
+ const session = source?.session
749
+ if (!session || typeof session.call !== 'function') throw new TypeError('[blogmcp-sdk] createPrivateDmClient needs the private client (createPrivateClient)')
750
+ const baseMs = Math.max(1, options.retry?.baseMs ?? PRIVATE_DM_RETRY.baseMs)
751
+ const maxMs = Math.max(baseMs, options.retry?.maxMs ?? PRIVATE_DM_RETRY.maxMs)
752
+ const boundedMs = Math.max(0, options.retry?.boundedMs ?? PRIVATE_DM_RETRY.boundedMs)
753
+ const random = options.random ?? Math.random
754
+ const randomUUID = options.randomUUID ?? (() => globalThis.crypto.randomUUID())
755
+ const now = options.now ?? Date.now
756
+ const self = (): string | null => {
757
+ try {
758
+ const id = options.self?.() ?? null
759
+ return isId(id) ? id.toLowerCase() : null
760
+ } catch {
761
+ return null
762
+ }
763
+ }
764
+
765
+ let closed = false
766
+ const drafts = new Map<string, string>()
767
+ const outbox: OutboxEntry[] = []
768
+ const pumping = new Set<string>()
769
+ const lastRead = new Map<string, number>()
770
+ const readInFlight = new Map<string, Promise<PrivateOutcome<PrivateDmReadResult>>>()
771
+ const lastTyping = new Map<string, number>()
772
+ const threads = new Map<string, ThreadImpl>()
773
+
774
+ /**
775
+ * The session's `call`, which resolves every refusal but can still reject on a local fault (the key store, a lock,
776
+ * the proof's signing). A rejection is no answer (`NETWORK`) to the caller, never an unhandled rejection or a send
777
+ * stuck in `sending`; `threw` tells the outbox that the fault was local, so it retries it only within the bounded
778
+ * window — a broken key store would otherwise be tried for as long as the tab is open.
779
+ */
780
+ async function attempt<T>(op: PrivateDmOp, body: Record<string, unknown>): Promise<{ out: PrivateOutcome<T>; threw: boolean }> {
781
+ try {
782
+ return { out: await session.call<T>(op, body), threw: false }
783
+ } catch {
784
+ return { out: { ok: false, code: 'NETWORK', status: null }, threw: true }
785
+ }
786
+ }
787
+
788
+ const call = async <T>(op: PrivateDmOp, body: Record<string, unknown> = {}): Promise<PrivateOutcome<T>> => (await attempt<T>(op, body)).out
789
+
790
+ /** A call whose answer carries nothing the client needs. */
791
+ async function callNull(op: PrivateDmOp, body: Record<string, unknown>): Promise<PrivateOutcome<null>> {
792
+ const out = await call(op, body)
793
+ return out.ok ? { ok: true, value: null } : out
794
+ }
795
+
796
+ /** A call whose answer is one message (`{ message }`), merged into its open thread. */
797
+ async function callMessage(op: PrivateDmOp, body: Record<string, unknown>, conversationId: string): Promise<PrivateOutcome<{ message: PrivateDmMessage }>> {
798
+ const out = await call<{ message?: unknown }>(op, body)
799
+ if (!out.ok) return out
800
+ const message = privateDmMessageOf(out.value.message, conversationId)
801
+ if (!message) return badAnswer()
802
+ threads.get(conversationId)?.merge([message])
803
+ return { ok: true, value: { message } }
804
+ }
805
+
806
+ // ── the outbox ──
807
+
808
+ function pendingOf(entry: OutboxEntry): PrivateDmPendingSend {
809
+ return Object.freeze({
810
+ clientMsgId: entry.clientMsgId,
811
+ conversationId: entry.conversationId,
812
+ text: entry.text,
813
+ replyToSeq: entry.replyToSeq,
814
+ state: entry.state,
815
+ attempts: entry.attempts,
816
+ lastCode: entry.lastCode,
817
+ })
818
+ }
819
+
820
+ function outboxChanged(conversationId: string): void {
821
+ threads.get(conversationId)?.changed()
822
+ }
823
+
824
+ function removeEntry(entry: OutboxEntry): void {
825
+ entry.gone = true
826
+ const i = outbox.indexOf(entry)
827
+ if (i >= 0) outbox.splice(i, 1)
828
+ if (entry.timer !== null) clearTimeout(entry.timer)
829
+ entry.timer = null
830
+ const wake = entry.wake
831
+ entry.wake = null
832
+ wake?.()
833
+ outboxChanged(entry.conversationId)
834
+ }
835
+
836
+ /** The wait before the next attempt (`attempts` already made, ≥ 1): a random half to whole of the ceiling. */
837
+ function retryDelay(attempts: number): number {
838
+ const ceiling = Math.min(maxMs, baseMs * 2 ** Math.min(attempts - 1, 30))
839
+ const r = Math.min(Math.max(random(), 0), 1)
840
+ return Math.round(ceiling / 2 + r * (ceiling / 2))
841
+ }
842
+
843
+ function waitFor(entry: OutboxEntry, ms: number): Promise<void> {
844
+ return new Promise((resolve) => {
845
+ const done = () => {
846
+ if (entry.timer !== null) clearTimeout(entry.timer)
847
+ entry.timer = null
848
+ entry.wake = null
849
+ resolve()
850
+ }
851
+ entry.wake = done
852
+ entry.timer = setTimeout(done, ms)
853
+ })
854
+ }
855
+
856
+ /** The entry stops as `failed` with this refusal (the member may `retry()` it). */
857
+ function fail(entry: OutboxEntry, failure: PrivateFailure): void {
858
+ entry.lastCode = failure.code
859
+ entry.state = 'failed'
860
+ outboxChanged(entry.conversationId)
861
+ entry.settle(failure)
862
+ }
863
+
864
+ /** One entry until kb-api takes it, refuses it for good, or it leaves the outbox. */
865
+ async function deliver(entry: OutboxEntry): Promise<void> {
866
+ /**
867
+ * The time spent after bounded refusals: from each bounded refusal to the answer of the attempt after it. The waits
868
+ * that follow an outage do not count, but an outage does not clear what was spent either — refusals that alternate
869
+ * with outages would otherwise never reach the window and be retried for as long as the tab stays open.
870
+ */
871
+ let boundedSpent = 0
872
+ let boundedAt: number | null = null
873
+ for (;;) {
874
+ if (entry.gone) return
875
+ entry.state = 'sending'
876
+ entry.attempts++
877
+ outboxChanged(entry.conversationId)
878
+ const { out, threw } = await attempt<{ message?: unknown }>('dm/send', {
879
+ conversationId: entry.conversationId,
880
+ clientMsgId: entry.clientMsgId,
881
+ text: entry.text,
882
+ ...(entry.replyToSeq !== null ? { replyToSeq: entry.replyToSeq } : {}),
883
+ })
884
+ if (entry.gone) return
885
+ if (boundedAt !== null) {
886
+ boundedSpent += Math.max(0, now() - boundedAt)
887
+ boundedAt = null
888
+ }
889
+ if (out.ok) {
890
+ const message = privateDmMessageOf(out.value.message, entry.conversationId)
891
+ if (message) {
892
+ removeEntry(entry)
893
+ threads.get(entry.conversationId)?.merge([message])
894
+ entry.settle({ ok: true, value: { message } })
895
+ return
896
+ }
897
+ // Stored, but an answer this client cannot read. A retry under the same clientMsgId would only read the same
898
+ // answer back, without end; the message stops as failed instead, and the thread's next read shows it if it
899
+ // was stored.
900
+ fail(entry, badAnswer())
901
+ return
902
+ }
903
+ if (!isRetryableDmFailure(out)) {
904
+ fail(entry, out)
905
+ return
906
+ }
907
+ if (threw || isBoundedDmFailure(out)) {
908
+ if (boundedSpent >= boundedMs) {
909
+ fail(entry, out)
910
+ return
911
+ }
912
+ boundedAt = now()
913
+ }
914
+ entry.lastCode = out.code
915
+ entry.state = 'waiting'
916
+ outboxChanged(entry.conversationId)
917
+ await waitFor(entry, retryDelay(entry.attempts))
918
+ }
919
+ }
920
+
921
+ /** The conversation's messages go out one at a time, in the order they were sent. */
922
+ async function pump(conversationId: string): Promise<void> {
923
+ if (pumping.has(conversationId)) return
924
+ pumping.add(conversationId)
925
+ try {
926
+ for (;;) {
927
+ if (closed) return
928
+ const next = outbox.find((e) => e.conversationId === conversationId && !e.gone && e.state !== 'failed')
929
+ if (!next) return
930
+ try {
931
+ await deliver(next)
932
+ } catch {
933
+ // Nothing in deliver() is meant to throw; should it, the message stops as failed rather than stand in
934
+ // `sending` for good with a `done` that never settles, and the conversation's later messages go on.
935
+ if (!next.gone && next.state !== 'failed') fail(next, { ok: false, code: 'NETWORK', status: null })
936
+ }
937
+ }
938
+ } finally {
939
+ pumping.delete(conversationId)
940
+ }
941
+ }
942
+
943
+ /**
944
+ * A new outbox entry, at the end — or, with `replacing`, in that entry's place, so that a message retried by hand
945
+ * keeps its place in the conversation's order.
946
+ */
947
+ function enqueue(conversationId: string, text: string, replyToSeq: number | null, clientMsgId: string, replacing?: OutboxEntry): OutboxEntry {
948
+ let settle!: (o: PrivateDmSendOutcome) => void
949
+ const done = new Promise<PrivateDmSendOutcome>((resolve) => {
950
+ settle = resolve
951
+ })
952
+ let settled = false
953
+ const entry: OutboxEntry = {
954
+ clientMsgId,
955
+ conversationId,
956
+ text,
957
+ replyToSeq,
958
+ state: 'queued',
959
+ attempts: 0,
960
+ lastCode: null,
961
+ gone: false,
962
+ wake: null,
963
+ timer: null,
964
+ settle: (o) => {
965
+ if (settled) return
966
+ settled = true
967
+ settle(o)
968
+ },
969
+ done,
970
+ }
971
+ const at = replacing ? outbox.indexOf(replacing) : -1
972
+ if (replacing) replacing.gone = true
973
+ if (at >= 0) outbox.splice(at, 1, entry)
974
+ else outbox.push(entry)
975
+ outboxChanged(conversationId)
976
+ void pump(conversationId).catch(() => undefined)
977
+ return entry
978
+ }
979
+
980
+ function sendingOf(entry: OutboxEntry): PrivateDmSending {
981
+ return {
982
+ clientMsgId: entry.clientMsgId,
983
+ done: entry.done,
984
+ cancel() {
985
+ if (entry.gone) return
986
+ removeEntry(entry)
987
+ entry.settle(cancelled())
988
+ },
989
+ }
990
+ }
991
+
992
+ /** The send, and whether it entered the outbox (a refused or closed one did not: its text is still only the caller's). */
993
+ function enqueueSend(input: PrivateDmSendInput): { sending: PrivateDmSending; queued: boolean } {
994
+ const conversationId = isId(input?.conversationId) ? input.conversationId.toLowerCase() : null
995
+ const text = textOf(input?.text)
996
+ const replyToSeq = input?.replyToSeq === undefined ? null : isSeq(input.replyToSeq) ? input.replyToSeq : undefined
997
+ const clientMsgId = randomUUID().toLowerCase()
998
+ if (closed) return { sending: { clientMsgId, done: Promise.resolve(cancelled()), cancel: () => undefined }, queued: false }
999
+ if (conversationId === null || text === null || replyToSeq === undefined) {
1000
+ return { sending: { clientMsgId, done: Promise.resolve(invalid()), cancel: () => undefined }, queued: false }
1001
+ }
1002
+ return { sending: sendingOf(enqueue(conversationId, text, replyToSeq, clientMsgId)), queued: true }
1003
+ }
1004
+
1005
+ const send = (input: PrivateDmSendInput): PrivateDmSending => enqueueSend(input).sending
1006
+
1007
+ // ── reads and typing ──
1008
+
1009
+ async function read(conversationId: string, seq: number): Promise<PrivateOutcome<PrivateDmReadResult>> {
1010
+ if (!isId(conversationId) || !isSeq(seq)) return invalid()
1011
+ const cid = conversationId.toLowerCase()
1012
+ const inFlight = readInFlight.get(cid)
1013
+ if (inFlight) await inFlight.catch(() => undefined)
1014
+ if ((lastRead.get(cid) ?? 0) >= seq) return { ok: true, value: { sent: false, notificationsRead: 0 } }
1015
+ const run = (async (): Promise<PrivateOutcome<PrivateDmReadResult>> => {
1016
+ const out = await call<{ notificationsRead?: unknown }>('dm/read', { conversationId: cid, seq })
1017
+ if (!out.ok) return out
1018
+ lastRead.set(cid, Math.max(lastRead.get(cid) ?? 0, seq))
1019
+ // A count kb-api did not give (or gave malformed) reads as 0: the host then leaves its dot to the next refresh.
1020
+ const n = out.value?.notificationsRead
1021
+ return { ok: true, value: { sent: true, notificationsRead: typeof n === 'number' && Number.isSafeInteger(n) && n > 0 ? n : 0 } }
1022
+ })()
1023
+ readInFlight.set(cid, run)
1024
+ try {
1025
+ return await run
1026
+ } finally {
1027
+ if (readInFlight.get(cid) === run) readInFlight.delete(cid)
1028
+ }
1029
+ }
1030
+
1031
+ async function typing(conversationId: string): Promise<PrivateOutcome<{ sent: boolean }>> {
1032
+ if (!isId(conversationId)) return invalid()
1033
+ const cid = conversationId.toLowerCase()
1034
+ const at = now()
1035
+ const last = lastTyping.get(cid)
1036
+ if (last !== undefined && at - last < PRIVATE_DM_TYPING_INTERVAL_MS) return { ok: true, value: { sent: false } }
1037
+ lastTyping.set(cid, at)
1038
+ const out = await call('dm/typing', { conversationId: cid })
1039
+ return out.ok ? { ok: true, value: { sent: true } } : out
1040
+ }
1041
+
1042
+ // ── the threads ──
1043
+
1044
+ class ThreadImpl implements PrivateDmThread {
1045
+ readonly conversationId: string
1046
+ private readonly bySeq = new Map<number, PrivateDmMessage>()
1047
+ private readonly listeners = new Set<PrivateDmThreadListener>()
1048
+ private hasOlder = false
1049
+ private loaded = false
1050
+ private loadingCount = 0
1051
+ private readUpTo: number | null = null
1052
+ private typingUntil = 0
1053
+ private typingTimer: ReturnType<typeof setTimeout> | null = null
1054
+ private error: PrivateCode | null = null
1055
+ private ended = false
1056
+ private snapshot: PrivateDmThreadState | null = null
1057
+ /** `loadNewer` coalesces: one read at a time, and one more after it when an event came in meanwhile. */
1058
+ private newer: Promise<PrivateOutcome<null>> | null = null
1059
+ private newerAgain = false
1060
+ /**
1061
+ * An event about this conversation came in while the first page was on its way: that page may have been read
1062
+ * before the change, so the thread reads again once it has loaded rather than drop the event.
1063
+ */
1064
+ private missed = false
1065
+
1066
+ constructor(conversationId: string) {
1067
+ this.conversationId = conversationId
1068
+ }
1069
+
1070
+ state(): PrivateDmThreadState {
1071
+ if (this.snapshot) return this.snapshot
1072
+ const messages = [...this.bySeq.values()].sort((a, b) => a.seq - b.seq)
1073
+ this.snapshot = Object.freeze({
1074
+ conversationId: this.conversationId,
1075
+ messages: Object.freeze(messages),
1076
+ pending: Object.freeze(outbox.filter((e) => e.conversationId === this.conversationId && !e.gone).map(pendingOf)),
1077
+ hasOlder: this.hasOlder,
1078
+ loading: this.loadingCount > 0,
1079
+ loaded: this.loaded,
1080
+ readUpTo: this.readUpTo,
1081
+ typing: this.typingUntil > now(),
1082
+ error: this.error,
1083
+ })
1084
+ return this.snapshot
1085
+ }
1086
+
1087
+ subscribe(listener: PrivateDmThreadListener): () => void {
1088
+ if (this.ended) return () => undefined
1089
+ this.listeners.add(listener)
1090
+ listener(this.state())
1091
+ return () => {
1092
+ this.listeners.delete(listener)
1093
+ }
1094
+ }
1095
+
1096
+ changed(): void {
1097
+ if (this.ended) return
1098
+ this.snapshot = null
1099
+ const state = this.state()
1100
+ for (const l of [...this.listeners]) {
1101
+ try {
1102
+ l(state)
1103
+ } catch (err) {
1104
+ // A host's listener that throws must not break the outbox or the thread mid-change (a send left in
1105
+ // `sending`, a merge half done); its error still surfaces as an uncaught one, outside this client.
1106
+ queueMicrotask(() => {
1107
+ throw err
1108
+ })
1109
+ }
1110
+ }
1111
+ }
1112
+
1113
+ /** Keep each message at its highest revision; a pending copy settles when its stored row arrives. */
1114
+ merge(messages: readonly PrivateDmMessage[]): void {
1115
+ if (this.ended) return
1116
+ let moved = false
1117
+ for (const m of messages) {
1118
+ const known = this.bySeq.get(m.seq)
1119
+ if (known && m.rev <= known.rev) continue
1120
+ this.bySeq.set(m.seq, m)
1121
+ moved = true
1122
+ if (m.clientMsgId !== null) {
1123
+ const entry = outbox.find((e) => e.clientMsgId === m.clientMsgId && !e.gone)
1124
+ if (entry) {
1125
+ removeEntry(entry)
1126
+ entry.settle({ ok: true, value: { message: m } })
1127
+ }
1128
+ }
1129
+ }
1130
+ if (moved) this.changed()
1131
+ }
1132
+
1133
+ drop(seqs: Iterable<number> | 'all'): void {
1134
+ if (seqs === 'all') this.bySeq.clear()
1135
+ else for (const s of seqs) this.bySeq.delete(s)
1136
+ this.changed()
1137
+ }
1138
+
1139
+ /**
1140
+ * The receipt a page carried: a number moves `readUpTo` forward (a live `rd` may already have moved it further, so
1141
+ * never back); null — receipts are no longer mutual — clears it; undefined (not said) leaves it.
1142
+ */
1143
+ private receipt(seq: number | null | undefined): void {
1144
+ if (seq === undefined) return
1145
+ if (seq === null) {
1146
+ if (this.readUpTo !== null) {
1147
+ this.readUpTo = null
1148
+ this.changed()
1149
+ }
1150
+ return
1151
+ }
1152
+ if (this.readUpTo === null || seq > this.readUpTo) {
1153
+ this.readUpTo = seq
1154
+ this.changed()
1155
+ }
1156
+ }
1157
+
1158
+ private highest(): number {
1159
+ let max = 0
1160
+ for (const s of this.bySeq.keys()) if (s > max) max = s
1161
+ return max
1162
+ }
1163
+
1164
+ private lowest(): number | null {
1165
+ let min: number | null = null
1166
+ for (const s of this.bySeq.keys()) if (min === null || s < min) min = s
1167
+ return min
1168
+ }
1169
+
1170
+ private async page(query: Omit<PrivateDmMessagesQuery, 'conversationId'>, joinAfter?: number): Promise<PrivateOutcome<PrivateDmPage>> {
1171
+ this.loadingCount++
1172
+ this.changed()
1173
+ try {
1174
+ const out = await messages({ conversationId: this.conversationId, ...query })
1175
+ if (this.ended) return out
1176
+ this.error = out.ok ? null : out.code
1177
+ if (out.ok) {
1178
+ if (joinAfter !== undefined) this.joinOrReplace(out.value.messages, joinAfter)
1179
+ this.merge(out.value.messages)
1180
+ this.receipt(out.value.counterpartReadSeq)
1181
+ }
1182
+ return out
1183
+ } finally {
1184
+ this.loadingCount--
1185
+ this.changed()
1186
+ }
1187
+ }
1188
+
1189
+ async loadLatest(): Promise<PrivateOutcome<null>> {
1190
+ const before = this.highest()
1191
+ const first = !this.loaded
1192
+ const out = await this.page({ limit: PRIVATE_DM_PAGE_MAX }, before)
1193
+ if (!out.ok) return out
1194
+ if (!this.ended) {
1195
+ if (first) this.hasOlder = out.value.hasMore
1196
+ this.loaded = true
1197
+ this.changed()
1198
+ if (this.missed) {
1199
+ this.missed = false
1200
+ void this.refresh()
1201
+ }
1202
+ }
1203
+ return { ok: true, value: null }
1204
+ }
1205
+
1206
+ /**
1207
+ * A page that does not join the loaded messages (it starts after the newest loaded one + 1): the messages in
1208
+ * between were never read, so the loaded ones below the page go and `loadOlder` reads down from the page — the
1209
+ * thread never shows a gap as if nothing had been written there.
1210
+ */
1211
+ private joinOrReplace(page: readonly PrivateDmMessage[], highestBefore: number): void {
1212
+ const lowest = page.length > 0 ? page[0]!.seq : null
1213
+ if (lowest === null || highestBefore === 0 || lowest <= highestBefore + 1) return
1214
+ for (const s of [...this.bySeq.keys()]) if (s < lowest) this.bySeq.delete(s)
1215
+ this.hasOlder = true
1216
+ }
1217
+
1218
+ async loadOlder(): Promise<PrivateOutcome<null>> {
1219
+ const oldest = this.lowest()
1220
+ if (!this.loaded || oldest === null) return this.loadLatest()
1221
+ if (oldest <= 1) {
1222
+ this.hasOlder = false
1223
+ this.changed()
1224
+ return { ok: true, value: null }
1225
+ }
1226
+ const out = await this.page({ beforeSeq: oldest, limit: PRIVATE_DM_PAGE_MAX })
1227
+ if (!out.ok) return out
1228
+ if (!this.ended) {
1229
+ this.hasOlder = out.value.hasMore
1230
+ this.changed()
1231
+ }
1232
+ return { ok: true, value: null }
1233
+ }
1234
+
1235
+ loadNewer(): Promise<PrivateOutcome<null>> {
1236
+ if (this.newer) {
1237
+ this.newerAgain = true
1238
+ return this.newer
1239
+ }
1240
+ const run = (async (): Promise<PrivateOutcome<null>> => {
1241
+ try {
1242
+ let result: PrivateOutcome<null> = { ok: true, value: null }
1243
+ do {
1244
+ this.newerAgain = false
1245
+ const read = await this.readAfter(this.highest())
1246
+ result = read.ok ? { ok: true, value: null } : read
1247
+ } while (result.ok && this.newerAgain && !this.ended)
1248
+ return result
1249
+ } finally {
1250
+ this.newer = null
1251
+ }
1252
+ })()
1253
+ this.newer = run
1254
+ return run
1255
+ }
1256
+
1257
+ /**
1258
+ * Every page after `after`, at most PRIVATE_DM_REREAD_PAGES of them; `seen` collects the seqs the answers carried.
1259
+ * When the pages run out before the newest message, the newest page is read instead and the loaded messages below
1260
+ * it go (`joinOrReplace`), so the thread holds no gap. Answers whether the read reached the newest message.
1261
+ */
1262
+ private async readAfter(after: number, seen?: Set<number>): Promise<PrivateOutcome<{ complete: boolean }>> {
1263
+ if (!this.loaded) {
1264
+ const first = await this.loadLatest()
1265
+ return first.ok ? { ok: true, value: { complete: false } } : first
1266
+ }
1267
+ let cursor = after
1268
+ for (let i = 0; i < PRIVATE_DM_REREAD_PAGES && !this.ended; i++) {
1269
+ const out = await this.page({ afterSeq: cursor, limit: PRIVATE_DM_PAGE_MAX })
1270
+ if (!out.ok) return out
1271
+ for (const m of out.value.messages) seen?.add(m.seq)
1272
+ const last = out.value.messages[out.value.messages.length - 1]
1273
+ if (!out.value.hasMore || !last || last.seq <= cursor) return { ok: true, value: { complete: true } }
1274
+ cursor = last.seq
1275
+ }
1276
+ if (this.ended) return { ok: true, value: { complete: false } }
1277
+ const newest = await this.page({ limit: PRIVATE_DM_PAGE_MAX }, cursor)
1278
+ return newest.ok ? { ok: true, value: { complete: false } } : newest
1279
+ }
1280
+
1281
+ /**
1282
+ * Re-read every loaded message (after a `resync`). A loaded message the answers no longer carry — hidden or cleared
1283
+ * on another device, or a row this client can no longer read — goes, once the read reached the newest message.
1284
+ */
1285
+ async refresh(): Promise<PrivateOutcome<null>> {
1286
+ const oldest = this.lowest()
1287
+ if (!this.loaded || oldest === null) return this.loadLatest()
1288
+ const seen = new Set<number>()
1289
+ const out = await this.readAfter(oldest - 1, seen)
1290
+ if (!out.ok) return out
1291
+ if (out.value.complete && !this.ended) {
1292
+ const gone = [...this.bySeq.keys()].filter((s) => s >= oldest && !seen.has(s))
1293
+ if (gone.length > 0) this.drop(gone)
1294
+ }
1295
+ return { ok: true, value: null }
1296
+ }
1297
+
1298
+ /** Re-read one loaded message after an edit or a delete; one newer than all loaded reads the rest too. */
1299
+ private reread(seq: number): void {
1300
+ const known = this.bySeq.get(seq)
1301
+ if (!known) {
1302
+ if (seq > this.highest()) void this.loadNewer()
1303
+ return
1304
+ }
1305
+ void this.page({ afterSeq: seq - 1, limit: 1, sinceRev: known.rev })
1306
+ }
1307
+
1308
+ apply(event: PrivateRealtimeEvent): void {
1309
+ if (this.ended || (event.c !== undefined && event.c.toLowerCase() !== this.conversationId)) return
1310
+ // The first page is on its way and may already be stale: read again once it is in (see `missed`).
1311
+ if (!this.loaded && this.loadingCount > 0 && (event.k === 'm' || event.k === 'e' || event.k === 'd' || event.k === 'resync')) {
1312
+ this.missed = true
1313
+ return
1314
+ }
1315
+ switch (event.k) {
1316
+ case 'm':
1317
+ if (this.loaded && (event.s === undefined || event.s > this.highest())) void this.loadNewer()
1318
+ return
1319
+ case 'e':
1320
+ case 'd':
1321
+ if (this.loaded && event.s !== undefined) this.reread(event.s)
1322
+ return
1323
+ case 'rd': {
1324
+ if (event.s === undefined) return
1325
+ const me = self()
1326
+ if (me !== null && typeof event.r === 'string' && event.r.toLowerCase() === me) {
1327
+ // The member read this far on another device: no read needs sending for it from here, and the
1328
+ // counterpart's receipt stays as it was.
1329
+ lastRead.set(this.conversationId, Math.max(lastRead.get(this.conversationId) ?? 0, event.s))
1330
+ return
1331
+ }
1332
+ if (this.readUpTo === null || event.s > this.readUpTo) {
1333
+ this.readUpTo = event.s
1334
+ this.changed()
1335
+ }
1336
+ return
1337
+ }
1338
+ case 't':
1339
+ this.typingUntil = now() + PRIVATE_DM_TYPING_SHOW_MS
1340
+ if (this.typingTimer !== null) clearTimeout(this.typingTimer)
1341
+ this.typingTimer = setTimeout(() => {
1342
+ this.typingTimer = null
1343
+ this.changed()
1344
+ }, PRIVATE_DM_TYPING_SHOW_MS)
1345
+ this.changed()
1346
+ return
1347
+ case 'resync':
1348
+ if (this.loaded) void this.refresh()
1349
+ return
1350
+ default:
1351
+ return
1352
+ }
1353
+ }
1354
+
1355
+ send(text: string, options: { replyToSeq?: number } = {}): PrivateDmSending {
1356
+ const { sending, queued } = enqueueSend({ conversationId: this.conversationId, text, ...(options.replyToSeq !== undefined ? { replyToSeq: options.replyToSeq } : {}) })
1357
+ // The text moved into the outbox, and the draft would show it twice. A send refused before it was queued (a
1358
+ // blank text, a bad reply, a closed client) moved nothing, so the member's draft stays.
1359
+ if (queued) drafts.delete(this.conversationId)
1360
+ return sending
1361
+ }
1362
+
1363
+ markRead(): Promise<PrivateOutcome<PrivateDmReadResult>> {
1364
+ const top = this.highest()
1365
+ if (top < 1) return Promise.resolve({ ok: true, value: { sent: false, notificationsRead: 0 } })
1366
+ return read(this.conversationId, top)
1367
+ }
1368
+
1369
+ close(): void {
1370
+ if (this.ended) return
1371
+ this.ended = true
1372
+ if (this.typingTimer !== null) clearTimeout(this.typingTimer)
1373
+ this.typingTimer = null
1374
+ this.bySeq.clear()
1375
+ this.listeners.clear()
1376
+ this.snapshot = null
1377
+ if (threads.get(this.conversationId) === this) threads.delete(this.conversationId)
1378
+ }
1379
+ }
1380
+
1381
+ // ── the calls ──
1382
+
1383
+ async function messages(query: PrivateDmMessagesQuery): Promise<PrivateOutcome<PrivateDmPage>> {
1384
+ if (!isId(query?.conversationId)) return invalid()
1385
+ const cid = query.conversationId.toLowerCase()
1386
+ const body: Record<string, unknown> = { conversationId: cid }
1387
+ if (query.afterSeq !== undefined) {
1388
+ if (typeof query.afterSeq !== 'number' || !Number.isSafeInteger(query.afterSeq) || query.afterSeq < 0) return invalid()
1389
+ body.afterSeq = query.afterSeq
1390
+ }
1391
+ if (query.beforeSeq !== undefined) {
1392
+ if (!isSeq(query.beforeSeq) || query.afterSeq !== undefined) return invalid()
1393
+ body.beforeSeq = query.beforeSeq
1394
+ }
1395
+ if (query.sinceRev !== undefined) {
1396
+ if (typeof query.sinceRev !== 'number' || !Number.isSafeInteger(query.sinceRev) || query.sinceRev < 0) return invalid()
1397
+ body.sinceRev = query.sinceRev
1398
+ }
1399
+ const limit = query.limit === undefined ? PRIVATE_DM_PAGE_MAX : query.limit
1400
+ if (!Number.isSafeInteger(limit) || limit < 1) return invalid()
1401
+ body.limit = Math.min(limit, PRIVATE_DM_PAGE_MAX)
1402
+ const out = await call<{ messages?: unknown; hasMore?: unknown; counterpartReadSeq?: unknown }>('dm/messages', body)
1403
+ if (!out.ok) return out
1404
+ const list = messagesOf(out.value.messages, cid)
1405
+ if (list === null) return badAnswer()
1406
+ const raw = out.value.messages as unknown[]
1407
+ const hasMore = typeof out.value.hasMore === 'boolean' ? out.value.hasMore : raw.length >= (body.limit as number)
1408
+ // A receipt kb-api did not say, or said in a shape this client cannot read, is not told (undefined).
1409
+ const r = out.value.counterpartReadSeq
1410
+ const counterpartReadSeq = r === null ? null : typeof r === 'number' && Number.isSafeInteger(r) && r >= 0 ? r : undefined
1411
+ return { ok: true, value: { messages: Object.freeze(list), hasMore, ...(counterpartReadSeq !== undefined ? { counterpartReadSeq } : {}) } }
1412
+ }
1413
+
1414
+ /** A body of `{ conversationId }` (lower case), or null when it is not an id. */
1415
+ const conv = (conversationId: unknown): { conversationId: string } | null => (isId(conversationId) ? { conversationId: conversationId.toLowerCase() } : null)
1416
+ const seqBody = (input: { conversationId: string; seq: number } | undefined): { conversationId: string; seq: number } | null => {
1417
+ const c = conv(input?.conversationId)
1418
+ return c && isSeq(input?.seq) ? { ...c, seq: input!.seq } : null
1419
+ }
1420
+
1421
+ function thread(conversationId: string): PrivateDmThread {
1422
+ if (!isId(conversationId)) throw new TypeError('[blogmcp-sdk] dm.thread needs a conversation id')
1423
+ const cid = conversationId.toLowerCase()
1424
+ const existing = threads.get(cid)
1425
+ if (existing) return existing
1426
+ const t = new ThreadImpl(cid)
1427
+ if (closed) {
1428
+ t.close()
1429
+ return t
1430
+ }
1431
+ threads.set(cid, t)
1432
+ return t
1433
+ }
1434
+
1435
+ /** A page cursor kb-api handed out (DM3 takes at most 64 characters). */
1436
+ const isCursor = (v: unknown): v is string => typeof v === 'string' && v !== '' && v.length <= 64
1437
+
1438
+ /** A `{ caseId }` answer (a report, a block-and-report). */
1439
+ async function callCaseId(op: PrivateDmOp, body: Record<string, unknown>): Promise<PrivateOutcome<{ caseId: string }>> {
1440
+ const out = await call<{ caseId?: unknown }>(op, body)
1441
+ if (!out.ok) return out
1442
+ return isId(out.value.caseId) ? { ok: true, value: { caseId: out.value.caseId.toLowerCase() } } : badAnswer()
1443
+ }
1444
+
1445
+ const client: PrivateDmClient = {
1446
+ async inbox(cursor) {
1447
+ if (cursor !== undefined && !isCursor(cursor)) return invalid()
1448
+ const out = await call<{ items?: unknown; nextCursor?: unknown }>('dm/list', cursor === undefined ? {} : { cursor })
1449
+ if (!out.ok) return out
1450
+ const items = rowsOf(out.value.items, conversationOf)
1451
+ if (items === null) return badAnswer()
1452
+ return { ok: true, value: { items: Object.freeze(items), nextCursor: isCursor(out.value.nextCursor) ? out.value.nextCursor : null } }
1453
+ },
1454
+ async open(handle) {
1455
+ const h = handleOf(handle)
1456
+ if (h === null) return invalid()
1457
+ const out = await call<{ conversationId?: unknown; state?: unknown }>('dm/open', { handle: h })
1458
+ if (!out.ok) return out
1459
+ const { conversationId, state } = out.value
1460
+ if (!isId(conversationId) || !isOpenState(state)) return badAnswer()
1461
+ return { ok: true, value: Object.freeze({ conversationId: conversationId.toLowerCase(), state }) }
1462
+ },
1463
+ messages,
1464
+ send,
1465
+ async edit(input) {
1466
+ const target = seqBody(input)
1467
+ const text = textOf(input?.text)
1468
+ if (!target || text === null || typeof input.rev !== 'number' || !Number.isSafeInteger(input.rev) || input.rev < 1) return invalid()
1469
+ return callMessage('dm/edit', { ...target, rev: input.rev, text }, target.conversationId)
1470
+ },
1471
+ async delete(input) {
1472
+ const target = seqBody(input)
1473
+ if (!target) return invalid()
1474
+ return callMessage('dm/delete', target, target.conversationId)
1475
+ },
1476
+ async hide(input) {
1477
+ const target = seqBody(input)
1478
+ if (!target) return invalid()
1479
+ const out = await callNull('dm/hide', target)
1480
+ if (out.ok) threads.get(target.conversationId)?.drop([target.seq])
1481
+ return out
1482
+ },
1483
+ async clear(conversationId) {
1484
+ const c = conv(conversationId)
1485
+ if (!c) return invalid()
1486
+ const out = await callNull('dm/clear', c)
1487
+ if (out.ok) threads.get(c.conversationId)?.drop('all')
1488
+ return out
1489
+ },
1490
+ read,
1491
+ typing,
1492
+ requests: {
1493
+ async list(cursor) {
1494
+ if (cursor !== undefined && !isCursor(cursor)) return invalid()
1495
+ const out = await call<{ items?: unknown; nextCursor?: unknown }>('requests/list', cursor === undefined ? {} : { cursor })
1496
+ if (!out.ok) return out
1497
+ const items = rowsOf(out.value.items, requestOf)
1498
+ if (items === null) return badAnswer()
1499
+ return { ok: true, value: { items: Object.freeze(items), nextCursor: isCursor(out.value.nextCursor) ? out.value.nextCursor : null } }
1500
+ },
1501
+ async accept(conversationId) {
1502
+ const c = conv(conversationId)
1503
+ return c ? callNull('requests/accept', c) : invalid()
1504
+ },
1505
+ async delete(conversationId) {
1506
+ const c = conv(conversationId)
1507
+ if (!c) return invalid()
1508
+ const out = await callNull('requests/delete', c)
1509
+ if (out.ok) threads.get(c.conversationId)?.close()
1510
+ return out
1511
+ },
1512
+ async blockReport(input) {
1513
+ const c = conv(input?.conversationId)
1514
+ if (!c || typeof input.category !== 'string' || input.category === '') return invalid()
1515
+ const note = input.text === undefined ? undefined : textOf(input.text)
1516
+ if (note === null) return invalid()
1517
+ const out = await callCaseId('requests/block-report', { ...c, category: input.category, ...(note !== undefined ? { text: note } : {}) })
1518
+ if (out.ok) threads.get(c.conversationId)?.close()
1519
+ return out
1520
+ },
1521
+ },
1522
+ blocks: {
1523
+ async add(memberId) {
1524
+ return isId(memberId) ? callNull('blocks/add', { memberId: memberId.toLowerCase() }) : invalid()
1525
+ },
1526
+ async remove(memberId) {
1527
+ return isId(memberId) ? callNull('blocks/remove', { memberId: memberId.toLowerCase() }) : invalid()
1528
+ },
1529
+ async list() {
1530
+ const out = await call<{ blocks?: unknown }>('blocks/list')
1531
+ if (!out.ok) return out
1532
+ const blocks = rowsOf(out.value.blocks, blockOf)
1533
+ return blocks === null ? badAnswer() : { ok: true, value: { blocks: Object.freeze(blocks) } }
1534
+ },
1535
+ },
1536
+ audience: {
1537
+ async check(handle) {
1538
+ const h = handleOf(handle)
1539
+ if (h === null) return invalid()
1540
+ const out = await call<{ canWrite?: unknown }>('audience/check', { handle: h })
1541
+ if (!out.ok) return out
1542
+ const canWrite = out.value.canWrite
1543
+ if (canWrite !== 'direct' && canWrite !== 'request' && canWrite !== 'no') return badAnswer()
1544
+ return { ok: true, value: { canWrite } }
1545
+ },
1546
+ },
1547
+ reports: {
1548
+ async preview(target) {
1549
+ const t = seqBody(target)
1550
+ if (!t || (target.line !== 'rules' && target.line !== 'illegal')) return invalid()
1551
+ const out = await call<{ messages?: unknown; recipients?: unknown }>('reports/preview', { ...t, line: target.line })
1552
+ if (!out.ok) return out
1553
+ const list = messagesOf(out.value.messages, t.conversationId)
1554
+ const r = out.value.recipients
1555
+ if (list === null || !isRecord(r)) return badAnswer()
1556
+ let recipients: PrivateDmReportRecipients
1557
+ if (r.kind === 'platform_ts') recipients = Object.freeze({ kind: 'platform_ts' })
1558
+ else if (r.kind === 'authorised_persons' && Array.isArray(r.names) && r.names.every((n) => typeof n === 'string')) {
1559
+ recipients = Object.freeze({ kind: 'authorised_persons', names: Object.freeze([...(r.names as string[])]) })
1560
+ } else return badAnswer()
1561
+ return { ok: true, value: { messages: Object.freeze(list), recipients } }
1562
+ },
1563
+ async submit(input) {
1564
+ const t = seqBody(input)
1565
+ if (!t || (input.line !== 'rules' && input.line !== 'illegal') || typeof input.category !== 'string' || input.category === '') return invalid()
1566
+ const note = input.text === undefined ? undefined : textOf(input.text)
1567
+ if (note === null) return invalid()
1568
+ return callCaseId('reports/submit', {
1569
+ ...t,
1570
+ line: input.line,
1571
+ category: input.category,
1572
+ ...(note !== undefined ? { text: note } : {}),
1573
+ // Ticked by default (§7.5): only an explicit `false` leaves the sender unblocked.
1574
+ block: input.block !== false,
1575
+ })
1576
+ },
1577
+ },
1578
+ cases: {
1579
+ async list(cursor) {
1580
+ if (cursor !== undefined && (typeof cursor !== 'string' || cursor === '')) return invalid()
1581
+ const out = await call<{ items?: unknown; nextCursor?: unknown }>('cases/list', cursor === undefined ? {} : { cursor })
1582
+ if (!out.ok) return out
1583
+ const items = rowsOf(out.value.items, caseOf)
1584
+ if (items === null) return badAnswer()
1585
+ return { ok: true, value: { items: Object.freeze(items), nextCursor: isText(out.value.nextCursor) ? out.value.nextCursor : null } }
1586
+ },
1587
+ async get(caseId) {
1588
+ if (!isId(caseId)) return invalid()
1589
+ const out = await call<{ case?: unknown }>('cases/get', { caseId: caseId.toLowerCase() })
1590
+ if (!out.ok) return out
1591
+ const found = caseOf(out.value.case)
1592
+ return found ? { ok: true, value: { case: found } } : badAnswer()
1593
+ },
1594
+ },
1595
+ statements: {
1596
+ async get(decisionId) {
1597
+ if (!isId(decisionId)) return invalid()
1598
+ const out = await call<Record<string, unknown>>('statements/get', { decisionId: decisionId.toLowerCase() })
1599
+ if (!out.ok) return out
1600
+ const s = out.value
1601
+ const closesAt = stringOrNull(s.closesAt)
1602
+ if (!isId(s.decisionId) || typeof s.statement !== 'string' || !isText(s.decidedAt) || closesAt === undefined) return badAnswer()
1603
+ return { ok: true, value: Object.freeze({ decisionId: s.decisionId.toLowerCase(), statement: s.statement, decidedAt: s.decidedAt, closesAt }) }
1604
+ },
1605
+ },
1606
+ appeals: {
1607
+ async submit(input) {
1608
+ const text = textOf(input?.text)
1609
+ if (!isId(input?.decisionId) || text === null) return invalid()
1610
+ const out = await call<{ appealId?: unknown; submittedAt?: unknown }>('appeals/submit', { decisionId: input.decisionId.toLowerCase(), text })
1611
+ if (!out.ok) return out
1612
+ const { appealId, submittedAt } = out.value
1613
+ if (!isText(appealId) || !isText(submittedAt)) return badAnswer()
1614
+ return { ok: true, value: Object.freeze({ appealId, submittedAt }) }
1615
+ },
1616
+ },
1617
+ export: {
1618
+ async download() {
1619
+ const out = await call<{ confirmSent?: unknown; export?: unknown }>('export/download')
1620
+ if (!out.ok) return out
1621
+ if (out.value.confirmSent === true) return { ok: true, value: Object.freeze({ confirmSent: true as const }) }
1622
+ if (out.value.confirmSent !== undefined && out.value.confirmSent !== false) return badAnswer()
1623
+ return isRecord(out.value.export) ? { ok: true, value: Object.freeze({ export: out.value.export }) } : badAnswer()
1624
+ },
1625
+ },
1626
+ drafts: {
1627
+ get: (conversationId) => drafts.get(String(conversationId).toLowerCase()) ?? '',
1628
+ set(conversationId, text) {
1629
+ if (closed || !isId(conversationId)) return
1630
+ const cid = conversationId.toLowerCase()
1631
+ if (typeof text !== 'string' || text === '') drafts.delete(cid)
1632
+ else drafts.set(cid, text)
1633
+ },
1634
+ delete: (conversationId) => {
1635
+ drafts.delete(String(conversationId).toLowerCase())
1636
+ },
1637
+ clear: () => drafts.clear(),
1638
+ },
1639
+ outbox: {
1640
+ pending(conversationId) {
1641
+ const cid = conversationId === undefined ? null : String(conversationId).toLowerCase()
1642
+ return Object.freeze(outbox.filter((e) => !e.gone && (cid === null || e.conversationId === cid)).map(pendingOf))
1643
+ },
1644
+ retryNow() {
1645
+ for (const e of [...outbox]) e.wake?.()
1646
+ },
1647
+ retry(clientMsgId) {
1648
+ const entry = outbox.find((e) => e.clientMsgId === String(clientMsgId).toLowerCase() && !e.gone)
1649
+ if (closed || !entry || entry.state !== 'failed') return null
1650
+ // A new end for the same message (the earlier `done` already said it failed), in the failed entry's place.
1651
+ return sendingOf(enqueue(entry.conversationId, entry.text, entry.replyToSeq, entry.clientMsgId, entry))
1652
+ },
1653
+ discard(clientMsgId) {
1654
+ const entry = outbox.find((e) => e.clientMsgId === String(clientMsgId).toLowerCase() && !e.gone)
1655
+ if (!entry) return false
1656
+ removeEntry(entry)
1657
+ entry.settle(cancelled())
1658
+ return true
1659
+ },
1660
+ },
1661
+ thread,
1662
+ apply(event) {
1663
+ const effect = dmEventEffect(event)
1664
+ if (closed || effect === 'other') return effect
1665
+ if (event.k === 'resync') {
1666
+ for (const t of [...threads.values()]) t.apply(event)
1667
+ } else if (event.c !== undefined) {
1668
+ threads.get(event.c.toLowerCase())?.apply(event)
1669
+ }
1670
+ return effect
1671
+ },
1672
+ close() {
1673
+ if (closed) return
1674
+ closed = true
1675
+ drafts.clear()
1676
+ for (const entry of [...outbox]) {
1677
+ removeEntry(entry)
1678
+ entry.settle(cancelled())
1679
+ }
1680
+ for (const t of [...threads.values()]) t.close()
1681
+ threads.clear()
1682
+ lastRead.clear()
1683
+ lastTyping.clear()
1684
+ },
1685
+ }
1686
+ return client
1687
+ }