@blogmcp/sdk 0.9.3 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) 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 +72 -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/dist/packages/mdx-render-vue/dist/node_modules/dompurify/dist/purify.es.js +1342 -484
  40. package/dist/packages/tripmap-core/dist/generated/maplibre-worker.bundle.js +1 -1
  41. package/package.json +21 -3
  42. package/src/community/channels.ts +8 -7
  43. package/src/community/client.ts +116 -5
  44. package/src/community/index.ts +59 -1
  45. package/src/community/links.ts +119 -2
  46. package/src/community/manifest/index.ts +107 -0
  47. package/src/community/mentions.ts +59 -0
  48. package/src/community/messages.cs.ts +88 -3
  49. package/src/community/messages.en.ts +77 -1
  50. package/src/community/messages.ts +19 -0
  51. package/src/community/outcome.ts +50 -1
  52. package/src/community/realtime/index.ts +522 -0
  53. package/src/community/routes.ts +16 -0
  54. package/src/community/server/bff.ts +2 -4
  55. package/src/community/server/host-routes.ts +12 -0
  56. package/src/community/server/index.ts +1 -0
  57. package/src/community/server/route-decision.ts +15 -0
  58. package/src/community/shapes.ts +256 -3
  59. package/src/community/store.ts +114 -0
  60. package/src/community/sw/index.ts +112 -0
  61. package/src/community/ua.ts +17 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blogmcp/sdk",
3
- "version": "0.9.3",
3
+ "version": "0.10.0",
4
4
  "description": "Headless SDK for Knowledge Base blog — core client, Vue composables, Nuxt adapter",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -47,6 +47,18 @@
47
47
  "./community/server": {
48
48
  "types": "./dist/community/server/index.d.ts",
49
49
  "import": "./dist/community/server/index.js"
50
+ },
51
+ "./community/sw": {
52
+ "types": "./dist/community/sw/index.d.ts",
53
+ "import": "./dist/community/sw/index.js"
54
+ },
55
+ "./community/manifest": {
56
+ "types": "./dist/community/manifest/index.d.ts",
57
+ "import": "./dist/community/manifest/index.js"
58
+ },
59
+ "./community/realtime": {
60
+ "types": "./dist/community/realtime/index.d.ts",
61
+ "import": "./dist/community/realtime/index.js"
50
62
  }
51
63
  },
52
64
  "main": "./dist/core/index.js",
@@ -66,11 +78,15 @@
66
78
  "postpack": "node scripts/postpack.mjs"
67
79
  },
68
80
  "peerDependencies": {
81
+ "centrifuge": ">=5.7.0",
69
82
  "react": ">=18",
70
83
  "react-dom": ">=18",
71
84
  "vue": "^3.4.0"
72
85
  },
73
86
  "peerDependenciesMeta": {
87
+ "centrifuge": {
88
+ "optional": true
89
+ },
74
90
  "react": {
75
91
  "optional": true
76
92
  },
@@ -82,8 +98,8 @@
82
98
  }
83
99
  },
84
100
  "dependencies": {
85
- "@blogmcp/mdx-schema": "^0.9.3",
86
- "@blogmcp/sanitize": "^0.9.3",
101
+ "@blogmcp/mdx-schema": "^0.10.0",
102
+ "@blogmcp/sanitize": "^0.10.0",
87
103
  "marked": "^15.0.7"
88
104
  },
