@aria-framework/notify 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -65,6 +65,25 @@ were wrong, and the app's own view permission stays the single place access is d
65
65
  consumer briefly included an `actorUserId` "so a viewer can ignore its own action"; no client
66
66
  ever read it, so its only effect was disclosing a staffer's user id to every other viewer.
67
67
 
68
+ ### A push reaches the page that CAUSED it — including mid-navigation
69
+
70
+ Since there is no `actorUserId`, a client that must not react to its own change has to know when
71
+ it made one. That is easy to get wrong in one specific way, and a consumer shipped the mistake:
72
+
73
+ A form POST is a navigation, but **the browser keeps the old page on screen — and its stream open —
74
+ until the response arrives.** So a push written while handling that POST is delivered to the very
75
+ page that caused it, which then re-fetches, sees its own change, and announces it. The redirect
76
+ lands a moment later and replaces everything. The consumer's code carried a comment asserting the
77
+ opposite: that a page which redirects "never sees an event for its own action".
78
+
79
+ The client-side fix is small — set a flag on `submit` and ignore events while it is set — but it
80
+ has to be deliberate, and `beforeunload` is too late (it fires once the response is already
81
+ arriving). This is not something the hub can do for you: it writes to open responses and has no
82
+ idea which one issued the request.
83
+
84
+ There is also **no replay**. `pushEntity` writes to whoever is connected at that instant, so an
85
+ event a page misses while navigating is simply gone — which is why suppressing it costs nothing.
86
+
68
87
  ## THE LIMIT: one process
69
88
 
70
89
  The hub is in memory and per-process. Two app processes behind a load balancer each hold half
