@blogmcp/community 0.4.1 → 0.5.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 (158) hide show
  1. package/dist/blogmcp-community-private.global.js +8 -0
  2. package/dist/blogmcp-community.global.js +3 -3
  3. package/dist/chunks/{mount-Ts_r2fwt.js → mount-SKmc4NgD.js} +39 -9
  4. package/dist/chunks/private-mount-BgfUSd3g.js +5548 -0
  5. package/dist/core/attrs.d.ts +15 -0
  6. package/dist/core/settings.d.ts +5 -0
  7. package/dist/index.js +2 -2
  8. package/dist/private/core/dock.d.ts +38 -0
  9. package/dist/private/core/push.d.ts +49 -0
  10. package/dist/private/core/realtime.d.ts +57 -0
  11. package/dist/private/core/setup.d.ts +43 -0
  12. package/dist/private/core/view.d.ts +179 -0
  13. package/dist/private/dm/composer.d.ts +34 -0
  14. package/dist/private/dm/controller.d.ts +162 -0
  15. package/dist/private/dm/index.d.ts +14 -0
  16. package/dist/private/dm/links.d.ts +33 -0
  17. package/dist/private/dm/muted.d.ts +37 -0
  18. package/dist/private/dm/search.d.ts +7 -0
  19. package/dist/private/dm/text.d.ts +27 -0
  20. package/dist/private/dm/ui/DmBlocks.vue.d.ts +8 -0
  21. package/dist/private/dm/ui/DmCases.vue.d.ts +8 -0
  22. package/dist/private/dm/ui/DmComposer.vue.d.ts +20 -0
  23. package/dist/private/dm/ui/DmInbox.vue.d.ts +12 -0
  24. package/dist/private/dm/ui/DmLinkWarning.vue.d.ts +8 -0
  25. package/dist/private/dm/ui/DmLocalAids.vue.d.ts +8 -0
  26. package/dist/private/dm/ui/DmMessageText.vue.d.ts +8 -0
  27. package/dist/private/dm/ui/DmNew.vue.d.ts +12 -0
  28. package/dist/private/dm/ui/DmReport.vue.d.ts +8 -0
  29. package/dist/private/dm/ui/DmRequests.vue.d.ts +12 -0
  30. package/dist/private/dm/ui/DmScreens.vue.d.ts +9 -0
  31. package/dist/private/dm/ui/DmThread.vue.d.ts +9 -0
  32. package/dist/private/element.d.ts +23 -0
  33. package/dist/private/global.d.ts +10 -0
  34. package/dist/private/i18n.d.ts +41 -0
  35. package/dist/private/index.d.ts +32 -0
  36. package/dist/private/index.js +57 -0
  37. package/dist/private/mount.d.ts +55 -0
  38. package/dist/private/pages/api.d.ts +44 -0
  39. package/dist/private/pages/element.d.ts +6 -0
  40. package/dist/private/pages/fragment.d.ts +43 -0
  41. package/dist/private/pages/i18n.d.ts +25 -0
  42. package/dist/private/pages/index.d.ts +1 -0
  43. package/dist/private/pages/pages.d.ts +276 -0
  44. package/dist/private/pages/proof.d.ts +36 -0
  45. package/dist/private/pages/provider-view.d.ts +33 -0
  46. package/dist/private/pages/setup.d.ts +42 -0
  47. package/dist/private/pages/ui/AccountPageRoot.vue.d.ts +9 -0
  48. package/dist/private/pages/ui/PageActivation.vue.d.ts +9 -0
  49. package/dist/private/pages/ui/PageAddress.vue.d.ts +8 -0
  50. package/dist/private/pages/ui/PageDeviceApprove.vue.d.ts +8 -0
  51. package/dist/private/pages/ui/PageDevices.vue.d.ts +8 -0
  52. package/dist/private/pages/ui/PageExport.vue.d.ts +8 -0
  53. package/dist/private/pages/ui/PageMessages.vue.d.ts +9 -0
  54. package/dist/private/react.d.ts +12 -0
  55. package/dist/private/react.js +36 -0
  56. package/dist/private/ui/ChatDockRoot.vue.d.ts +20 -0
  57. package/dist/private/ui/LegalBlocks.vue.d.ts +10 -0
  58. package/dist/private/ui/LegalRun.vue.d.ts +7 -0
  59. package/dist/private/ui/LegalRuns.vue.d.ts +6 -0
  60. package/dist/private/ui/LegalText.vue.d.ts +13 -0
  61. package/dist/private/ui/PrivateScreens.vue.d.ts +14 -0
  62. package/dist/private/ui/PrivateViewRoot.vue.d.ts +23 -0
  63. package/dist/private/ui/PromiseBlock.vue.d.ts +9 -0
  64. package/dist/private/ui/ProviderLine.vue.d.ts +8 -0
  65. package/dist/private/ui/ScreenActivation.vue.d.ts +8 -0
  66. package/dist/private/ui/ScreenAddress.vue.d.ts +8 -0
  67. package/dist/private/ui/ScreenApproval.vue.d.ts +8 -0
  68. package/dist/private/ui/ScreenDevices.vue.d.ts +8 -0
  69. package/dist/private/ui/ScreenHome.vue.d.ts +12 -0
  70. package/dist/private/ui/ScreenNotifications.vue.d.ts +8 -0
  71. package/dist/private/ui/ScreenReads.vue.d.ts +8 -0
  72. package/dist/private/ui/ScreenSettings.vue.d.ts +8 -0
  73. package/dist/private/ui/legal.d.ts +15 -0
  74. package/dist/private/ui/root.d.ts +35 -0
  75. package/dist/private/ui/text.d.ts +22 -0
  76. package/dist/private/vue.d.ts +88 -0
  77. package/dist/private/vue.js +72 -0
  78. package/dist/react.js +14 -14
  79. package/dist/vue.js +14 -14
  80. package/package.json +23 -6
  81. package/src/core/attrs.ts +19 -0
  82. package/src/core/settings.ts +55 -12
  83. package/src/private/core/dock.ts +105 -0
  84. package/src/private/core/push.ts +166 -0
  85. package/src/private/core/realtime.ts +109 -0
  86. package/src/private/core/setup.ts +75 -0
  87. package/src/private/core/view.ts +920 -0
  88. package/src/private/dm/composer.ts +74 -0
  89. package/src/private/dm/controller.ts +636 -0
  90. package/src/private/dm/index.ts +14 -0
  91. package/src/private/dm/links.ts +55 -0
  92. package/src/private/dm/muted.ts +160 -0
  93. package/src/private/dm/search.ts +18 -0
  94. package/src/private/dm/text.ts +60 -0
  95. package/src/private/dm/ui/DmBlocks.vue +27 -0
  96. package/src/private/dm/ui/DmCases.vue +58 -0
  97. package/src/private/dm/ui/DmComposer.vue +68 -0
  98. package/src/private/dm/ui/DmInbox.vue +34 -0
  99. package/src/private/dm/ui/DmLinkWarning.vue +27 -0
  100. package/src/private/dm/ui/DmLocalAids.vue +43 -0
  101. package/src/private/dm/ui/DmMessageText.vue +16 -0
  102. package/src/private/dm/ui/DmNew.vue +46 -0
  103. package/src/private/dm/ui/DmReport.vue +93 -0
  104. package/src/private/dm/ui/DmRequests.vue +50 -0
  105. package/src/private/dm/ui/DmScreens.vue +66 -0
  106. package/src/private/dm/ui/DmThread.vue +235 -0
  107. package/src/private/element.ts +90 -0
  108. package/src/private/global.ts +14 -0
  109. package/src/private/i18n.ts +127 -0
  110. package/src/private/index.ts +68 -0
  111. package/src/private/messages/cs.json +311 -0
  112. package/src/private/messages/en.json +319 -0
  113. package/src/private/mount.ts +103 -0
  114. package/src/private/pages/api.ts +96 -0
  115. package/src/private/pages/build.d.mts +2 -0
  116. package/src/private/pages/build.mjs +72 -0
  117. package/src/private/pages/element.ts +49 -0
  118. package/src/private/pages/fragment.ts +63 -0
  119. package/src/private/pages/i18n.ts +82 -0
  120. package/src/private/pages/index.ts +10 -0
  121. package/src/private/pages/messages/cs.json +97 -0
  122. package/src/private/pages/messages/en.json +97 -0
  123. package/src/private/pages/pages.ts +410 -0
  124. package/src/private/pages/proof.ts +110 -0
  125. package/src/private/pages/provider-view.ts +121 -0
  126. package/src/private/pages/setup.ts +79 -0
  127. package/src/private/pages/ui/AccountPageRoot.vue +45 -0
  128. package/src/private/pages/ui/PageActivation.vue +42 -0
  129. package/src/private/pages/ui/PageAddress.vue +39 -0
  130. package/src/private/pages/ui/PageDeviceApprove.vue +62 -0
  131. package/src/private/pages/ui/PageDevices.vue +84 -0
  132. package/src/private/pages/ui/PageExport.vue +35 -0
  133. package/src/private/pages/ui/PageMessages.vue +39 -0
  134. package/src/private/pages/ui/account.css +6 -0
  135. package/src/private/react.ts +49 -0
  136. package/src/private/shims.d.ts +6 -0
  137. package/src/private/ui/ChatDockRoot.vue +119 -0
  138. package/src/private/ui/LegalBlocks.vue +30 -0
  139. package/src/private/ui/LegalRun.vue +13 -0
  140. package/src/private/ui/LegalRuns.vue +20 -0
  141. package/src/private/ui/LegalText.vue +25 -0
  142. package/src/private/ui/PrivateScreens.vue +61 -0
  143. package/src/private/ui/PrivateViewRoot.vue +70 -0
  144. package/src/private/ui/PromiseBlock.vue +18 -0
  145. package/src/private/ui/ProviderLine.vue +20 -0
  146. package/src/private/ui/ScreenActivation.vue +82 -0
  147. package/src/private/ui/ScreenAddress.vue +37 -0
  148. package/src/private/ui/ScreenApproval.vue +71 -0
  149. package/src/private/ui/ScreenDevices.vue +42 -0
  150. package/src/private/ui/ScreenHome.vue +29 -0
  151. package/src/private/ui/ScreenNotifications.vue +44 -0
  152. package/src/private/ui/ScreenReads.vue +23 -0
  153. package/src/private/ui/ScreenSettings.vue +44 -0
  154. package/src/private/ui/legal.ts +29 -0
  155. package/src/private/ui/private.css +90 -0
  156. package/src/private/ui/root.ts +89 -0
  157. package/src/private/ui/text.ts +40 -0
  158. package/src/private/vue.ts +87 -0
