@blogmcp/sdk 0.9.4 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/community/channels.d.ts +7 -6
  2. package/dist/community/channels.js +4 -4
  3. package/dist/community/client.d.ts +74 -4
  4. package/dist/community/client.js +143 -91
  5. package/dist/community/index.d.ts +11 -6
  6. package/dist/community/index.js +111 -80
  7. package/dist/community/links.d.ts +61 -1
  8. package/dist/community/links.js +94 -40
  9. package/dist/community/manifest/index.d.ts +54 -0
  10. package/dist/community/manifest/index.js +46 -0
  11. package/dist/community/mentions.d.ts +38 -0
  12. package/dist/community/mentions.js +25 -0
  13. package/dist/community/messages.cs.d.ts +73 -3
  14. package/dist/community/messages.cs.js +82 -3
  15. package/dist/community/messages.d.ts +11 -0
  16. package/dist/community/messages.en.d.ts +69 -1
  17. package/dist/community/messages.en.js +71 -1
  18. package/dist/community/messages.js +26 -16
  19. package/dist/community/outcome.d.ts +8 -3
  20. package/dist/community/outcome.js +75 -28
  21. package/dist/community/realtime/index.d.ts +118 -0
  22. package/dist/community/realtime/index.js +215 -0
  23. package/dist/community/routes.d.ts +12 -0
  24. package/dist/community/routes.js +41 -25
  25. package/dist/community/server/bff.js +25 -25
  26. package/dist/community/server/host-routes.js +12 -0
  27. package/dist/community/server/index.d.ts +1 -1
  28. package/dist/community/server/index.js +15 -14
  29. package/dist/community/server/route-decision.d.ts +8 -0
  30. package/dist/community/server/route-decision.js +28 -22
  31. package/dist/community/shapes.d.ts +214 -2
  32. package/dist/community/shapes.js +65 -25
  33. package/dist/community/store.d.ts +18 -1
  34. package/dist/community/store.js +316 -261
  35. package/dist/community/sw/index.d.ts +45 -0
  36. package/dist/community/sw/index.js +59 -0
  37. package/dist/community/ua.d.ts +12 -0
  38. package/dist/community/ua.js +9 -0
  39. package/package.json +20 -3
  40. package/src/community/channels.ts +8 -7
  41. package/src/community/client.ts +116 -5
  42. package/src/community/index.ts +59 -1
  43. package/src/community/links.ts +119 -2
  44. package/src/community/manifest/index.ts +107 -0
  45. package/src/community/mentions.ts +59 -0
  46. package/src/community/messages.cs.ts +88 -3
  47. package/src/community/messages.en.ts +77 -1
  48. package/src/community/messages.ts +19 -0
  49. package/src/community/outcome.ts +53 -1
  50. package/src/community/realtime/index.ts +522 -0
  51. package/src/community/routes.ts +16 -0
  52. package/src/community/server/bff.ts +2 -4
  53. package/src/community/server/host-routes.ts +12 -0
  54. package/src/community/server/index.ts +1 -0
  55. package/src/community/server/route-decision.ts +15 -0
  56. package/src/community/shapes.ts +256 -3
  57. package/src/community/store.ts +114 -0
  58. package/src/community/sw/index.ts +112 -0
  59. package/src/community/ua.ts +17 -0