package/assets/bell.js ADDED
@@ -0,0 +1,180 @@
1
+ /**
2
+ * @aria-framework/notify — the bell client. Both apps hand-rolled one against this package's
3
+ * server half; each had a fix the other lacked (one the SSE connection lifecycle, the other the
4
+ * same-origin href guard). This is the merge, and the stream's single owner.
5
+ *
6
+ * MARKUP CONTRACT (ships as views/notify/bell.ejs): a root with id="notif-menu" carrying
7
+ * [data-notif-badge], [data-notif-list], [data-notif-readall], and optionally:
8
+ * data-notif-base route prefix (default '/notifications')
9
+ * data-notif-fill 'load' (default) fills on page load; 'open' fills on the dropdown's
10
+ * show.bs.dropdown (server-rendered initial badge keeps working without JS)
11
+ *
12
+ * THE STREAM IS MULTIPLEXED AND THIS FILE OWNS IT. An SSE connection never completes, so it holds
13
+ * one of the browser's ~6 per-origin connections (HTTP/1.1); in a multi-page app every navigation
14
+ * opens a new one, so the old one MUST close on pagehide/hidden or leaked streams exhaust the pool
15
+ * and the whole site stalls. One connection per page — app features that want live frames do NOT
16
+ * open their own EventSource; they listen for the DOM events this file re-dispatches:
17
+ *
18
+ * 'aria:sse' detail = the parsed frame (every frame, whatever its type)
19
+ * 'aria:sse-open' detail = { firstOpen } — fired on connect and every reconnect; catch-up
20
+ * refreshes belong on reconnect only (firstOpen === false), because the first
21
+ * open lands right after the page rendered.
22
+ *
23
+ * Frame types listed in data-notif-quiet (comma-separated, e.g. "ticket,draft") do NOT re-sync
24
+ * the bell — a ticket reply cannot change the notification list, and draft frames fire while
25
+ * somebody is typing. Extra stream query params come from any page element carrying
26
+ * data-notif-stream-param="key=value" (a ticket page watching itself rides the same connection).
27
+ *
28
+ * XSS-safe by construction: rows are createElement/textContent, and only a same-origin PATH may
29
+ * become a row's href — a link that ever carried attacker-influenced text (javascript: or
30
+ * //host) would execute or leave the site on click.
31
+ */
32
+ (function () {
33
+ 'use strict';
34
+
35
+ var menu = document.getElementById('notif-menu');
36
+ if (!menu) return;
37
+
38
+ var badge = menu.querySelector('[data-notif-badge]');
39
+ var list = menu.querySelector('[data-notif-list]');
40
+ var readAllBtn = menu.querySelector('[data-notif-readall]');
41
+ if (!badge || !list) return;
42
+
43
+ var BASE = menu.getAttribute('data-notif-base') || '/notifications';
44
+ var FILL = menu.getAttribute('data-notif-fill') || 'load';
45
+ var QUIET = (menu.getAttribute('data-notif-quiet') || '').split(',').map(function (s) { return s.trim(); }).filter(Boolean);
46
+ var tokenMeta = document.querySelector('meta[name="csrf-token"]');
47
+ var csrf = tokenMeta ? tokenMeta.getAttribute('content') : '';
48
+
49
+ function post(url) {
50
+ return fetch(url, { method: 'POST', headers: { 'x-csrf-token': csrf }, credentials: 'same-origin' });
51
+ }
52
+
53
+ function setBadge(n) {
54
+ if (n > 0) { badge.textContent = n > 99 ? '99+' : String(n); badge.hidden = false; }
55
+ else { badge.hidden = true; }
56
+ }
57
+
58
+ function safeHref(link) {
59
+ return (typeof link === 'string' && /^\/(?!\/)/.test(link)) ? link : BASE;
60
+ }
61
+
62
+ /** "3m ago" over SQLite's UTC datetime('now') strings — the trailing Z is load-bearing. */
63
+ function relTime(iso) {
64
+ if (!iso) return '';
65
+ var t = Date.parse(String(iso).includes('T') ? iso : String(iso).replace(' ', 'T') + 'Z');
66
+ if (!Number.isFinite(t)) return '';
67
+ var s = Math.max(0, (Date.now() - t) / 1000);
68
+ if (s < 60) return 'just now';
69
+ if (s < 3600) return Math.floor(s / 60) + 'm ago';
70
+ if (s < 86400) return Math.floor(s / 3600) + 'h ago';
71
+ return Math.floor(s / 86400) + 'd ago';
72
+ }
73
+
74
+ function row(item) {
75
+ var a = document.createElement('a');
76
+ a.href = safeHref(item.link);
77
+ a.className = 'dropdown-item py-2 border-bottom' + (item.is_read ? '' : ' bg-light fw-semibold');
78
+ a.style.whiteSpace = 'normal';
79
+
80
+ var top = document.createElement('div');
81
+ top.className = 'small';
82
+ if (item.actor_name) {
83
+ var who = document.createElement('span');
84
+ who.textContent = item.actor_name + ' ';
85
+ top.appendChild(who);
86
+ }
87
+ var what = document.createElement('span');
88
+ what.className = 'text-muted';
89
+ what.textContent = item.title || '';
90
+ top.appendChild(what);
91
+ a.appendChild(top);
92
+
93
+ var meta = document.createElement('div');
94
+ meta.className = 'text-muted';
95
+ meta.style.fontSize = '0.72rem';
96
+ meta.textContent = relTime(item.created_at);
97
+ a.appendChild(meta);
98
+
99
+ a.addEventListener('click', function () {
100
+ if (!item.is_read) { post(BASE + '/' + item.id + '/read'); } // navigation continues
101
+ });
102
+ return a;
103
+ }
104
+
105
+ function render(data) {
106
+ setBadge(data.unread || 0);
107
+ list.textContent = '';
108
+ if (!data.items || !data.items.length) {
109
+ var empty = document.createElement('div');
110
+ empty.className = 'text-muted small px-3 py-3';
111
+ empty.textContent = 'No notifications yet.';
112
+ list.appendChild(empty);
113
+ return;
114
+ }
115
+ data.items.forEach(function (it) { list.appendChild(row(it)); });
116
+ }
117
+
118
+ function sync() {
119
+ fetch(BASE + '/recent', { credentials: 'same-origin' })
120
+ .then(function (r) { return r.ok ? r.json() : null; })
121
+ .then(function (d) { if (d) render(d); })
122
+ .catch(function () {});
123
+ }
124
+
125
+ if (readAllBtn) {
126
+ readAllBtn.addEventListener('click', function () { post(BASE + '/read-all').then(sync).catch(function () {}); });
127
+ }
128
+
129
+ if (FILL === 'open') {
130
+ // Server-rendered badge stands until the dropdown is opened; degrades to a plain link with JS off.
131
+ var filled = false;
132
+ menu.addEventListener('show.bs.dropdown', function () { if (!filled) { filled = true; sync(); } });
133
+ } else {
134
+ sync(); // initial paint
135
+ }
136
+
137
+ // ── The stream ──────────────────────────────────────────────────────────────────────────────
138
+ var es = null;
139
+ var firstOpen = true;
140
+
141
+ function streamUrl() {
142
+ var params = [];
143
+ document.querySelectorAll('[data-notif-stream-param]').forEach(function (el) {
144
+ var p = el.getAttribute('data-notif-stream-param');
145
+ if (p) params.push(p);
146
+ });
147
+ return BASE + '/stream' + (params.length ? '?' + params.join('&') : '');
148
+ }
149
+
150
+ function openStream() {
151
+ if (!window.EventSource || es) return;
152
+ try {
153
+ es = new EventSource(streamUrl());
154
+ es.onmessage = function (ev) {
155
+ var d = null;
156
+ try { d = JSON.parse(ev.data); } catch (_) { /* keep the notif behaviour */ }
157
+ // EVERY frame goes back out as a DOM event — the seam that lets app features (a live
158
+ // ticket page, a draft indicator, a version-skew banner) ride this connection without
159
+ // knowing it exists, and without burning a second one.
160
+ if (d) document.dispatchEvent(new CustomEvent('aria:sse', { detail: d }));
161
+ if (!d || QUIET.indexOf(d.type) === -1) sync();
162
+ };
163
+ es.onopen = function () {
164
+ sync(); // self-heal the badge on every open, reconnects included
165
+ var wasFirst = firstOpen;
166
+ firstOpen = false;
167
+ document.dispatchEvent(new CustomEvent('aria:sse-open', { detail: { firstOpen: wasFirst } }));
168
+ };
169
+ } catch (e) { es = null; }
170
+ }
171
+ function closeStream() { if (es) { es.close(); es = null; } }
172
+
173
+ openStream();
174
+ // Release the connection when leaving or backgrounding; reopen on visible/bfcache restore.
175
+ window.addEventListener('pagehide', closeStream);
176
+ document.addEventListener('visibilitychange', function () {
177
+ if (document.visibilityState === 'hidden') { closeStream(); }
178
+ else { sync(); openStream(); }
179
+ });
180
+ })();
package/index.js CHANGED
@@ -15,8 +15,18 @@
15
15
 