89
105
  "optionalDependencies": {
@@ -96,8 +112,10 @@
96
112
  "@types/react-dom": "^18.3.0",
97
113
  "@vitejs/plugin-vue": "^6.0.0",
98
114
  "@vue/test-utils": "^2.4.0",
115
+ "centrifuge": "^5.8.0",
99
116
  "graphql": "^16.12.0",
100
117
  "happy-dom": "^17.4.0",
118
+ "jsdom": "^25.0.1 || ^26.0.0 || ^27.0.0 || ^28.0.0 || ^29.0.0 || ^30.0.0",
101
119
  "react": "^18.3.0",
102
120
  "react-dom": "^18.3.0",
103
121
  "typescript": "^5.3.3",
@@ -1,12 +1,13 @@
1
1
  /**
2
- * The realtime channel names, reserved now so the later realtime (M2) adds on without renaming anything
3
- * (docs/internal/m1-contracts.md §10.2; community.md §3.7, §7.4). Constants only: M1 opens no socket — a
4
- * discussion is kept fresh by pollDiscussionHead.
2
+ * The realtime channel names (docs/internal/m2-contracts.md §3.5; community.md §3.7, §7.4). Centrifugo v6 refuses
3
+ * one-letter namespace names (`^[-a-zA-Z0-9_.]{2,}$`), so M1's reserved `d:` and `u:` became `disc:` and `user:`
4
+ * before anything used them.
5
5
  *
6
- * `d:<conversationId>` carries a public discussion's projection; `u:inbox` is the member's own channel (ids and
7
- * codes only, community.md invariant 6).
6
+ * `disc:<conversationId>` carries a public discussion's projection (`@blogmcp/sdk/community/realtime` subscribes to
7
+ * it); `user:` is reserved for the member's own inbox of the private surfaces (ids and codes only, invariant 6) —
8
+ * nothing mints a token for it in M2.
8
9
  */
9
10
  export const COMMUNITY_CHANNELS = Object.freeze({
10
- discussion: (conversationId: string): string => `d:${conversationId}`,
11
- inbox: 'u:inbox',
11
+ discussion: (conversationId: string): string => `disc:${conversationId}`,
12
+ inbox: 'user:inbox',
12
13
  } as const)
@@ -38,6 +38,18 @@ import {
38
38
  type KnownNeed,
39
39
  type LegalTextKind,
40
40
  type MemberExport,
41
+ type MemberSettings,
42
+ type MemberSettingsUpdate,
43
+ type MuteEntry,
44
+ type MuteTargetKind,
45
+ type NotificationListInput,
46
+ type PushStatusAnswer,
47
+ type PushSubscribeAnswer,
48
+ type PushSubscribeInput,
49
+ type PushUnsubscribeAnswer,
50
+ type PushVapidKey,
51
+ type RealtimeSubscribeToken,
52
+ type RealtimeToken,
41
53
  type MessageEditInput,
42
54
  type MessagePostInput,
43
55
  type MessageReportInput,
@@ -120,8 +132,48 @@ export interface CommunityClient {
120
132
  onboard: Call<OnboardInput, MyState>
121
133
  updateProfile: Call<ProfileUpdateInput, { profile: OwnProfile }>
122
134
  notifications: {
123
- list: CallOptionalInput<{ cursor?: string | null }, CommunityPage<NotificationItem>>
124
- markRead: Call<{ ids: readonly string[] }, { updated: number }>
135
+ /** Newest first; M2 T3: `unreadOnly`, `codes` filter the centre. */
136
+ list: CallOptionalInput<NotificationListInput, CommunityPage<NotificationItem>>
137
+ /** The given ids, or `{ all: true }`: every unread one of the member's. */
138
+ markRead: Call<{ ids: readonly string[] } | { all: true }, { updated: number }>
139
+ /** M2 T3: the badge's number — a count only (poll it every 60 s while the page is visible). */
140
+ unreadCount: CallNoInput<{ count: number }>
141
+ }
142
+ /** M2 T3: the member's notification switches. */
143
+ settings: {
144
+ get: CallNoInput<{ settings: MemberSettings }>
145
+ /** The switches given change; the others keep their value. */
146
+ update: Call<MemberSettingsUpdate, { settings: MemberSettings }>
147
+ /**
148
+ * The digest's unsubscribe link (the `kbun_` token from the mail link's fragment): no session needed — it can
149
+ * only switch that member's digest off. A forged or stale token is `invalid`.
150
+ */
151
+ unsubscribeDigest: Call<{ token: string }, { unsubscribed: true }>
152
+ }
153
+ /** M2 T3: private, one-sided mutes — a muted discussion or member sends the member no notification. */
154
+ mutes: {
155
+ set: Call<{ targetKind: MuteTargetKind; targetId: string; muted: boolean }, { targetKind: MuteTargetKind; targetId: string; muted: boolean }>
156
+ list: CallNoInput<{ items: MuteEntry[] }>
157
+ }
158
+ /**
159
+ * M2 T4: web push — the VAPID key for `pushManager.subscribe`, the browser's subscription, its removal. Only
160
+ * after the member's click („Zapnout upozornění"), never on page load. An endpoint kb-api will not send to is
161
+ * `pushRefused`; more than 10 browsers, or too many new ones today, `quota`. `unsubscribe` is never refused.
162
+ * `status` (M2 T10, D-M2-10): whether kb-api still holds this browser's subscription (its `endpoint`) for the
163
+ * member viewing — read on load before the switch shows on; it never answers an endpoint and never subscribes.
164
+ */
165
+ push: {
166
+ vapid: CallNoInput<PushVapidKey>
167
+ subscribe: Call<PushSubscribeInput, PushSubscribeAnswer>
168
+ unsubscribe: Call<{ endpoint: string }, PushUnsubscribeAnswer>
169
+ status: Call<{ endpoint: string }, PushStatusAnswer>
170
+ }
171
+ /**
172
+ * M2 T5: the token community-rt takes and the URL to connect to (`realtimeOff` outside a live or braked module,
173
+ * or where live updates are not configured: poll instead). `@blogmcp/sdk/community/realtime` calls it.
174
+ */
175
+ realtime: {
176
+ token: CallNoInput<RealtimeToken>
125
177
  }
126
178
  decisions: {
127
179
  list: CallOptionalInput<{ cursor?: string | null }, CommunityPage<DecisionSummary>>
@@ -149,6 +201,10 @@ export interface CommunityClient {
149
201
  legal: {
150
202
  current: Call<{ kind: LegalTextKind; locale: string }, CurrentLegalText>
151
203
  }
204
+ /** M2 T5: a channel's token — `disc:<conversationId>` of a discussion the viewer may read, else `notFound`. */
205
+ realtime: {
206
+ subscribeToken: Call<{ channel: string }, RealtimeSubscribeToken>
207
+ }
152
208
  notices: {
153
209
  /** Anyone, with or without a session; `confirmations` must hold COMMUNITY_GOOD_FAITH. */
154
210
  submit: Call<NoticeSubmitInput, NoticeReceipt>
@@ -219,6 +275,18 @@ export const COMMUNITY_ANSWER_FIELDS: Readonly<Record<CommunityOpName, Readonly<
219
275
  'me.updateProfile': fieldsOfAnswer({ profile: 'record' }),
220
276
  'me.notifications.list': fieldsOfAnswer({ items: 'array' }),
221
277
  'me.notifications.markRead': fieldsOfAnswer({ updated: 'number' }),
278
+ 'me.notifications.unreadCount': fieldsOfAnswer({ count: 'number' }),
279
+ 'me.settings.get': fieldsOfAnswer({ settings: 'record' }),
280
+ 'me.settings.update': fieldsOfAnswer({ settings: 'record' }),
281
+ 'me.settings.unsubscribeDigest': fieldsOfAnswer({ unsubscribed: 'boolean' }),
282
+ 'me.mutes.set': fieldsOfAnswer({ muted: 'boolean' }),
283
+ 'me.mutes.list': fieldsOfAnswer({ items: 'array' }),
284
+ 'me.push.vapid': fieldsOfAnswer({ publicKey: 'string', keyId: 'string' }),
285
+ 'me.push.subscribe': fieldsOfAnswer({ subscribed: 'boolean', keyId: 'string' }),
286
+ 'me.push.unsubscribe': fieldsOfAnswer({ unsubscribed: 'boolean' }),
287
+ 'me.push.status': fieldsOfAnswer({ subscribed: 'boolean' }),
288
+ 'me.realtime.token': fieldsOfAnswer({ token: 'string', url: 'string', expiresInS: 'number' }),
289
+ 'realtime.subscribeToken': fieldsOfAnswer({ token: 'string' }),
222
290
  'me.decisions.list': fieldsOfAnswer({ items: 'array' }),
223
291
  'me.decisions.get': fieldsOfAnswer({ decisionId: 'string' }),
224
292
  'me.appeals.file': fieldsOfAnswer({ appealId: 'string' }),
@@ -275,6 +343,13 @@ function fieldsOf(value: unknown): string[] | undefined {
275
343
  return paths.slice(0, MAX_LIST)
276
344
  }
277
345
 
346
+ /** The codes of a VALIDATION's issues (`{ path, code }`), as codes; an issue without one gives none. */
347
+ function issueCodesOf(value: unknown): string[] | undefined {
348
+ if (!isArray(value)) return undefined
349
+ const codes = value.map((i) => (isRecord(i) ? i.code : undefined)).filter((c): c is string => isString(c) && CODE_RE.test(c))
350
+ return codes.length > 0 ? [...new Set(codes)].slice(0, MAX_LIST) : undefined
351
+ }
352
+
278
353
  function secondsOf(value: unknown): number | undefined {
279
354
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.ceil(value) : undefined
280
355
  }
@@ -291,6 +366,8 @@ function refusalOf(body: Rec, answer: CommunityTransportAnswer): CommunityFailur
291
366
  if (isString(body.until)) out.until = body.until
292
367
  const fields = fieldsOf(body.issues)
293
368
  if (fields) out.fields = fields
369
+ const issueCodes = issueCodesOf(body.issues)
370
+ if (issueCodes) out.issueCodes = issueCodes
294
371
  return out
295
372
  }
296
373
 
@@ -392,12 +469,43 @@ export function createCommunityClient(config: CommunityClientConfig): CommunityC
392
469
  },
393
470
  me: {
394
471
  get: empty('me.get'),
395
- onboard: fields('me.onboard', ['ageBand', 'rulesTextId', 'art9TextId', 'displayName', 'handle', 'avatarPreset']),
472
+ onboard: fields('me.onboard', ['ageBand', 'rulesTextId', 'art9TextId', 'art9Refused', 'displayName', 'handle', 'avatarPreset']),
396
473
  updateProfile: fields('me.updateProfile', ['displayName', 'handle', 'avatarPreset', 'bio']),
397
474
  notifications: {
398
- list: fields('me.notifications.list', ['cursor']),
475
+ list: fields('me.notifications.list', ['cursor', 'unreadOnly', 'codes']),
399
476
  markRead: (input, options) =>
400
- call('me.notifications.markRead', { ids: isRecord(input) && isArray(input.ids) ? [...input.ids] : [] }, options),
477
+ call(
478
+ 'me.notifications.markRead',
479
+ isRecord(input) && 'all' in input ? { all: input.all } : { ids: isRecord(input) && isArray(input.ids) ? [...input.ids] : [] },
480
+ options,
481
+ ),
482
+ unreadCount: empty('me.notifications.unreadCount'),
483
+ },
484
+ settings: {
485
+ get: empty('me.settings.get'),
486
+ update: fields('me.settings.update', ['notifyReply', 'notifyMention', 'notifyTopic', 'pushEnabled', 'digestEmail', 'quietHours']),
487
+ unsubscribeDigest: fields('me.settings.unsubscribeDigest', ['token']),
488
+ },
489
+ mutes: {
490
+ set: fields('me.mutes.set', ['targetKind', 'targetId', 'muted']),
491
+ list: empty('me.mutes.list'),
492
+ },
493
+ push: {
494
+ vapid: empty('me.push.vapid'),
495
+ subscribe: (input, options) =>
496
+ call(
497
+ 'me.push.subscribe',
498
+ {
499
+ ...pick(input, ['endpoint', 'userAgentClass']),
500
+ ...(isRecord(input) && isRecord(input.keys) ? { keys: pick(input.keys, ['p256dh', 'auth']) } : {}),
501
+ },
502
+ options,
503
+ ),
504
+ unsubscribe: fields('me.push.unsubscribe', ['endpoint']),
505
+ status: fields('me.push.status', ['endpoint']),
506
+ },
507
+ realtime: {
508
+ token: empty('me.realtime.token'),
401
509
  },
402
510
  decisions: {
403
511
  list: fields('me.decisions.list', ['cursor']),
@@ -421,6 +529,9 @@ export function createCommunityClient(config: CommunityClientConfig): CommunityC
421
529
  legal: {
422
530
  current: fields('legal.current', ['kind', 'locale']),
423
531
  },
532
+ realtime: {
533
+ subscribeToken: fields('realtime.subscribeToken', ['channel']),
534
+ },
424
535
  notices: {
425
536
  submit: (input, options) => {
426
537
  const body = pick(input, ['category', 'target', 'description', 'ruleId', 'turnstileToken', 'confirmations'])
@@ -7,7 +7,9 @@
7
7
  * createDiscussionStore the immutable two-level thread, optimistic writes, open enums skipped;
8
8
  * pollDiscussionHead the polling signal while the discussion is visible (no realtime in M1);
9
9
  * communityMessage every text, cs and en, under the tone test;
10
- * links statements, the panel, the notifier's receipt in the fragment.
10
+ * links statements, the panel, the notifier's receipt in the fragment; M2: profiles, the
11
+ * module's pages and the digest's unsubscribe token in the fragment;
12
+ * communityMentionSpans `@handle` in a body as text spans a page links (never HTML).
11
13
  *
12
14
  * Browser-safe: nothing here takes a key, a session, a cookie or an IP, and nothing imports `node:*`. This entry
13
15
  * never reaches the server entries (`@blogmcp/sdk/community/server`, `@blogmcp/sdk/consultations/server`), the
@@ -65,6 +67,8 @@ export type {
65
67
  } from './outcome'
66
68
 
67
69
  export { fetchTransport, isRelativeCommunityBase, assertCommunityBase, communityOpUrl } from './transport'
70
+ // M2 T4 (m2-contracts.md §3.4): the one user-agent sniff — Facebook's and Instagram's in-app browsers take no push.
71
+ export { isInAppBrowser, IN_APP_BROWSER_RE } from './ua'
68
72
  export type { CommunityTransport, CommunityTransportAnswer, FetchTransportOptions } from './transport'
69
73
 
70
74
  export {
@@ -73,6 +77,10 @@ export {
73
77
  NEEDS,
74
78
  RESTRICTION_KINDS,
75
79
  NOTIFICATION_CODES,
80
+ MODULE_STATES,
81
+ MUTE_TARGET_KINDS,
82
+ PUSH_USER_AGENT_CLASSES,
83
+ REALTIME_EVENT_KINDS,
76
84
  CASE_CATEGORIES,
77
85
  CATEGORY_WITHOUT_NOTIFIER,
78
86
  AGE_BANDS,
@@ -83,9 +91,18 @@ export {
83
91
  isKnownNeed,
84
92
  isKnownRestrictionKind,
85
93
  isKnownNotificationCode,
94
+ isKnownModuleState,
86
95
  isCaseCategory,
87
96
  communityRulesOf,
88
97
  communityLegalSectionsOf,
98
+ ART9_CONSENT_LAYOUTS,
99
+ ART9_REFUSALS,
100
+ ART9_CONTROLLERS_MAX,
101
+ art9ConsentLayoutOf,
102
+ art9RefusalOf,
103
+ art9ControllersOf,
104
+ TRUST_LABELS,
105
+ isKnownTrustLabel,
89
106
  } from './shapes'
90
107
  export type {
91
108
  KnownMessageState,
@@ -98,6 +115,27 @@ export type {
98
115
  RestrictionKind,
99
116
  KnownNotificationCode,
100
117
  NotificationCode,
118
+ KnownModuleState,
119
+ ModuleState,
120
+ KnownTrustLabel,
121
+ TrustLabel,
122
+ ModuleInfo,
123
+ MemberSettings,
124
+ MemberSettingsUpdate,
125
+ MuteEntry,
126
+ MuteTargetKind,
127
+ NotificationListInput,
128
+ PushUserAgentClass,
129
+ PushVapidKey,
130
+ RealtimeToken,
131
+ RealtimeSubscribeToken,
132
+ RealtimeEvent,
133
+ RealtimeEventKind,
134
+ PushSubscribeInput,
135
+ PushSubscribeAnswer,
136
+ PushUnsubscribeAnswer,
137
+ PushStatusAnswer,
138
+ MemberCaps,
101
139
  CaseCategory,
102
140
  AgeBand,
103
141
  LegalTextKind,
@@ -131,6 +169,10 @@ export type {
131
169
  CurrentLegalText,
132
170
  CommunityRule,
133
171
  CommunityLegalSection,
172
+ Art9ConsentLayout,
173
+ Art9Refusal,
174
+ Art9Controller,
175
+ CommunityConsentSettings,
134
176
  MemberExport,
135
177
  NoticeTarget,
136
178
  NoticeReceipt,
@@ -156,6 +198,7 @@ export {
156
198
  } from './store'
157
199
  export type {
158
200
  DiscussionStore,
201
+ RealtimeEventOutcome,
159
202
  DiscussionState,
160
203
  DiscussionMessage,
161
204
  DiscussionViewer,
@@ -178,8 +221,21 @@ export {
178
221
  signInLink,
179
222
  receiptFromHash,
180
223
  readReceiptFromHash,
224
+ profilePath,
225
+ COMMUNITY_MESSAGE_ANCHOR_PREFIX,
226
+ communityMessageAnchor,
227
+ communityMessageSeqFromHash,
228
+ communityMessageLink,
229
+ COMMUNITY_DIGEST_TOKEN_RE,
230
+ digestTokenFromHash,
231
+ readDigestTokenFromHash,
232
+ forgetDigestToken,
181
233
  } from './links'
182
234
 
235
+ // M2 T8 (m2-contracts.md §3.3): `@handle` in a body as spans — text, and mentions a page links to profilePath.
236
+ export { COMMUNITY_MENTION_RE, communityMentionSpans, communityMentionHandles } from './mentions'
237
+ export type { CommunityTextSpan } from './mentions'
238
+
183
239
  export {
184
240
  COMMUNITY_MESSAGES,
185
241
  communityMessage,
@@ -188,5 +244,7 @@ export {
188
244
  warningMessageKey,
189
245
  confirmMessageKey,
190
246
  noteMessageKey,
247
+ notificationMessageKey,
248
+ trustLabelMessageKey,
191
249
  } from './messages'
192
250
  export type { CommunityMessageKey, CommunityMessageLanguage } from './messages'
@@ -9,9 +9,15 @@
9
9
  * takes them as attributes. Without them the managed blog's pages apply, COMMUNITY_ROUTES — the paths kb-api's
10
10
  * deliveries fall back to (a drift spec pins them to kb-api's).
11
11
  *
12
- * Browser-safe; readReceiptFromHash is the one function that touches `window` (on call, never on import).
12
+ * M2 T8: the module's pages (profile, settings, welcome, notifications, discussions) and the digest's unsubscribe
13
+ * token, which travels in the fragment of the settings page's link (`#u=<kbun_…>`) by the receipt's rule.
14
+ *
15
+ * Browser-safe; readReceiptFromHash and readDigestTokenFromHash are the functions that touch `window` (on call,
16
+ * never on import).
13
17
  */
14
18
 
19
+ import { COMMUNITY_HANDLE_RE } from './routes'
20
+
15
21
  /**
16
22
  * The managed blog's community pages (router-relative; the blog prepends its own base). The three legal pages —
17
23
  * `rules`, `terms`, `privacy` — are each the tenant's current `legal/current` text of that kind, rendered by the blog's
@@ -32,6 +38,17 @@ export const COMMUNITY_ROUTES = Object.freeze({
32
38
  terms: '/community/terms',
33
39
  /** The discussion privacy notice, rendered the same way. */
34
40
  privacy: '/community/privacy',
41
+ // M2 T8 (m2-contracts.md §3.10, §3.3): the module's pages. The storefront names its own (`/komunita/…`).
42
+ /** The discussions overview (the articles with a discussion). */
43
+ discussions: '/community/discussions',
44
+ /** A member's public profile; `{handle}` is the member's handle (profilePath). */
45
+ profile: '/community/u/{handle}',
46
+ /** The member's notification settings — also where the digest's unsubscribe link lands (`#u=<token>`). */
47
+ settings: '/community/settings',
48
+ /** The welcome page after joining: the rules' summary and three links. */
49
+ welcome: '/community/welcome',
50
+ /** The notification centre (kb-api's fallback for `notifications_link_path`). */
51
+ notifications: '/community/notifications',
35
52
  } as const)
36
53
 
37
54
  /** A decision's id (kb-api's UUIDs). */
@@ -60,6 +77,56 @@ export function statementPath(template: string | null | undefined, decisionId: s
60
77
  return t.split('{id}').join(decisionId.toLowerCase())
61
78
  }
62
79
 
80
+ /**
81
+ * A member's profile page: `{handle}` of the template filled with the handle (lower-cased; a leading `@` is dropped).
82
+ * The template is the host's (its `profilePath` attribute); absent, the managed blog's. Null for a handle that is no
83
+ * handle, or a template that is no site path, lacks `{handle}` or holds another brace — no link from arbitrary text.
84
+ */
85
+ export function profilePath(template: string | null | undefined, handle: string): string | null {
86
+ const t = template === null || template === undefined || template === '' ? COMMUNITY_ROUTES.profile : template
87
+ if (!isSitePath(t) || !t.includes('{handle}') || /[{}]/.test(t.split('{handle}').join(''))) return null
88
+ const h = typeof handle === 'string' ? handle.replace(/^@/, '').toLowerCase() : ''
89
+ if (!COMMUNITY_HANDLE_RE.test(h)) return null
90
+ return t.split('{handle}').join(h)
91
+ }
92
+
93
+ /**
94
+ * M2 T10: the id `<blogmcp-discussion>` gives a message's row — `bcm-msg-<seq>` (the seq is the message's number in
95
+ * its conversation, the same for every reader) — and the fragment a link to that message carries. The element
96
+ * renders in a shadow root, so it scrolls to the row itself once its first page is in (the browser cannot).
97
+ */
98
+ export const COMMUNITY_MESSAGE_ANCHOR_PREFIX = 'bcm-msg-'
99
+
100
+ const isSeq = (seq: unknown): seq is number => typeof seq === 'number' && Number.isSafeInteger(seq) && seq > 0
101
+
102
+ /** A message's anchor id (`bcm-msg-12`), or null for anything that is not a message's seq (a pending row's 0). */
103
+ export function communityMessageAnchor(seq: number): string | null {
104
+ return isSeq(seq) ? `${COMMUNITY_MESSAGE_ANCHOR_PREFIX}${seq}` : null
105
+ }
106
+
107
+ /** The seq of a message anchor in a URL fragment (`#bcm-msg-12`), or null — nothing else of the fragment is read. */
108
+ export function communityMessageSeqFromHash(hash: string): number | null {
109
+ const m = new RegExp(`^#${COMMUNITY_MESSAGE_ANCHOR_PREFIX}([1-9][0-9]{0,14})$`).exec(typeof hash === 'string' ? hash : '')
110
+ const seq = m ? Number(m[1]) : NaN
111
+ return isSeq(seq) ? seq : null
112
+ }
113
+
114
+ /**
115
+ * M2 T10: a message on its article's page — the host's article template (`articlePath`, one `{slug}`: the managed
116
+ * blogs `/blog/articles/{slug}`, the storefront `/blog/{slug}`) filled with the article's slug (URL-encoded), and the
117
+ * message's anchor in the fragment. No default: null without a template, for a template that is no site path, holds
118
+ * a fragment, lacks `{slug}` or holds another brace, and for a slug or seq that is none — no link from arbitrary text.
119
+ */
120
+ export function communityMessageLink(articlePath: string | null | undefined, articleSlug: string | null | undefined, seq: number | null | undefined): string | null {
121
+ const t = articlePath
122
+ if (!isSitePath(t) || t.includes('#') || !t.includes('{slug}') || /[{}]/.test(t.split('{slug}').join(''))) return null
123
+ if (typeof articleSlug !== 'string' || articleSlug === '' || articleSlug.length > 512 || articleSlug === '.' || articleSlug === '..') return null
124
+ if (/[\u0000-\u001f\u007f]/.test(articleSlug)) return null
125
+ const anchor = communityMessageAnchor(seq as number)
126
+ if (anchor === null) return null
127
+ return `${t.split('{slug}').join(encodeURIComponent(articleSlug))}#${anchor}`
128
+ }
129
+
63
130
  /** The „Moje komunita" page: the host's path when it is a site path, else the managed blog's. */
64
131
  export function myCommunityPath(path?: string | null): string {
65
132
  return isSitePath(path) ? path : COMMUNITY_ROUTES.myCommunity
@@ -104,7 +171,7 @@ const receipts = new WeakMap<Window, string | null>()
104
171
  function browserWindow(): Window {
105
172
  if (typeof window === 'undefined') {
106
173
  throw new Error(
107
- '[blogmcp-sdk] readReceiptFromHash reads the address bar — call it in the browser (onMounted / useEffect), ' +
174
+ '[blogmcp-sdk] readReceiptFromHash and readDigestTokenFromHash read the address bar — call them in the browser (onMounted / useEffect), ' +
108
175
  'never while rendering on the server',
109
176
  )
110
177
  }
@@ -172,3 +239,53 @@ export function readReceiptFromHash(win: Window = browserWindow()): string | nul
172
239
  if (first || fresh !== null) receipts.set(win, fresh)
173
240
  return receipts.get(win) ?? null
174
241
  }
242
+
243
+ // ───────────────────────── the digest's unsubscribe link (M2 T3, m2-contracts.md §3.3, §9.3) ─────────────────────────
244
+
245
+ /** The digest's unsubscribe token: kb-api's `kbun_` capability (DIGEST_TOKEN_RE: 64 base64url characters). */
246
+ export const COMMUNITY_DIGEST_TOKEN_RE = /^kbun_[A-Za-z0-9_-]{64}$/
247
+
248
+ /** The fragment key of the unsubscribe token (`#u=…`), kb-api's UNSUBSCRIBE_FRAGMENT_KEY. */
249
+ const DIGEST_TOKEN_KEY = 'u'
250
+
251
+ /**
252
+ * The unsubscribe token in a URL fragment (`#u=<token>`, the digest e-mail's link to the settings page), or null.
253
+ * Only kb-api's exact token shape is accepted, as receiptFromHash does for a receipt.
254
+ */
255
+ export function digestTokenFromHash(hash: string): string | null {
256
+ const match = /^#u=([^&]*)/.exec(typeof hash === 'string' ? hash : '')
257
+ const token = match?.[1] ?? ''
258
+ return COMMUNITY_DIGEST_TOKEN_RE.test(token) ? token : null
259
+ }
260
+
261
+ /** The unsubscribe token each window's address bar carried, read once. */
262
+ const digestTokens = new WeakMap<Window, string | null>()
263
+
264
+ /**
265
+ * The digest's unsubscribe token from the address bar, which is then cleared of it (the URL and the router's copy in
266
+ * `history.state`), as readReceiptFromHash does for a receipt — the token switches the member's digest off, so it
267
+ * stays out of the history, a bookmark and a shared link. Remembered per window (a second mount still gets it)
268
+ * until forgetDigestToken — call it once the token was used, so a later mount does not offer the unsubscribe again.
269
+ *
270
+ * Reading it never sends it: the page POSTs `me.settings.unsubscribeDigest({ token })` only on the member's click
271
+ * (a mail scanner that opens the link must not unsubscribe anyone). ⚠️ In a vue-router app follow it with
272
+ * `router.replace({ hash: '' })`.
273
+ */
274
+ export function readDigestTokenFromHash(win: Window = browserWindow()): string | null {
275
+ const hash = win.location.hash
276
+ const fresh = digestTokenFromHash(hash)
277
+ const first = !digestTokens.has(win)
278
+ if (hash.startsWith(`#${DIGEST_TOKEN_KEY}=`)) {
279
+ win.history.replaceState(scrubbedState(win.history.state, hash, fresh), '', win.location.pathname + win.location.search)
280
+ }
281
+ if (first || fresh !== null) digestTokens.set(win, fresh)
282
+ return digestTokens.get(win) ?? null
283
+ }
284
+
285
+ /**
286
+ * Forgets the window's remembered unsubscribe token (after `me.settings.unsubscribeDigest` answered, either way: the
287
+ * token is single-purpose). The next readDigestTokenFromHash reads the address bar afresh — which it cleared.
288
+ */
289
+ export function forgetDigestToken(win: Window = browserWindow()): void {
290
+ digestTokens.delete(win)
291
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * `@blogmcp/sdk/community/manifest` — the web app manifest that lets a member install the site (community M2,
3
+ * slice T4; docs/internal/m2-contracts.md §3.4; community.md §7.5: iOS shows web push only to a website added to
4
+ * the home screen).
5
+ *
6
+ * A host serves `JSON.stringify(communityManifest(…))` from `<base>/manifest.webmanifest` as
7
+ * COMMUNITY_MANIFEST_CONTENT_TYPE and links it from its pages (`<link rel="manifest">`). `display: standalone`, the
8
+ * start URL is the notification centre, the scope is the site's base (the managed blogs' `/blog/`, the
9
+ * storefront's `/`), so an installed app opens where a notification would.
10
+ *
11
+ * Pure: no DOM, no globals, no import.
12
+ */
13
+
14
+ /** The Content-Type a host serves the manifest with. */
15
+ export const COMMUNITY_MANIFEST_CONTENT_TYPE = 'application/manifest+json; charset=utf-8'
16
+
17
+ export interface CommunityManifestIcon {
18
+ /** A path on this site. */
19
+ readonly src: string
20
+ /** `192x192`, `512x512`, … */
21
+ readonly sizes: string
22
+ readonly type?: string
23
+ readonly purpose?: 'any' | 'maskable' | 'monochrome' | 'any maskable'
24
+ }
25
+
26
+ export interface CommunityManifestOptions {
27
+ readonly name: string
28
+ readonly shortName?: string
29
+ /** The notification centre: where the installed app opens (a path inside `scope`). */
30
+ readonly startUrl: string
31
+ /** The site's base (default `/`): what the installed app covers. */
32
+ readonly scope?: string
33
+ readonly icons: readonly CommunityManifestIcon[]
34
+ readonly themeColor?: string
35
+ readonly backgroundColor?: string
36
+ /** The manifest's language (`cs`, `en`). */
37
+ readonly lang?: string
38
+ }
39
+
40
+ /** The manifest (W3C Web App Manifest) a host serves. */
41
+ export interface CommunityWebManifest {
42
+ readonly name: string
43
+ readonly short_name: string
44
+ readonly start_url: string
45
+ readonly scope: string
46
+ readonly display: 'standalone'
47
+ readonly icons: ReadonlyArray<{ src: string; sizes: string; type?: string; purpose?: string }>
48
+ readonly theme_color?: string
49
+ readonly background_color?: string
50
+ readonly lang?: string
51
+ }
52
+
53
+ const NAME_MAX = 80
54
+ const SHORT_NAME_MAX = 30
55
+ const COLOR_RE = /^(#[0-9a-fA-F]{3,8}|[a-zA-Z]{3,30}|(rgb|hsl)a?\([0-9.,%\s/]{1,60}\))$/
56
+ const SIZES_RE = /^(any|\d{1,4}x\d{1,4}( \d{1,4}x\d{1,4})*)$/
57
+
58
+ function sitePath(value: unknown, what: string): string {
59
+ if (typeof value !== 'string' || !/^\/(?!\/)[^\s\\]*$/.test(value) || value.length > 512) {
60
+ throw new TypeError(`communityManifest: ${what} must be a path on this site (starting with a single /)`)
61
+ }
62
+ return value
63
+ }
64
+
65
+ function text(value: unknown, max: number, what: string): string {
66
+ if (typeof value !== 'string' || value.trim() === '') throw new TypeError(`communityManifest: ${what} is required`)
67
+ return value.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, max)
68
+ }
69
+
70
+ /** The manifest (see the module comment). Throws a TypeError for a path outside the site or a start URL outside the scope. */
71
+ export function communityManifest(options: CommunityManifestOptions): CommunityWebManifest {
72
+ const name = text(options?.name, NAME_MAX, 'name')
73
+ const shortName = options.shortName === undefined ? name.slice(0, SHORT_NAME_MAX) : text(options.shortName, SHORT_NAME_MAX, 'shortName')
74
+ const scopeRaw = sitePath(options.scope ?? '/', 'scope')
75
+ const scope = scopeRaw.endsWith('/') ? scopeRaw : `${scopeRaw}/`
76
+ const startUrl = sitePath(options.startUrl, 'startUrl')
77
+ if (!startUrl.startsWith(scope) && `${startUrl}/` !== scope) throw new TypeError('communityManifest: startUrl must lie inside scope')
78
+ if (!Array.isArray(options.icons) || options.icons.length === 0) throw new TypeError('communityManifest: at least one icon is required')
79
+ const icons = options.icons.map((icon, i) => {
80
+ const src = sitePath(icon?.src, `icons[${i}].src`)
81
+ if (typeof icon.sizes !== 'string' || !SIZES_RE.test(icon.sizes)) throw new TypeError(`communityManifest: icons[${i}].sizes is not a sizes list`)
82
+ return {
83
+ src,
84
+ sizes: icon.sizes,
85
+ ...(typeof icon.type === 'string' && /^image\/[a-z0-9.+-]{1,40}$/.test(icon.type) ? { type: icon.type } : {}),
86
+ ...(icon.purpose ? { purpose: icon.purpose } : {}),
87
+ }
88
+ })
89
+ const color = (value: unknown, what: string): string | undefined => {
90
+ if (value === undefined) return undefined
91
+ if (typeof value !== 'string' || !COLOR_RE.test(value)) throw new TypeError(`communityManifest: ${what} is not a colour`)
92
+ return value
93
+ }
94
+ const themeColor = color(options.themeColor, 'themeColor')
95
+ const backgroundColor = color(options.backgroundColor, 'backgroundColor')
96
+ return {
97
+ name,
98
+ short_name: shortName,
99
+ start_url: startUrl,
100
+ scope,
101
+ display: 'standalone',
102
+ icons,
103
+ ...(themeColor ? { theme_color: themeColor } : {}),
104
+ ...(backgroundColor ? { background_color: backgroundColor } : {}),
105
+ ...(typeof options.lang === 'string' && /^[a-z]{2}(-[A-Za-z0-9]{2,8})?$/.test(options.lang) ? { lang: options.lang } : {}),
106
+ }
107
+ }