@@ -4,8 +4,11 @@
4
4
  * - the six switches of `me/settings/get`, each saved on its own (`me/settings/update` with that one switch);
5
5
  * - this browser's push: shown only while `me/get`'s `module.features.push`; „Zapnout upozornění" (the member's
6
6
  * click, never on load) registers the host's worker (`swPath`), asks `me/push/vapid`, subscribes the PushManager
7
- * (`userVisibleOnly`, the VAPID key) and hands the subscription to `me/push/subscribe`; „Vypnout" ends the browser's
8
- * subscription and `me/push/unsubscribe`s it. A subscription made for another VAPID key id (a rotation), or an
7
+ * (`userVisibleOnly`, the VAPID key) and hands the subscription to `me/push/subscribe`; „Vypnout" deletes the host's
8
+ * row (`me/push/unsubscribe`) and keeps the browser's subscription. One browser has one service worker and so one
9
+ * `PushSubscription` for the host's push and the private push (m4-contracts.md §6.2, B-55): this element ends it
10
+ * only when it was made for another VAPID key, never on „Vypnout", so switching the host's push off and on never
11
+ * ends the endpoint the private view registered for its own row. A subscription made for another VAPID key id (a rotation), or an
9
12
  * unread `module_push_reset` notification, asks the member to switch it on again. The switch reads on only for a