16
16
  'use strict';
17
17
 
18
+ const path = require('path');
19
+
18
20
  module.exports = {
19
21
  ...require('./store'),
20
22
  ...require('./hub'),
21
- ...require('./emit')
23
+ ...require('./emit'),
24
+ // 0.2.0 — the bell CLIENT (2026-08-22 audit): both apps hand-rolled one against this package's
25
+ // server half, each with a fix the other lacked. assets/bell.js owns the page's ONE SSE
26
+ // connection and re-dispatches every frame as DOM events ('aria:sse', 'aria:sse-open');
27
+ // views/notify/bell.ejs is the markup half, shipped together so the hook names cannot drift.
28
+ // staticDirs.push({ mount: '/js/notify', dir: notify.assetsDir })
29
+ // viewDirs.push(notify.viewsDir)
30
+ assetsDir: path.join(__dirname, 'assets'),
31
+ viewsDir: path.join(__dirname, 'views')
22
32
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/notify",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Aria App Framework — notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery, and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -12,7 +12,9 @@
12
12
  "index.js",
13
13
  "store.js",
14
14
  "hub.js",
15
- "emit.js"
15
+ "emit.js",
16
+ "assets/",
17
+ "views/"
16
18
  ],
17
19
  "peerDependencies": {
18
20
  "better-sqlite3": ">=11"
@@ -23,6 +25,6 @@
23
25
  }
24
26
  },
25
27
  "scripts": {
26
- "test": "node test/store.js && node test/hub.js && node test/emit.js"
28
+ "test": "node test/store.js && node test/hub.js && node test/emit.js && node test/bell.js"
27
29
  }
28
30
  }
@@ -0,0 +1,37 @@
1
+ <%# The notification bell — markup half of assets/bell.js, shipped together so the hook names
2
+ (#notif-menu, data-notif-badge/-list/-readall) cannot drift from the script that binds them.
3
+ Both apps carried this dropdown skeleton with different hook spellings; this is the one shape.
4
+
5
+ Include locals (all optional):
6
+ notifBase route prefix (default '/notifications')
7
+ notifFill 'load' | 'open' (default 'load'; 'open' fills on first
8
+ dropdown open — pair it with notifUnread)
9
+ notifQuiet comma list of SSE frame types that must NOT re-sync the bell (e.g. 'ticket,draft')
10
+ notifUnread server-rendered initial unread count (keeps the badge honest before JS runs,
11
+ and with JS off the bell stays a working link to the notifications page)
12
+ notifWidth dropdown width (default '340px') %>
13
+ <%
14
+ var __base = (typeof notifBase === 'undefined') ? '/notifications' : notifBase;
15
+ var __fill = (typeof notifFill === 'undefined') ? 'load' : notifFill;
16
+ var __quiet = (typeof notifQuiet === 'undefined') ? '' : notifQuiet;
17
+ var __unread = (typeof notifUnread === 'undefined') ? 0 : Number(notifUnread) || 0;
18
+ var __width = (typeof notifWidth === 'undefined') ? '340px' : notifWidth;
19
+ %>
20
+ <div class="dropdown" id="notif-menu" data-notif-base="<%= __base %>" data-notif-fill="<%= __fill %>"<% if (__quiet) { %> data-notif-quiet="<%= __quiet %>"<% } %>>
21
+ <a href="<%= __base %>" class="bell-btn" role="button"
22
+ data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false" title="Notifications">
23
+ <i class="bi bi-bell"></i>
24
+ <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"
25
+ data-notif-badge <% if (!__unread) { %>hidden<% } %>><%= __unread > 99 ? '99+' : __unread %></span>
26
+ </a>
27
+ <div class="dropdown-menu dropdown-menu-end shadow border-0" style="width: <%= __width %>;">
28
+ <div class="d-flex justify-content-between align-items-center px-3 py-2 border-bottom">
29
+ <strong class="small">Notifications</strong>
30
+ <button type="button" class="btn btn-link btn-sm p-0 text-decoration-none" data-notif-readall>Mark all read</button>
31
+ </div>
32
+ <div data-notif-list style="max-height: 360px; overflow-y: auto;">
33
+ <div class="text-muted small px-3 py-3">Loading…</div>
34
+ </div>
35
+ <a class="dropdown-item text-center small border-top text-muted" href="<%= __base %>">See all</a>
36
+ </div>
37
+ </div>