@@ -1,4 +1,4 @@
1
- const I = [
1
+ const T = [
2
2
  /** The host refused the method (a programming error: every operation is a POST). */
3
3
  "method",
4
4
  /** The host refused the request's origin (the page and its API are on different sites). */
@@ -45,13 +45,23 @@ const I = [
45
45
  "notMoved",
46
46
  /** kb-api could not record the change; nothing changed — retry. */
47
47
  "ledger",
48
+ /** The community's extra features are off for now (MyState `module.until` says until when): the discussions under articles keep working, this feature does not. */
49
+ "readOnly",
50
+ /** The community is paused for now (`until` when the pause has an end): reading works, writing does not. */
51
+ "braked",
52
+ /** M2 T3: more @mentions in one message than the member may use yet. */
53
+ "mentionLimit",
54
+ /** M2 T4: the browser's push service is not one the community sends to (or could not be reached): no notifications on this browser. */
55
+ "pushRefused",
56
+ /** M2 T5: live updates are not on here: the discussion keeps itself fresh by polling (pollDiscussionHead). */
57
+ "realtimeOff",
48
58
  /** Anything else: "that did not work, try again". */
49
59
  "submit"
50
- ], n = new Set(I);
51
- function R(E) {
52
- return typeof E == "string" && n.has(E);
60
+ ], D = new Set(T);
61
+ function e(E) {
62
+ return typeof E == "string" && D.has(E);
53
63
  }
54
- const L = [
64
+ const r = [
55
65
  "SURFACE_OFF",
56
66
  "CUTOVER_NOT_MOVED",
57
67
  "NOT_FOUND",
@@ -78,6 +88,19 @@ const L = [
78
88
  "STAFF_POSTING_OFF",
79
89
  "PRESET_CONFLICT",
80
90
  "INTERNAL",
91
+ "MODULE_DARK",
92
+ "MODULE_READ_ONLY",
93
+ "BRAKED",
94
+ "BRAKE_PLATFORM",
95
+ "MODULE_CONDITIONS",
96
+ "TRUST_LEVEL_INVALID",
97
+ "MENTION_LIMIT",
98
+ "DIGEST_UNSUBSCRIBE_INVALID",
99
+ "PUSH_ENDPOINT_REFUSED",
100
+ "PUSH_LIMIT",
101
+ "REALTIME_OFF",
102
+ "BUSY",
103
+ "BRAKE_KIND_MISMATCH",
81
104
  "NOT_A_MEMBER_SESSION",
82
105
  "IDENTITY_NOT_ADMITTED",
83
106
  "ACCOUNT_NOT_ELIGIBLE",
@@ -101,9 +124,10 @@ const L = [
101
124
  "INVALID_INPUT",
102
125
  "LEGAL_HOLD",
103
126
  "TEXT_MISSING",
127
+ "AGE16_NOT_ALLOWED",
104
128
  "QUOTA_DAILY",
105
129
  "QUOTA_IP_HOURLY"
106
- ], t = Object.freeze({
130
+ ], A = Object.freeze({
107
131
  SURFACE_OFF: "surfaceOff",
108
132
  CUTOVER_NOT_MOVED: "notMoved",
109
133
  NOT_FOUND: "notFound",
@@ -132,6 +156,27 @@ const L = [
132
156
  STAFF_POSTING_OFF: "submit",
133
157
  PRESET_CONFLICT: "submit",
134
158
  INTERNAL: "unavailable",
159
+ // M2 (m2-contracts.md §3.1): a Pro surface of a tenant without the module answers as one that is not there.
160
+ MODULE_DARK: "unavailable",
161
+ MODULE_READ_ONLY: "readOnly",
162
+ BRAKED: "braked",
163
+ // The team's and the platform's own refusals: no public operation produces them.
164
+ BRAKE_PLATFORM: "submit",
165
+ MODULE_CONDITIONS: "submit",
166
+ // M2 T2: the team's members/set-trust-level with a level outside 0..3 (no public operation produces it).
167
+ TRUST_LEVEL_INVALID: "invalid",
168
+ // M2 T3 (§3.3): too many @handles for the member's trust level; an unsubscribe link that is not (or no longer) valid.
169
+ MENTION_LIMIT: "mentionLimit",
170
+ DIGEST_UNSUBSCRIBE_INVALID: "invalid",
171
+ // M2 T4 (§3.4): a push endpoint kb-api will not send to; more than 10 subscriptions, or the push quota spent (retryAfterS).
172
+ PUSH_ENDPOINT_REFUSED: "pushRefused",
173
+ PUSH_LIMIT: "quota",
174
+ // M2 T5 (§3.5): the module is neither live nor braked, or live updates are not configured — poll instead.
175
+ REALTIME_OFF: "realtimeOff",
176
+ // F-W0-M4: the team router's lock timeout or deadlock (module/enable's first ranking) — no public operation produces it.
177
+ BUSY: "submit",
178
+ // M2 follow-up F3: the platform's brakes/lift found another kind of brake (no public operation produces it).
179
+ BRAKE_KIND_MISMATCH: "submit",
135
180
  // A session that is not a reader's (the team, a key) or an identity the tenant does not admit: sign in as a reader.
136
181
  NOT_A_MEMBER_SESSION: "signIn",
137
182
  IDENTITY_NOT_ADMITTED: "signIn",
@@ -160,52 +205,54 @@ const L = [
160
205
  LEGAL_HOLD: "submit",
161
206
  // The tenant has not published the text a join needs: the community cannot be joined yet.
162
207
  TEXT_MISSING: "unavailable",
208
+ // M2 T9: the team's settings/update only (the age limit 16 for a tenant its size class does not allow it).
209
+ AGE16_NOT_ALLOWED: "submit",
163
210
  QUOTA_DAILY: "quota",
164
211
  QUOTA_IP_HOURLY: "quota"
165
- }), s = ["METHOD", "ORIGIN", "TOO_LARGE", "INVALID_JSON"], A = Object.freeze({
212
+ }), S = ["METHOD", "ORIGIN", "TOO_LARGE", "INVALID_JSON"], N = Object.freeze({
166
213
  METHOD: "method",
167
214
  ORIGIN: "origin",
168
215
  TOO_LARGE: "invalid",
169
216
  INVALID_JSON: "invalid"
170
- }), N = (E, O) => Object.prototype.hasOwnProperty.call(E, O);
171
- function S(E) {
172
- return typeof E != "string" || E === "" ? "submit" : N(t, E) ? t[E] : N(A, E) ? A[E] : "submit";
217
+ }), I = (E, O) => Object.prototype.hasOwnProperty.call(E, O);
218
+ function s(E) {
219
+ return typeof E != "string" || E === "" ? "submit" : I(A, E) ? A[E] : I(N, E) ? N[E] : "submit";
173
220
  }
174
- const T = /* @__PURE__ */ Symbol.for("@blogmcp/sdk/CommunityTransportError");
175
- function r(E) {
221
+ const t = /* @__PURE__ */ Symbol.for("@blogmcp/sdk/CommunityTransportError");
222
+ function n(E) {
176
223
  return typeof E == "number" && Number.isInteger(E) && E >= 100 && E <= 599 ? E : null;
177
224
  }
178
225
  function i(E) {
179
226
  return typeof E == "number" && Number.isFinite(E) && E >= 0 ? Math.ceil(E) : null;
180
227
  }
181
- class D extends Error {
228
+ class L extends Error {
182
229
  /** The HTTP status, or null when there was no response (network, timeout). */
183
230
  status;
184
231
  /** Seconds to wait before retrying (`Retry-After`), or null. */
185
232
  retryAfterS;
186
233
  constructor(O, _ = {}) {
187
- super(O), this.name = "CommunityTransportError", this.status = r(_.status), this.retryAfterS = i(_.retryAfterS), Object.defineProperty(this, T, { value: !0 });
234
+ super(O), this.name = "CommunityTransportError", this.status = n(_.status), this.retryAfterS = i(_.retryAfterS), Object.defineProperty(this, t, { value: !0 });
188
235
  }
189
236
  }
190
- function e(E) {
191
- return E instanceof D ? !0 : E instanceof Error && E[T] === !0;
237
+ function R(E) {
238
+ return E instanceof L ? !0 : E instanceof Error && E[t] === !0;
192
239
  }
193
240
  function u(E) {
194
- return e(E) && E.retryAfterS !== null ? { ok: !1, code: "unavailable", retryAfterS: E.retryAfterS } : { ok: !1, code: "unavailable" };
241
+ return R(E) && E.retryAfterS !== null ? { ok: !1, code: "unavailable", retryAfterS: E.retryAfterS } : { ok: !1, code: "unavailable" };
195
242
  }
196
- function o(E) {
243
+ function a(E) {
197
244
  return E === "unavailable" || E === "submit" || E === "method" || E === "origin" || E === "invalid" || E === "ledger";
198
245
  }
199
246
  export {
200
- L as COMMUNITY_API_CODES,
201
- s as COMMUNITY_HOST_CODES,
202
- A as COMMUNITY_OUTCOME_OF_HOST,
203
- t as COMMUNITY_OUTCOME_OF_KB,
204
- I as COMMUNITY_UI_CODES,
205
- D as CommunityTransportError,
247
+ r as COMMUNITY_API_CODES,
248
+ S as COMMUNITY_HOST_CODES,
249
+ N as COMMUNITY_OUTCOME_OF_HOST,
250
+ A as COMMUNITY_OUTCOME_OF_KB,
251
+ T as COMMUNITY_UI_CODES,
252
+ L as CommunityTransportError,
206
253
  u as communityFailureOf,
207
- S as communityOutcomeOf,
208
- e as isCommunityTransportError,
209
- R as isCommunityUiCode,
210
- o as isLoggedCommunityOutcome
254
+ s as communityOutcomeOf,
255
+ R as isCommunityTransportError,
256
+ e as isCommunityUiCode,
257
+ a as isLoggedCommunityOutcome
211
258
  };
@@ -0,0 +1,118 @@
1
+ /**
2
+ * `@blogmcp/sdk/community/realtime` — live updates of one article discussion (docs/internal/m2-contracts.md §3.5
3
+ * "The client", §3.10; community.md §7.4). A separate entry with the peer dependency `centrifuge` (≥ 5.7, MIT),
4
+ * optional for the PACKAGE, not for this entry: a host that never imports this entry ships no socket code and needs
5
+ * no `centrifuge`; a host that imports it installs `centrifuge` (a bundler resolves the entry's `import('centrifuge')`
6
+ * at build time and fails without it). Without a bundler, or with the module passed as `centrifuge`, an import that
7
+ * fails at run time keeps the session polling.
8
+ *
9
+ * const session = createRealtimeSession({ client, store }) // after the first discussions/list
10
+ * // on unmount: session.stop()
11
+ *
12
+ * What it does:
13
+ * - asks `me/realtime/token` for a connection token AND the URL to connect to — the only source of that URL (this
14
+ * entry builds none from configuration: the endpoints are `${url}/connection/websocket`, `${url}/connection/
15
+ * http_stream` and `${url}/emulation` of kb-api's answer);
16
+ * - subscribes to `disc:<conversationId>` (the store's conversation, or `channel`) with `realtime/subscribe-token`;
17
+ * Centrifuge asks again when a token expires (`getToken`), and a connection the server ends as unauthorized is
18
+ * opened again with a fresh token (with jitter, a few times);
19
+ * - hands every publication to `store.applyEvent` (the delta by `rev`); an answer `resync`, a `resync` publication,
20
+ * every successful subscribe (the first one and each after a reconnect), the page shown again
21
+ * (`visibilitychange → visible`) and `online` re-read the discussion (refreshDiscussion: the pages loaded);
22
+ * - the viewer's own post is shown by its write's answer (its `clientMsgId`), not by the channel;
23
+ * - a change of the viewer (the store's `viewer.memberId`: a host session's first join turns its `v:` subject into
24
+ * the member) opens the connection again with a fresh token — Centrifugo binds a connection to its user, so the
25
+ * member's tokens would be refused on the visitor's connection, and a disconnect of the member must reach it;
26
+ * - falls back to `pollDiscussionHead` when kb-api answers `realtimeOff` (outside a live or braked module, or where
27
+ * live updates are not configured), `signIn` (an anonymous reader: tokens are for host sessions), a subscribe
28
+ * token is refused, `centrifuge` is not installed, or the server cuts the connection for good;
29
+ * - M2 T10, the watchdog: when the subscription is not live within REALTIME_WATCHDOG_MS (15 s) of connecting — the
30
+ * first time or after the connection dropped (the realtime endpoint unreachable, a proxy that drops the upgrade) — the discussion
31
+ * polls (`polling`) while Centrifuge keeps reconnecting on its own, and goes `live` again (the poller stopped, the
32
+ * discussion re-read) once it subscribes;
33
+ * - M2 T10, a revoked session (the server's 4501: the back channel or a self-service cut-off disconnected the
34
+ * user): `me/realtime/token` is asked ONCE more and the connection opened again only when it answers — a member
35
+ * whose own password change cut the old session keeps a live page under the new one; a refusal, or a second
36
+ * 4501 in this session, polls for good.
37
+ */
38
+ import type { CommunityClient } from '../client.js';
39
+ import { type DiscussionStore } from '../store.js';
40
+ /** A Centrifuge subscription, as far as this entry uses it. */
41
+ export interface RealtimeSubscriptionLike {
42
+ on(event: 'publication' | 'subscribed' | 'unsubscribed' | 'error', listener: (ctx: any) => void): unknown;
43
+ subscribe(): void;
44
+ unsubscribe(): void;
45
+ }
46
+ /** A Centrifuge client, as far as this entry uses it. */
47
+ export interface RealtimeClientLike {
48
+ on(event: 'connected' | 'connecting' | 'disconnected' | 'error', listener: (ctx: any) => void): unknown;
49
+ newSubscription(channel: string, options: {
50
+ getToken: (ctx: {
51
+ channel: string;
52
+ }) => Promise<string>;
53
+ token?: string;
54
+ }): RealtimeSubscriptionLike;
55
+ connect(): void;
56
+ disconnect(): void;
57
+ removeSubscription?(sub: RealtimeSubscriptionLike | null): void;
58
+ }
59
+ export type RealtimeTransportEndpoint = {
60
+ transport: 'websocket' | 'http_stream';
61
+ endpoint: string;
62
+ };
63
+ /** `centrifuge`'s module, as far as this entry uses it (tests pass a fake one). */
64
+ export interface CentrifugeModuleLike {
65
+ Centrifuge: new (endpoints: RealtimeTransportEndpoint[], options: {
66
+ token?: string;
67
+ getToken: () => Promise<string>;
68
+ emulationEndpoint: string;
69
+ name?: string;
70
+ }) => RealtimeClientLike;
71
+ /** Thrown from getToken, it tells Centrifuge to stop (no retry). */
72
+ UnauthorizedError?: new (message?: string) => Error;
73
+ }
74
+ export type RealtimeMode = 'connecting' | 'live' | 'polling' | 'stopped';
75
+ export interface RealtimeSessionOptions {
76
+ client: Pick<CommunityClient, 'discussions' | 'me' | 'realtime'>;
77
+ store: DiscussionStore;
78
+ /**
79
+ * `disc:<conversationId>`; default the store's conversation (a discussion without one polls until it has one). The id
80
+ * is used in lower case (kb-api publishes to, and mints tokens for, the lower-case channel).
81
+ */
82
+ channel?: string;
83
+ /** The discussion's language, for the re-reads (as the page's discussions/list asks). */
84
+ languageCode?: string | null;
85
+ /** The `centrifuge` module, or a loader of it (tests); default `import('centrifuge')`. */
86
+ centrifuge?: CentrifugeModuleLike | (() => Promise<CentrifugeModuleLike>);
87
+ /** Whether the discussion is seen now (default: the document is visible); the fallback polls only then. */
88
+ visible?: () => boolean;
89
+ /** The fallback poller's interval (pollDiscussionHead's default otherwise). */
90
+ pollIntervalMs?: number;
91
+ /** Called on every change of mode. */
92
+ onMode?: (mode: RealtimeMode) => void;
93
+ /** Aborting it stops the session. */
94
+ signal?: AbortSignal;
95
+ }
96
+ export interface RealtimeSession {
97
+ readonly mode: RealtimeMode;
98
+ /** Re-reads the discussion now (coalesced with one already on its way). */
99
+ resync(): Promise<void>;
100
+ /** Ends the session: no socket, no poller, no listener. */
101
+ stop(): void;
102
+ }
103
+ /**
104
+ * How long a connection may take to become live (subscribed) before the discussion polls meanwhile (M2 T10). The
105
+ * poll stops again on the next subscribe; Centrifuge's own reconnects (with its backoff) go on underneath.
106
+ */
107
+ export declare const REALTIME_WATCHDOG_MS = 15000;
108
+ /**
109
+ * The connection URL of kb-api's answer, without a trailing slash — an absolute http(s) URL with no credentials, or
110
+ * null (then the session polls).
111
+ */
112
+ export declare function realtimeUrlOf(url: unknown): string | null;
113
+ /** Centrifuge's endpoints under kb-api's URL (websocket first, http_stream as the fallback). */
114
+ export declare function realtimeEndpointsOf(url: string): {
115
+ endpoints: RealtimeTransportEndpoint[];
116
+ emulationEndpoint: string;
117
+ };
118
+ export declare function createRealtimeSession(options: RealtimeSessionOptions): RealtimeSession;
@@ -0,0 +1,215 @@
1
+ import { COMMUNITY_CHANNELS as le } from "../channels.js";
2
+ import { pollDiscussionHead as J } from "../poll.js";
3
+ import { refreshDiscussion as ce } from "../store.js";
4
+ const se = 15e3, ue = 4501, ae = (e) => typeof e == "number" && (e >= 3500 && e < 4e3 || e >= 4500 && e < 5e3), fe = 3, de = 1e3, A = (e) => typeof e == "object" && e !== null && !Array.isArray(e);
5
+ function me(e) {
6
+ if (typeof e != "string" || e.length > 2048) return null;
7
+ let t;
8
+ try {
9
+ t = new URL(e);
10
+ } catch {
11
+ return null;
12
+ }
13
+ return t.protocol !== "https:" && t.protocol !== "http:" || t.username || t.password || t.search || t.hash ? null : t.href.replace(/\/+$/, "");
14
+ }
15
+ function pe(e) {
16
+ return {
17
+ endpoints: [
18
+ { transport: "websocket", endpoint: `${e.replace(/^http/, "ws")}/connection/websocket` },
19
+ { transport: "http_stream", endpoint: `${e}/connection/http_stream` }
20
+ ],
21
+ emulationEndpoint: `${e}/emulation`
22
+ };
23
+ }
24
+ async function ve(e) {
25
+ try {
26
+ if (typeof e == "function") return await e();
27
+ if (e) return e;
28
+ const t = await import("centrifuge");
29
+ return t && typeof t.Centrifuge == "function" ? t : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+ function he(e) {
35
+ const { client: t, store: d } = e, R = e.visible ?? (() => typeof document > "u" || document.visibilityState !== "hidden");
36
+ let m = "connecting", r = !1, p = null, b = null, l = null, v = null, y = 0, E = null, k = null, M = !1, z = !1, I = null, _ = !1, O = 0, P = d.getState().viewer.memberId, D = null;
37
+ const T = new AbortController(), C = { signal: T.signal }, g = (n) => {
38
+ if (m !== n) {
39
+ m = n;
40
+ try {
41
+ e.onMode?.(n);
42
+ } catch {
43
+ }
44
+ }
45
+ }, H = () => d.getState().articleId;
46
+ async function Q() {
47
+ const n = H();
48
+ !n || r || await ce(d, t, { articleId: n, languageCode: e.languageCode ?? null }, C);
49
+ }
50
+ function w() {
51
+ return r ? Promise.resolve() : I ? (_ = !0, I) : (I = (async () => {
52
+ try {
53
+ do
54
+ _ = !1, await Q();
55
+ while (_ && !r);
56
+ } finally {
57
+ I = null;
58
+ }
59
+ })(), I);
60
+ }
61
+ function N() {
62
+ k && clearTimeout(k), k = null;
63
+ }
64
+ function S() {
65
+ E && clearTimeout(E), E = null, N(), M = !1;
66
+ const n = p;
67
+ p = null;
68
+ const u = b;
69
+ b = null;
70
+ try {
71
+ u?.unsubscribe(), n?.removeSubscription?.(u), n?.disconnect();
72
+ } catch {
73
+ }
74
+ }
75
+ function U() {
76
+ const n = H();
77
+ if (!n || l || r) return;
78
+ const u = {
79
+ visible: R,
80
+ signal: T.signal,
81
+ onChange: (L) => {
82
+ L.some((h) => d.applyHead(h)) && w();
83
+ }
84
+ };
85
+ e.pollIntervalMs !== void 0 && (u.intervalMs = e.pollIntervalMs), l = J(t, [n], u);
86
+ }
87
+ function a() {
88
+ r || (S(), g("polling"), !l && (U(), !l && !v && (v = d.subscribe(() => U()))));
89
+ }
90
+ function $(n) {
91
+ r || M || n !== p || b === null || (N(), k = setTimeout(() => {
92
+ k = null, !(r || n !== p || b === null || m === "live" || m === "polling") && (M = !0, g("polling"), U());
93
+ }, se));
94
+ }
95
+ function Z() {
96
+ N(), M && (M = !1, l?.stop(), l = null), g("live");
97
+ }
98
+ async function x() {
99
+ S(), l?.stop(), l = null, v?.(), v = null, g("connecting");
100
+ const n = O, u = await t.me.realtime.token(C);
101
+ if (!(r || n !== O)) {
102
+ if (!u.ok) return a();
103
+ await V(u.value);
104
+ }
105
+ }
106
+ const j = () => {
107
+ if (typeof e.channel == "string" && e.channel !== "") return e.channel.toLowerCase();
108
+ const n = d.getState().conversationId;
109
+ return n ? le.discussion(n) : null;
110
+ };
111
+ async function V(n) {
112
+ const u = ++O, L = () => u === O && !r, h = await ve(e.centrifuge);
113
+ if (!L()) return;
114
+ if (!h) return a();
115
+ const q = n ? { ok: !0, value: n } : await t.me.realtime.token(C);
116
+ if (!L()) return;
117
+ if (!q.ok) return a();
118
+ const G = me(q.value.url);
119
+ if (!G) return a();
120
+ const K = (i) => h.UnauthorizedError ? new h.UnauthorizedError(i) : new Error(i), ne = async () => {
121
+ const i = await t.me.realtime.token(C);
122
+ if (i.ok) return i.value.token;
123
+ throw i.code === "realtimeOff" || i.code === "signIn" ? (queueMicrotask(a), K(i.code)) : new Error(i.code);
124
+ }, { endpoints: te, emulationEndpoint: re } = pe(G), c = new h.Centrifuge(te, { token: q.value.token, getToken: ne, emulationEndpoint: re, name: "blogmcp-community" });
125
+ p = c, c.on("connected", () => {
126
+ c === p && (y = 0);
127
+ }), c.on("connecting", () => {
128
+ c !== p || r || (m === "live" && g("connecting"), $(c));
129
+ }), c.on("disconnected", (i) => {
130
+ if (c !== p || r) return;
131
+ const s = A(i) ? i.code : void 0;
132
+ if (s === 1 || s === 3500) {
133
+ if (y >= fe) return a();
134
+ y += 1, m === "live" && g("connecting"), $(c);
135
+ const f = de * 2 ** (y - 1) * (0.5 + Math.random());
136
+ E = setTimeout(() => {
137
+ E = null, c === p && !r && c.connect();
138
+ }, f);
139
+ return;
140
+ }
141
+ if (s === ue && !z) {
142
+ z = !0, x().catch(() => a());
143
+ return;
144
+ }
145
+ ae(s) && a();
146
+ });
147
+ const X = (i) => {
148
+ const s = c.newSubscription(i, {
149
+ getToken: async (f) => {
150
+ const o = await t.realtime.subscribeToken({ channel: f?.channel ?? i }, C);
151
+ if (o.ok) return o.value.token;
152
+ throw o.code === "notFound" || o.code === "realtimeOff" || o.code === "signIn" || o.code === "surfaceOff" ? (queueMicrotask(a), K(o.code)) : new Error(o.code);
153
+ }
154
+ });
155
+ b = s, $(c), s.on("publication", (f) => {
156
+ if (s !== b || r) return;
157
+ const o = A(f) ? f.data : void 0;
158
+ A(o) && d.applyEvent(o) === "resync" && w();
159
+ }), s.on("subscribed", () => {
160
+ s !== b || r || (Z(), w());
161
+ }), s.on("unsubscribed", (f) => {
162
+ s !== b || r || A(f) && f.code !== 0 && a();
163
+ }), s.subscribe();
164
+ }, Y = j();
165
+ if (Y) X(Y);
166
+ else {
167
+ const i = d.subscribe(() => {
168
+ const o = j();
169
+ !o || c !== p || r || (i(), l?.stop(), l = null, X(o));
170
+ }), s = v;
171
+ v = () => {
172
+ i(), s?.();
173
+ };
174
+ const f = H();
175
+ if (f) {
176
+ const o = {
177
+ visible: R,
178
+ signal: T.signal,
179
+ onChange: (ie) => {
180
+ ie.some((oe) => d.applyHead(oe)) && w();
181
+ }
182
+ };
183
+ e.pollIntervalMs !== void 0 && (o.intervalMs = e.pollIntervalMs), l = J(t, [f], o);
184
+ }
185
+ }
186
+ c.connect();
187
+ }
188
+ function ee() {
189
+ r || (S(), l?.stop(), l = null, v?.(), v = null, y = 0, g("connecting"), V().catch(() => a()));
190
+ }
191
+ const B = () => {
192
+ R() && m === "live" && w();
193
+ }, F = () => {
194
+ m === "live" && w();
195
+ };
196
+ function W() {
197
+ r || (r = !0, S(), l?.stop(), l = null, v?.(), v = null, D?.(), D = null, T.abort(), typeof document < "u" && document.removeEventListener("visibilitychange", B), typeof window < "u" && window.removeEventListener("online", F), e.signal?.removeEventListener("abort", W), g("stopped"));
198
+ }
199
+ return e.signal?.aborted ? (r = !0, m = "stopped") : (typeof document < "u" && document.addEventListener("visibilitychange", B), typeof window < "u" && window.addEventListener("online", F), e.signal?.addEventListener("abort", W, { once: !0 }), D = d.subscribe((n) => {
200
+ const u = n.viewer.memberId;
201
+ u !== P && (P = u, ee());
202
+ }), V().catch(() => a())), {
203
+ get mode() {
204
+ return m;
205
+ },
206
+ resync: w,
207
+ stop: W
208
+ };
209
+ }
210
+ export {
211
+ se as REALTIME_WATCHDOG_MS,
212
+ he as createRealtimeSession,
213
+ pe as realtimeEndpointsOf,
214
+ me as realtimeUrlOf
215
+ };
@@ -41,6 +41,18 @@ export declare const COMMUNITY_OPS: Readonly<{
41
41
  readonly 'me.updateProfile': CommunityOp<"me.updateProfile">;
42
42
  readonly 'me.notifications.list': CommunityOp<"me.notifications.list">;
43
43
  readonly 'me.notifications.markRead': CommunityOp<"me.notifications.markRead">;
44
+ readonly 'me.notifications.unreadCount': CommunityOp<"me.notifications.unreadCount">;
45
+ readonly 'me.settings.get': CommunityOp<"me.settings.get">;
46
+ readonly 'me.settings.update': CommunityOp<"me.settings.update">;
47
+ readonly 'me.settings.unsubscribeDigest': CommunityOp<"me.settings.unsubscribeDigest">;
48
+ readonly 'me.mutes.set': CommunityOp<"me.mutes.set">;
49
+ readonly 'me.mutes.list': CommunityOp<"me.mutes.list">;
50
+ readonly 'me.push.vapid': CommunityOp<"me.push.vapid">;
51
+ readonly 'me.push.subscribe': CommunityOp<"me.push.subscribe">;
52
+ readonly 'me.push.unsubscribe': CommunityOp<"me.push.unsubscribe">;
53
+ readonly 'me.push.status': CommunityOp<"me.push.status">;
54
+ readonly 'me.realtime.token': CommunityOp<"me.realtime.token">;
55
+ readonly 'realtime.subscribeToken': CommunityOp<"realtime.subscribeToken">;
44
56
  readonly 'me.decisions.list': CommunityOp<"me.decisions.list">;
45
57
  readonly 'me.decisions.get': CommunityOp<"me.decisions.get">;
46
58
  readonly 'me.appeals.file': CommunityOp<"me.appeals.file">;
@@ -1,4 +1,4 @@
1
- const e = (i, s, t) => Object.freeze({ name: i, method: "POST", path: t, surface: s }), n = Object.freeze({
1
+ const e = (i, s, t) => Object.freeze({ name: i, method: "POST", path: t, surface: s }), m = Object.freeze({
2
2
  "discussions.list": e("discussions.list", "public", "/community/v1/public/discussions/list"),
3
3
  "discussions.head": e("discussions.head", "public", "/community/v1/public/discussions/head"),
4
4
  "messages.post": e("messages.post", "public", "/community/v1/public/messages/post"),
@@ -14,6 +14,22 @@ const e = (i, s, t) => Object.freeze({ name: i, method: "POST", path: t, surface
14
14
  "me.updateProfile": e("me.updateProfile", "public", "/community/v1/public/me/profile/update"),
15
15
  "me.notifications.list": e("me.notifications.list", "public", "/community/v1/public/me/notifications/list"),
16
16
  "me.notifications.markRead": e("me.notifications.markRead", "public", "/community/v1/public/me/notifications/mark-read"),
17
+ // M2 T3 (m2-contracts.md §3.3, §5.1): the badge, the member's switches and its mutes.
18
+ "me.notifications.unreadCount": e("me.notifications.unreadCount", "public", "/community/v1/public/me/notifications/unread-count"),
19
+ "me.settings.get": e("me.settings.get", "public", "/community/v1/public/me/settings/get"),
20
+ "me.settings.update": e("me.settings.update", "public", "/community/v1/public/me/settings/update"),
21
+ "me.settings.unsubscribeDigest": e("me.settings.unsubscribeDigest", "public", "/community/v1/public/me/settings/unsubscribe-digest"),
22
+ "me.mutes.set": e("me.mutes.set", "public", "/community/v1/public/me/mutes/set"),
23
+ "me.mutes.list": e("me.mutes.list", "public", "/community/v1/public/me/mutes/list"),
24
+ // M2 T4 (m2-contracts.md §3.4, §5.1): web push — the VAPID key, a browser's subscription, its removal.
25
+ "me.push.vapid": e("me.push.vapid", "public", "/community/v1/public/me/push/vapid"),
26
+ "me.push.subscribe": e("me.push.subscribe", "public", "/community/v1/public/me/push/subscribe"),
27
+ "me.push.unsubscribe": e("me.push.unsubscribe", "public", "/community/v1/public/me/push/unsubscribe"),
28
+ // M2 T10 (m2-contracts.md Appendix A D-M2-10): whether kb-api still holds this browser's subscription for the member.
29
+ "me.push.status": e("me.push.status", "public", "/community/v1/public/me/push/status"),
30
+ // M2 T5 (m2-contracts.md §3.5, §5.1): live updates — the connection token (with the URL to connect to) and a channel's.
31
+ "me.realtime.token": e("me.realtime.token", "public", "/community/v1/public/me/realtime/token"),
32
+ "realtime.subscribeToken": e("realtime.subscribeToken", "public", "/community/v1/public/realtime/subscribe-token"),
17
33
  "me.decisions.list": e("me.decisions.list", "public", "/community/v1/public/me/decisions/list"),
18
34
  "me.decisions.get": e("me.decisions.get", "public", "/community/v1/public/me/decisions/get"),
19
35
  "me.appeals.file": e("me.appeals.file", "public", "/community/v1/public/me/appeals/file"),
@@ -30,37 +46,37 @@ const e = (i, s, t) => Object.freeze({ name: i, method: "POST", path: t, surface
30
46
  "notices.appeal": e("notices.appeal", "notice", "/trust/v1/notices/appeal"),
31
47
  "notices.withdrawAppeal": e("notices.withdrawAppeal", "notice", "/trust/v1/notices/appeal/withdraw")
32
48
  }), c = "/community";
33
- function m(i) {
49
+ function n(i) {
34
50
  return i.surface === "public" && i.path.startsWith(`${c}/`) ? i.path.slice(c.length) : i.path;
35
51
  }
36
- const l = 4e3, u = 2, a = 1e3, p = 4e3, r = 4e3, b = 120, M = 2, _ = 80, d = 280, I = /^[a-z0-9][a-z0-9_]{2,29}$/, N = 30, y = 50, O = 50, T = 200, A = "community_notice", f = "good_faith", g = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
37
- function v() {
52
+ const o = 4e3, l = 2, p = 1e3, a = 4e3, b = 4e3, r = 120, d = 2, M = 80, _ = 280, y = /^[a-z0-9][a-z0-9_]{2,29}$/, g = 30, v = 50, I = 50, N = 200, T = "community_notice", h = "good_faith", O = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
53
+ function f() {
38
54
  const i = globalThis.crypto;
39
55
  if (typeof i?.randomUUID == "function") return i.randomUUID();
40
56
  const s = i.getRandomValues(new Uint8Array(16));
41
57
  s[6] = (s[6] ?? 0) & 15 | 64, s[8] = (s[8] ?? 0) & 63 | 128;
42
- const t = Array.from(s, (o) => o.toString(16).padStart(2, "0")).join("");
58
+ const t = Array.from(s, (u) => u.toString(16).padStart(2, "0")).join("");
43
59
  return `${t.slice(0, 8)}-${t.slice(8, 12)}-${t.slice(12, 16)}-${t.slice(16, 20)}-${t.slice(20)}`;
44
60
  }
45
61
  export {
46
- p as COMMUNITY_APPEAL_MAX,
47
- d as COMMUNITY_BIO_MAX,
48
- g as COMMUNITY_CLIENT_MSG_ID_RE,
49
- _ as COMMUNITY_DISPLAY_NAME_MAX,
50
- M as COMMUNITY_DISPLAY_NAME_MIN,
51
- f as COMMUNITY_GOOD_FAITH,
52
- N as COMMUNITY_HANDLE_CHANGE_DAYS,
53
- I as COMMUNITY_HANDLE_RE,
54
- y as COMMUNITY_HEAD_ARTICLES_MAX,
55
- u as COMMUNITY_MESSAGE_LINKS_MAX,
56
- l as COMMUNITY_MESSAGE_MAX,
57
- r as COMMUNITY_NOTICE_DESCRIPTION_MAX,
58
- A as COMMUNITY_NOTICE_TURNSTILE_ACTION,
59
- b as COMMUNITY_NOTIFIER_NAME_MAX,
60
- n as COMMUNITY_OPS,
61
- O as COMMUNITY_PAGE_SIZE,
62
- T as COMMUNITY_REPLIES_MAX,
63
- a as COMMUNITY_REPORT_NOTE_MAX,
64
- m as communityOpPath,
65
- v as newClientMsgId
62
+ a as COMMUNITY_APPEAL_MAX,
63
+ _ as COMMUNITY_BIO_MAX,
64
+ O as COMMUNITY_CLIENT_MSG_ID_RE,
65
+ M as COMMUNITY_DISPLAY_NAME_MAX,
66
+ d as COMMUNITY_DISPLAY_NAME_MIN,
67
+ h as COMMUNITY_GOOD_FAITH,
68
+ g as COMMUNITY_HANDLE_CHANGE_DAYS,
69
+ y as COMMUNITY_HANDLE_RE,
70
+ v as COMMUNITY_HEAD_ARTICLES_MAX,
71
+ l as COMMUNITY_MESSAGE_LINKS_MAX,
72
+ o as COMMUNITY_MESSAGE_MAX,
73
+ b as COMMUNITY_NOTICE_DESCRIPTION_MAX,
74
+ T as COMMUNITY_NOTICE_TURNSTILE_ACTION,
75
+ r as COMMUNITY_NOTIFIER_NAME_MAX,
76
+ m as COMMUNITY_OPS,
77
+ I as COMMUNITY_PAGE_SIZE,
78
+ N as COMMUNITY_REPLIES_MAX,
79
+ p as COMMUNITY_REPORT_NOTE_MAX,
80
+ n as communityOpPath,
81
+ f as newClientMsgId
66
82
  };