10
13
  * subscription this member made here (another member's on a shared browser reads off), for the current key,
11
14
  * with the permission granted, that kb-api still holds: on load the page ASKS `me/push/status { endpoint }`
@@ -45,6 +48,20 @@ import {
45
48
  type PushSupport,
46
49
  } from './push'
47
50
 
51
+ /**
52
+ * Whether a subscription was made for this VAPID key: true or false from its `options.applicationServerKey`, null when
53
+ * the browser does not say (an older engine) — then `subscribe` itself decides (B-55, `enablePush`).
54
+ */
55
+ export function sameApplicationServerKey(sub: PushSubscription, key: Uint8Array): boolean | null {
56
+ const raw = (sub as { options?: { applicationServerKey?: ArrayBuffer | ArrayBufferView | null } }).options?.applicationServerKey
57
+ if (raw === undefined || raw === null) return null
58
+ const bytes = raw instanceof ArrayBuffer ? new Uint8Array(raw) : ArrayBuffer.isView(raw) ? new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength) : null
59
+ if (bytes === null) return null
60
+ if (bytes.length !== key.length) return false
61
+ for (let i = 0; i < key.length; i++) if (bytes[i] !== key[i]) return false
62
+ return true
63
+ }
64
+
48
65
  /** The six switches, in the order the page shows them. */
49
66
  export const SETTING_KEYS = ['notifyReply', 'notifyMention', 'notifyTopic', 'pushEnabled', 'digestEmail', 'quietHours'] as const
50
67
  export type SettingKey = (typeof SETTING_KEYS)[number]
@@ -269,21 +286,39 @@ export function createMemberSettings(o: MemberSettingsOptions): MemberSettingsCo
269
286
  if (!vapid.ok) return fail(vapid.code === 'pushRefused' ? 'refused' : null, vapid)
270
287
  const applicationServerKey = base64UrlBytes(vapid.value.publicKey)
271
288
  if (!applicationServerKey) return fail(null, { ok: false, code: 'unavailable' })
272
- // A subscription made for another key cannot be changed in place: end it first.
289
+ // B-55: the browser's one subscription may also carry the private view's row. It is ended only when it was
290
+ // made for another key (which cannot be changed in place, and whose private row is gone with the rotation too);
291
+ // one made for this key is reused as it is — `subscribe` with the same key answers the existing subscription.
273
292
  const old = await currentSubscription(reg)
274
- if (old) await old.unsubscribe().catch(() => false)
275
- const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: applicationServerKey as BufferSource })
293
+ const oldKey = old ? sameApplicationServerKey(old, applicationServerKey) : null
294
+ if (old && oldKey === false) await old.unsubscribe().catch(() => false)
295
+ /** Whether the subscription existed before this click (then another surface may hold it: never end it here). */
296
+ let reused = old !== null && oldKey !== false
297
+ const options = { userVisibleOnly: true, applicationServerKey: applicationServerKey as BufferSource }
298
+ let sub: PushSubscription
299
+ try {
300
+ sub = await reg.pushManager.subscribe(options)
301
+ } catch (err) {
302
+ // A browser that does not expose the old subscription's key refuses one made for another key here, with an
303
+ // InvalidStateError: only then is the old one ended and the subscription made again. Any other error (the push
304
+ // service aborted, the permission went) ends nothing, because the old one may be this key's and carry the
305
+ // private row (B-55).
306
+ if (!old || oldKey !== null || (err as { name?: unknown } | null)?.name !== 'InvalidStateError') throw err
307
+ await old.unsubscribe().catch(() => false)
308
+ reused = false
309
+ sub = await reg.pushManager.subscribe(options)
310
+ }
276
311
  if (disposed) return
277
312
  const input = subscriptionInput(sub)
278
313
  if (!input) {
279
- await sub.unsubscribe().catch(() => false)
314
+ if (!reused) await sub.unsubscribe().catch(() => false)
280
315
  return fail('refused')
281
316
  }
282
317
  const r = await client.me.push.subscribe({ ...input, userAgentClass: userAgentClass() }, call)
283
318
  if (disposed) return
284
319
  if (!r.ok) {
285
- // kb-api keeps nothing of a refused subscription: the browser's goes too.
286
- await sub.unsubscribe().catch(() => false)
320
+ // kb-api keeps nothing of a refused subscription: one this click made goes too, one that was here stays.
321
+ if (!reused) await sub.unsubscribe().catch(() => false)
287
322
  return fail(r.code === 'pushRefused' ? 'refused' : null, r)
288
323
  }
289
324
  storePush({ memberId: me, keyId: r.value.keyId })
@@ -306,19 +341,27 @@ export function createMemberSettings(o: MemberSettingsOptions): MemberSettingsCo
306
341
  p.status = 'busy'
307
342
  p.failure = null
308
343
  p.note = null
344
+ // B-55: only the host's row goes; the browser's subscription stays, because the private view's row may use the
345
+ // same endpoint (one service worker, one subscription) and ending it would silently end the private push too.
309
346
  let endpoint: string | null = null
310
347
  try {
311
348
  const sub = await currentSubscription(await currentRegistration())
312
- endpoint = sub?.endpoint ?? null
313
- await sub?.unsubscribe()
349
+ endpoint = sub ? (subscriptionInput(sub)?.endpoint ?? sub.endpoint ?? null) : null
314
350
  } catch {
315
- // The browser's subscription could not be ended: kb-api forgets it anyway.
351
+ // The browser's subscription cannot be read: there is no endpoint to name.
316
352
  }
317
353
  if (disposed) return
318
354
  if (endpoint) {
319
355
  const r = await client.me.push.unsubscribe({ endpoint }, call)
320
356
  if (disposed) return
321
- if (!r.ok) p.failure = r
357
+ if (!r.ok) {
358
+ // The browser's subscription is no longer ended here, so a host row kb-api did not delete keeps receiving
359
+ // pushes: the switch stays on, the stored record stays (the next load still reads it on), and the member sees
360
+ // the refusal and can press „Vypnout" again.
361
+ p.failure = r
362
+ p.status = 'on'
363
+ return
364
+ }
322
365
  }
323
366
  storePush(null)
324
367
  p.status = 'off'
@@ -0,0 +1,105 @@
1
+ /**
2
+ * `<blogmcp-chat-dock>`'s windows (m4-contracts.md §6.2): a launcher with the private unread dot, a panel with the
3
+ * conversation list and the account's screens, and up to three open windows on a desktop — full screen on a phone,
4
+ * one at a time. The dock lives in the host's root layout, so a client-side navigation never unmounts it: its private
5
+ * session, its realtime subscription and its windows stay as they are. A host hides it on a page (the regulated
6
+ * preset's pages, §6.7) with the attribute `hidden-by-host`, which hides it by CSS and unmounts nothing.
7
+ *
8
+ * A window holds one of the private view's screens, or one conversation (DM8b, `openConversation`): both share the
9
+ * same list of windows and the same limit.
10
+ */
11
+ import { reactive } from 'vue'
12
+ import type { PrivateRealtimeInput } from './realtime'
13
+ import type { PrivateScreen } from './view'
14
+
15
+ /** How many windows stay open side by side on a desktop; opening one more closes the oldest. */
16
+ export const DOCK_MAX_WINDOWS = 3
17
+ /** At or below this width a window takes the whole screen and only one is open. */
18
+ export const DOCK_MOBILE_QUERY = '(max-width:640px)'
19
+
20
+ /**
21
+ * The dock's `realtime` property (§6.3, C.8): the SDK's `createPrivateRealtime`, which the dock's controller starts
22
+ * with its own private client, or a source of the host's own (`{ subscribe(listener) }`, the inbox's `{ k }`).
23
+ */
24
+ export type PrivateDockRealtime = PrivateRealtimeInput
25
+
26
+ export interface DockWindow {
27
+ readonly id: string
28
+ readonly screen: PrivateScreen
29
+ /** A conversation's window (its screen is `messages`); absent for an account screen's window. */
30
+ readonly conversationId?: string
31
+ }
32
+
33
+ export interface DockUi {
34
+ panelOpen: boolean
35
+ windows: DockWindow[]
36
+ mobile: boolean
37
+ }
38
+
39
+ export interface DockController {
40
+ readonly state: DockUi
41
+ togglePanel(): void
42
+ openWindow(screen: PrivateScreen): void
43
+ /** One conversation's window (DM8b); an open one comes to the front. */
44
+ openConversation(conversationId: string): void
45
+ closeWindow(id: string): void
46
+ /**
47
+ * Every conversation's window goes (the account screens' stay): the conversations ended — a sign-out, another
48
+ * member on this browser, a forgotten key —, and a window of the previous member's conversation must not wait for
49
+ * the next member's controller to fill it.
50
+ */
51
+ closeConversations(): void
52
+ dispose(): void
53
+ }
54
+
55
+ /** The layout's media query (null where there is none: a test DOM, an old engine). */
56
+ function mediaQuery(query: string): MediaQueryList | null {
57
+ try {
58
+ return typeof matchMedia === 'function' ? matchMedia(query) : null
59
+ } catch {
60
+ return null
61
+ }
62
+ }
63
+
64
+ export function createDock(): DockController {
65
+ const mq = mediaQuery(DOCK_MOBILE_QUERY)
66
+ const state = reactive<DockUi>({ panelOpen: false, windows: [], mobile: mq?.matches === true }) as DockUi
67
+ const max = (): number => (state.mobile ? 1 : DOCK_MAX_WINDOWS)
68
+ const onChange = (e: MediaQueryListEvent): void => {
69
+ state.mobile = e.matches
70
+ // A phone shows the newest window only.
71
+ if (state.windows.length > max()) state.windows = state.windows.slice(-max())
72
+ }
73
+ mq?.addEventListener?.('change', onChange)
74
+
75
+ /** An open window comes to the front (the end of the list) instead of opening twice; the oldest goes past the limit. */
76
+ function bring(id: string, make: () => DockWindow): void {
77
+ const existing = state.windows.find((w) => w.id === id)
78
+ const rest = state.windows.filter((w) => w !== existing)
79
+ state.windows = [...rest, existing ?? make()].slice(-max())
80
+ if (state.mobile) state.panelOpen = false
81
+ }
82
+
83
+ return {
84
+ state,
85
+ togglePanel() {
86
+ state.panelOpen = !state.panelOpen
87
+ },
88
+ openWindow(screen) {
89
+ bring(`w-${screen}`, () => ({ id: `w-${screen}`, screen }))
90
+ },
91
+ openConversation(conversationId) {
92
+ const cid = conversationId.toLowerCase()
93
+ bring(`c-${cid}`, () => ({ id: `c-${cid}`, screen: 'messages', conversationId: cid }))
94
+ },
95
+ closeWindow(id) {
96
+ state.windows = state.windows.filter((w) => w.id !== id)
97
+ },
98
+ closeConversations() {
99
+ if (state.windows.some((w) => w.conversationId)) state.windows = state.windows.filter((w) => !w.conversationId)
100
+ },
101
+ dispose() {
102
+ mq?.removeEventListener?.('change', onChange)
103
+ },
104
+ }
105
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * This browser's private push (m4-contracts.md §6.2, §6.3, B-55). One service worker gives one `PushSubscription`, the
3
+ * same endpoint for the host's push and the private push; kb-api keeps one row per origin (`UNIQUE (endpoint,
4
+ * origin)`), so each surface manages only its own row:
5
+ *
6
+ * - on the member's click the private view reuses the browser's subscription when it was made for the tenant's VAPID
7
+ * key (`subscribe` with the same key answers it), or subscribes when there is none, and posts it to
8
+ * `private/push/subscribe` with this device's session;
9
+ * - „Vypnout" posts `private/push/unsubscribe` for the endpoint and leaves the browser's subscription alone, because
10
+ * the host's row may use it; when kb-api does not take it, the device stays recorded as the one that turned push
11
+ * on (the private row is still live, and nothing else would end it), and the view keeps the switch on;
12
+ * - **the private view never calls `PushSubscription.unsubscribe()`** (test/private/text.spec.ts scans for it);
13
+ * - on every start it re-reads `getSubscription()` and re-posts `private/push/subscribe` for a device that turned the
14
+ * private push on here, so a changed endpoint (the browser rotated it, the host's element made a new one for a new
15
+ * key) replaces the device's private row.
16
+ *
17
+ * After a VAPID key rotation the browser's subscription belongs to the old key, and `subscribe` with the new key is
18
+ * refused while it exists. The private view still never ends it: `enable` and `resync` compare the subscription's key
19
+ * with `me/push/vapid` and answer `stale`, and the screen asks the member to switch the website's notifications off and
20
+ * on (the public element ends a subscription made for another key), after which the next start re-posts the endpoint.
21
+ *
22
+ * Which device turned it on here is kept per browser as the device key's thumbprint (a public value, never a token):
23
+ * another member's device on a shared browser, or this member's key after a `forget`, is not this device. The worker,
24
+ * the permission and the VAPID key are the public element's glue (`../../core/push.ts`, the one module that may touch
25
+ * the service worker) and the host's `me/push/vapid`.
26
+ */
27
+ import type { CommunityClient } from '@blogmcp/sdk/community'
28
+ import type { PrivateClient } from '@blogmcp/sdk/community/private'
29
+ import {
30
+ base64UrlBytes,
31
+ currentRegistration,
32
+ currentSubscription,
33
+ notificationPermission,
34
+ pushSupport,
35
+ registerWorker,
36
+ requestNotificationPermission,
37
+ subscriptionInput,
38
+ } from '../../core/push'
39
+
40
+ export type PrivatePushResult = 'on' | 'denied' | 'refused' | 'unsupported' | 'stale'
41
+
42
+ /** What the private view needs of this browser's push (a stub in the unit specs). */
43
+ export interface PrivatePushPort {
44
+ supported(): boolean
45
+ /**
46
+ * Re-post this device's subscription when it turned the private push on here: true when it is on, `stale` when the
47
+ * subscription was made for a key the tenant no longer serves (nothing is posted then).
48
+ */
49
+ resync(client: PrivateClient): Promise<boolean | 'stale'>
50
+ enable(client: PrivateClient): Promise<PrivatePushResult>
51
+ /** Delete this device's private row; false when kb-api did not take it (the private push is still on). */
52
+ disable(client: PrivateClient): Promise<boolean>
53
+ }
54
+
55
+ const PRIVATE_PUSH_STORAGE = 'blogmcp-community:private-push'
56
+
57
+ function storedJkt(): string | null {
58
+ try {
59
+ const raw = typeof localStorage === 'undefined' ? null : localStorage.getItem(PRIVATE_PUSH_STORAGE)
60
+ const v = raw === null ? null : (JSON.parse(raw) as { jkt?: unknown } | null)
61
+ return v && typeof v.jkt === 'string' ? v.jkt : null
62
+ } catch {
63
+ return null
64
+ }
65
+ }
66
+
67
+ function storeJkt(jkt: string | null): void {
68
+ try {
69
+ if (typeof localStorage === 'undefined') return
70
+ if (jkt === null) localStorage.removeItem(PRIVATE_PUSH_STORAGE)
71
+ else localStorage.setItem(PRIVATE_PUSH_STORAGE, JSON.stringify({ jkt }))
72
+ } catch {
73
+ // Blocked storage: the next start does not know the device turned push on; the member turns it on again.
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Whether a subscription was made for this VAPID key: true or false from its `options.applicationServerKey`, null when
79
+ * the browser does not say. The same comparison as the public element's `sameApplicationServerKey` (core/settings.ts),
80
+ * kept here because the private bundle may not import the public settings view.
81
+ */
82
+ function sameKey(sub: PushSubscription, key: Uint8Array): boolean | null {
83
+ const raw = (sub as { options?: { applicationServerKey?: ArrayBuffer | ArrayBufferView | null } }).options?.applicationServerKey
84
+ if (raw === undefined || raw === null) return null
85
+ const bytes = raw instanceof ArrayBuffer ? new Uint8Array(raw) : ArrayBuffer.isView(raw) ? new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength) : null
86
+ if (bytes === null) return null
87
+ if (bytes.length !== key.length) return false
88
+ for (let i = 0; i < key.length; i++) if (bytes[i] !== key[i]) return false
89
+ return true
90
+ }
91
+
92
+ /** The subscription as `private/push/subscribe` takes it (the keys flat, §6.3). */
93
+ function privateInput(sub: PushSubscription): { endpoint: string; p256dh: string; auth: string } | null {
94
+ const input = subscriptionInput(sub)
95
+ return input ? { endpoint: input.endpoint, p256dh: input.keys.p256dh, auth: input.keys.auth } : null
96
+ }
97
+
98
+ export interface BrowserPrivatePushOptions {
99
+ /** The host's worker script (`<site-base>/sw.js`). */
100
+ swPath: string
101
+ /** The host's public client, for `me/push/vapid` (the tenant's one VAPID key serves both rows). */
102
+ host: CommunityClient
103
+ }
104
+
105
+ /** The browser's glue (see the module doc). */
106
+ export function browserPrivatePush(o: BrowserPrivatePushOptions): PrivatePushPort {
107
+ const supported = (): boolean => pushSupport() === 'supported'
108
+ return {
109
+ supported,
110
+ async resync(client) {
111
+ if (!supported()) return false
112
+ const jkt = await client.session.currentJkt()
113
+ if (jkt === null || storedJkt() !== jkt || notificationPermission() !== 'granted') return false
114
+ const sub = await currentSubscription(await currentRegistration())
115
+ const input = sub ? privateInput(sub) : null
116
+ if (!sub || !input) return false
117
+ // A subscription made for a key the tenant rotated away from is dead at the push service: not re-posted, said.
118
+ const vapid = await o.host.me.push.vapid()
119
+ const key = vapid.ok ? base64UrlBytes(vapid.value.publicKey) : null
120
+ if (key && sameKey(sub, key) === false) return 'stale'
121
+ const r = await client.push.subscribe(input)
122
+ return r.ok
123
+ },
124
+ async enable(client) {
125
+ if (!supported()) return 'unsupported'
126
+ try {
127
+ if ((await requestNotificationPermission()) !== 'granted') return 'denied'
128
+ const reg = await registerWorker(o.swPath)
129
+ const vapid = await o.host.me.push.vapid()
130
+ if (!vapid.ok) return 'refused'
131
+ const key = base64UrlBytes(vapid.value.publicKey)
132
+ if (!key) return 'refused'
133
+ // The same key answers the existing subscription; another key is refused by the browser, and this view never
134
+ // ends one: the member is asked to switch the website's notifications off and on instead.
135
+ const existing = await currentSubscription(reg)
136
+ if (existing && sameKey(existing, key) === false) return 'stale'
137
+ const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key as BufferSource })
138
+ const input = privateInput(sub)
139
+ if (!input) return 'refused'
140
+ const r = await client.push.subscribe(input)
141
+ if (!r.ok) return 'refused'
142
+ storeJkt(await client.session.currentJkt())
143
+ return 'on'
144
+ } catch {
145
+ return notificationPermission() === 'denied' ? 'denied' : 'refused'
146
+ }
147
+ },
148
+ async disable(client) {
149
+ let endpoint: string | null = null
150
+ try {
151
+ const sub = await currentSubscription(await currentRegistration())
152
+ endpoint = sub ? (privateInput(sub)?.endpoint ?? null) : null
153
+ } catch {
154
+ // The browser's subscription cannot be read: there is no endpoint to name.
155
+ }
156
+ if (endpoint) {
157
+ const r = await client.push.unsubscribe(endpoint)
158
+ // The browser's subscription is never ended here, so a row kb-api kept still receives pushes: keep the
159
+ // record, and let the member press „Vypnout" again.
160
+ if (!r.ok) return false
161
+ }
162
+ storeJkt(null)
163
+ return true
164
+ },
165
+ }
166
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The private elements' live inbox (m4-contracts.md §6.2, §6.3, C.8): the `realtime` the host passes to
3
+ * `<blogmcp-chat-dock>`, `<blogmcp-private-view>` and `createPrivateView`. The elements own no socket; it is either
4
+ *
5
+ * - the SDK's factory, `createPrivateRealtime` of `@blogmcp/sdk/community/private` (or any function of its shape):
6
+ * the controller calls it with ITS private client once the view is ready, so the connection's tokens are asked
7
+ * with this device's session, and closes it when the view goes (unmounted, signed out, dark, a final refusal); or
8
+ * - a source the host runs itself, `{ subscribe(listener) }` (the shape C.8 names): the controller only subscribes
9
+ * and unsubscribes, and never closes what it did not open.
10
+ *
11
+ * Either way the events are the inbox's content-free `{ k }` (with at most `c`, `s` and `r`).
12
+ */
13
+ import { dmEventEffect, type PrivateClient } from '@blogmcp/sdk/community/private'
14
+
15
+ /** One inbox event, as far as the elements read it. */
16
+ export interface PrivateInboxEvent {
17
+ readonly k: string
18
+ }
19
+
20
+ /** A source of inbox events: `subscribe` returns the function that removes the listener. */
21
+ export interface PrivateRealtimeSource {
22
+ subscribe(listener: (event: PrivateInboxEvent) => void): () => void
23
+ close?(): void
24
+ }
25
+
26
+ /** What the controller calls a factory with. */
27
+ export interface PrivateRealtimeFactoryOptions {
28
+ client: PrivateClient
29
+ onMode?: (mode: string) => void
30
+ onEnd?: (end: { reason: string; code: string | null }) => void
31
+ }
32
+
33
+ /** `createPrivateRealtime`, or any function of its shape. */
34
+ export type PrivateRealtimeFactory = (options: PrivateRealtimeFactoryOptions) => PrivateRealtimeSource
35
+
36
+ /** What a host passes as `realtime`. */
37
+ export type PrivateRealtimeInput = PrivateRealtimeFactory | PrivateRealtimeSource
38
+
39
+ /** The live inbox as the view states it: none passed, connecting, live, or ended (its reason kept for the screen). */
40
+ export type PrivateRealtimeState = 'off' | 'connecting' | 'live' | 'ended'
41
+
42
+ export interface RunningRealtime {
43
+ stop(): void
44
+ }
45
+
46
+ /** Whether a value can be used as `realtime` (a factory, or an object with `subscribe`). */
47
+ export function isRealtimeInput(value: unknown): value is PrivateRealtimeInput {
48
+ return typeof value === 'function' || (typeof value === 'object' && value !== null && typeof (value as { subscribe?: unknown }).subscribe === 'function')
49
+ }
50
+
51
+ /**
52
+ * Start the inbox for `client` and hand its events to `onEvent`; `onState` follows the connection. Never throws: a
53
+ * factory or a source that fails leaves the view without live updates (it still reads on every open).
54
+ */
55
+ export function startRealtime(
56
+ input: PrivateRealtimeInput,
57
+ client: PrivateClient,
58
+ onEvent: (event: PrivateInboxEvent) => void,
59
+ onState: (state: PrivateRealtimeState, end?: { reason: string; code: string | null }) => void,
60
+ ): RunningRealtime {
61
+ let source: PrivateRealtimeSource | null = null
62
+ let off: (() => void) | null = null
63
+ let stopped = false
64
+ const owned = typeof input === 'function'
65
+ try {
66
+ if (owned) {
67
+ source = input({
68
+ client,
69
+ onMode: (mode) => {
70
+ if (stopped) return
71
+ if (mode === 'live') onState('live')
72
+ else if (mode === 'connecting') onState('connecting')
73
+ },
74
+ onEnd: (end) => {
75
+ if (!stopped) onState('ended', end)
76
+ },
77
+ })
78
+ } else source = input
79
+ onState(owned ? 'connecting' : 'live')
80
+ off = source.subscribe((event) => {
81
+ if (!stopped && event && typeof event.k === 'string') onEvent(event)
82
+ })
83
+ } catch {
84
+ onState('ended', { reason: 'unavailable', code: null })
85
+ }
86
+ return {
87
+ stop() {
88
+ if (stopped) return
89
+ stopped = true
90
+ try {
91
+ off?.()
92
+ if (owned) source?.close?.()
93
+ } catch {
94
+ // A source that is going anyway.
95
+ }
96
+ },
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Whether an inbox event can move the private unread count (the dot): the account's events, `resync`, and of the
102
+ * conversations' kinds only those `dmEventEffect` says move the inbox (`m`, `d`, `rq`). Typing (`t`), a read receipt
103
+ * (`rd`) and an edit (`e`) cannot, and a busy conversation would otherwise spend the private session's limiter on
104
+ * `notifications/unread-count` calls that change nothing (C.11 RF8-C (h)).
105
+ */
106
+ export function refreshesUnread(event: PrivateInboxEvent): boolean {
107
+ const effect = dmEventEffect(event)
108
+ return effect === 'inbox' || effect === 'other'
109
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * From an element's attributes to its controller (m4-contracts.md §6.2). The host names:
3
+ * - `kb-origin` — kb-api's public origin (`https://<slug>.blogmcp.ai`): the only origin the private client talks to,
4
+ * with no credentials (§5.8); never the host's own base;
5
+ * - `api-base` / `site-base` — the host's relative base for its own `me/get` (the public client, as every public
6
+ * element);
7
+ * - `routes` — the host's pages and its grant routes (`grantPath`, default `<site-base>/community/grant`);
8
+ * - `account-origin` — the account host (`https://<slug>--account.<base>`), for `provider_page`'s link;
9
+ * - `site-name` — the website's name in the promise; `sw-path` — the host's worker, for this browser's private push.
10
+ * A test or a host that builds its own private client passes it as the `client` property; the live inbox is the
11
+ * `realtime` property (the SDK's `createPrivateRealtime`, core/realtime.ts).
12
+ */
13
+ import { createPrivateClient, kbOriginOf, type PrivateClient } from '@blogmcp/sdk/community/private'
14
+ import type { CommunityClient, CommunityTransport } from '@blogmcp/sdk/community'
15
+ import { isSitePath, parseRoutes, routesWithDefaults, type CommunityRoutes } from '../../core/attrs'
16
+ import { communityClientFor, siteBaseFor, warnOnce } from '../../core/client'
17
+ import { browserPrivatePush, type PrivatePushPort } from './push'
18
+ import type { PrivateRealtimeInput } from './realtime'
19
+ import { createPrivateView, type PrivateViewController } from './view'
20
+
21
+ export interface PrivateElementInput {
22
+ kbOrigin?: string | null
23
+ apiBase?: string | null
24
+ siteBase?: string | null
25
+ routes?: string | CommunityRoutes | null
26
+ siteName?: string | null
27
+ swPath?: string | null
28
+ accountOrigin?: string | null
29
+ transport?: CommunityTransport | null
30
+ /** A private client the host made itself (or a test's stub). */
31
+ client?: PrivateClient | null
32
+ /** A push port in place of the browser's (a test's stub; null turns this browser's private push off). */
33
+ push?: PrivatePushPort | null
34
+ /** The host's live inbox (core/realtime.ts): the SDK's `createPrivateRealtime`, or a source of its own. */
35
+ realtime?: PrivateRealtimeInput | null
36
+ }
37
+
38
+ export interface PrivateSetup {
39
+ controller: PrivateViewController
40
+ routes: ReturnType<typeof routesWithDefaults>
41
+ /** The account host's `/zpravy` (the `provider_page` link), or null when the host named no account origin. */
42
+ accountUrl: string | null
43
+ host: CommunityClient
44
+ }
45
+
46
+ /** The controller for an element, or null (the developer told once) when a required attribute is unusable. */
47
+ export function privateSetupFor(i: PrivateElementInput): PrivateSetup | null {
48
+ const siteBase = siteBaseFor(i.siteBase ?? null)
49
+ if (siteBase === null) return null
50
+ const host = communityClientFor(i.apiBase ?? null, i.transport ?? null, siteBase)
51
+ if (!host) return null
52
+ const routes = routesWithDefaults(parseRoutes(i.routes ?? null), null, siteBase)
53
+ const kbOrigin = kbOriginOf(i.kbOrigin ?? null)
54
+ if (!i.client && kbOrigin === null) {
55
+ warnOnce('kb-origin', '[blogmcp-community] kb-origin must be kb-api’s https origin (e.g. "https://tenant.blogmcp.ai"): the private view talks to it directly')
56
+ return null
57
+ }
58
+ const accountOrigin = kbOriginOf(i.accountOrigin ?? null)
59
+ const swPath = i.swPath === undefined || i.swPath === null || i.swPath === '' ? `${siteBase}/sw.js` : i.swPath
60
+ const push = i.push !== undefined ? i.push : isSitePath(swPath) ? browserPrivatePush({ swPath, host }) : null
61
+ const siteName = typeof i.siteName === 'string' && i.siteName.trim() !== '' ? i.siteName.trim() : typeof location !== 'undefined' ? location.hostname : ''
62
+ const member = async (): Promise<string | null> => {
63
+ const me = await host.me.get()
64
+ return me.ok ? (me.value.member?.memberId ?? null) : null
65
+ }
66
+ const controller = createPrivateView({
67
+ host,
68
+ client: () => i.client ?? createPrivateClient({ kbOrigin: kbOrigin!, grantPath: routes.grantPath, member }),
69
+ push,
70
+ siteName,
71
+ realtime: i.realtime ?? null,
72
+ consultationPath: routes.consultationPath ?? null,
73
+ })
74
+ return { controller, routes, accountUrl: accountOrigin ? `${accountOrigin}/zpravy` : null, host }
75
+ }