@prunellejs/live 0.1.1 → 0.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -15,8 +15,8 @@
15
15
  - `path`: route path (e.g. `'/api/events'`).
16
16
  - `room`: room name or `(ctx: RequestContext) => string` (default `'default'`).
17
17
  - `member`: `(ctx: RequestContext) => TMember | Promise<TMember>` (required when `path` is set).
18
- - `authorize`: `(ctx, room) => boolean | Response | Promise<boolean | Response>` (`false` → `403`).
19
- - `pingMs`: keepalive interval in ms (default `20000`, `0` disables).
18
+ - `authorize`: `(ctx, room) => boolean | Response | Promise<boolean | Response>` (`false` → `403`); runs after the connection caps (`429` per client, `503` per room or total). Without it the channel is public and `prunelle check` warns `[live/authorize]`: pass `authorize: () => true` to say so.
19
+ - `pingMs`: keepalive interval in ms (default `20000`, `0` disables); one timer per interval serves every subscriber. A throwing `onJoin` or `onLeave` is logged, and the stream still closes and frees its slot.
20
20
  - `onJoin(room, member)`, `onLeave(room, member)`.
21
21
  - Manual route mode (omit `path`): no route mounted; return `rooms.stream(ctx, { room, member, pingMs?, onJoin?, onLeave?, ...limits })` from a `GET` route handler.
22
22
  - `ConnectionLimits`: `maxConnectionsPerRoom` (`1000`), `maxConnectionsPerClient` (`10`, returns `429`), `maxTotalConnections` (`10000`, returns `503`), `clientKey(ctx)` (defaults to `ctx.ip`), `highWaterMark` (`64`).
@@ -24,9 +24,9 @@
24
24
  ## Handle Methods & Client Hook
25
25
 
26
26
  - `rooms.publish(room, message, event?, id?)`: broadcasts JSON-serialized SSE frames to all room subscribers.
27
- - `rooms.coalesce(build, event?)`: returns `(room) => void` that batches burst updates into one microtask broadcast per room.
27
+ - `rooms.coalesce(build, event?)`: returns `(room) => void` that batches burst updates into one microtask broadcast per room; a `build` that throws, or a message JSON cannot encode (a BigInt), is logged and dropped.
28
28
  - `rooms.members(room)`, `rooms.size(room)`, `rooms.stream(ctx, opts)`, `rooms.join(room, sub)`, `rooms.leave(room, sub)`.
29
- - `useLive<TMessage>(url, onMessage?, options?)` (`@prunellejs/live/client`): returns `{ status: Signal<'connecting' | 'open' | 'closed'>, last: Signal<TMessage | undefined>, close() }` with exponential-backoff reconnect (`baseDelayMs`, `maxDelayMs`, `jitterMs`, `events`, `withCredentials`) and automatic `onMount` cleanup.
29
+ - `useLive<TMessage>(url, onMessage?, options?)` (`@prunellejs/live/client`): returns `{ status: Signal<'connecting' | 'open' | 'closed'>, last: Signal<TMessage | undefined>, close() }` and closes on unmount. `onMessage(message, type)` gets the SSE event type (`'message'` or a name from `events`) and its errors are not caught; a frame that is not JSON is skipped. Options: `baseDelayMs` (1000), `maxDelayMs` (30000), `maxRetries`, `events`, `withCredentials`. Reconnect waits a random delay up to the doubling backoff capped at `maxDelayMs`, without end once the stream has opened (2 retries if it never did, which stops a wrong URL), none while the page is hidden, and at once when the page is shown again or back `online`.
30
30
 
31
31
  ## Snippets
32
32
 
@@ -37,6 +37,7 @@ import { createRooms } from '@prunellejs/live'
37
37
  export type ChatMsg = { from: string, text: string }
38
38
  export const chat = createRooms<ChatMsg, { name: string }>({
39
39
  path: '/api/chat',
40
+ authorize: ctx => ctx.locals.user !== undefined,
40
41
  room: ctx => ctx.url.searchParams.get('room') ?? 'general',
41
42
  member: ctx => ({ name: ctx.locals.user?.name ?? 'guest' }),
42
43
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/live",
3
- "version": "0.1.1",
3
+ "version": "0.7.0",
4
4
  "description": "Zero-dependency typed SSE rooms and coalesced presence plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,6 +22,6 @@
22
22
  "directory": "packages/plugin-live"
23
23
  },
24
24
  "peerDependencies": {
25
- "prunelle": "^0.1.1"
25
+ "prunelle": "^0.7.0"
26
26
  }
27
27
  }
package/src/client.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Browser client helper for @prunellejs/live SSE rooms (~65 LOC, zero dependencies).
1
+ // Browser client helper for @prunellejs/live SSE rooms (zero dependencies).
2
2
 
3
3
  import type { Signal } from 'prunelle'
4
4
  import { onMount, signal } from 'prunelle'
@@ -14,11 +14,9 @@ export interface LiveConnection<TMessage> {
14
14
  export interface UseLiveOptions {
15
15
  /** Base reconnect delay in milliseconds after EventSource enters CLOSED state (default: 1000). */
16
16
  baseDelayMs?: number | undefined
17
- /** Maximum exponential backoff delay in milliseconds before jitter (default: 30000). */
17
+ /** Cap of the exponential backoff in milliseconds; each delay is a random value up to it (default: 30000). */
18
18
  maxDelayMs?: number | undefined
19
- /** Maximum random jitter added in milliseconds (default: 30% of current delay). */
20
- jitterMs?: number | undefined
21
- /** Maximum consecutive failed reconnect attempts before staying closed (default: 5; resets on open). */
19
+ /** Consecutive failed reconnects before staying closed (default: unlimited once opened, 2 before; resets on open). */
22
20
  maxRetries?: number | undefined
23
21
  /** Named SSE `event:` types to listen for in addition to default unnamed `message` events. */
24
22
  events?: readonly string[] | undefined
@@ -28,11 +26,11 @@ export interface UseLiveOptions {
28
26
 
29
27
  const DEFAULT_BASE_DELAY_MS = 1_000
30
28
  const DEFAULT_MAX_DELAY_MS = 30_000
31
- const DEFAULT_MAX_RETRIES = 5
29
+ const DEFAULT_INITIAL_MAX_RETRIES = 2
32
30
 
33
31
  export function useLive<TMessage>(
34
32
  url: string,
35
- onMessage?: (message: TMessage) => void,
33
+ onMessage?: (message: TMessage, type: string) => void,
36
34
  options?: UseLiveOptions,
37
35
  ): LiveConnection<TMessage> {
38
36
  const status = signal<LiveStatus>('connecting')
@@ -40,6 +38,7 @@ export function useLive<TMessage>(
40
38
  let source: EventSource | undefined
41
39
  let reconnectTimer: ReturnType<typeof setTimeout> | undefined
42
40
  let attempt = 0
41
+ let hasOpened = false
43
42
  let manuallyClosed = false
44
43
 
45
44
  const clearReconnectTimer = () => {
@@ -49,17 +48,35 @@ export function useLive<TMessage>(
49
48
  }
50
49
  }
51
50
 
51
+ // A closed connection the app did not close reconnects now; a hidden page waits until it is shown.
52
+ const wake = () => {
53
+ if (source !== undefined || document.hidden)
54
+ return
55
+ connect()
56
+ }
57
+
52
58
  const close = () => {
53
59
  manuallyClosed = true
54
60
  clearReconnectTimer()
55
61
  source?.close()
56
62
  source = undefined
57
63
  status.value = 'closed'
64
+ removeEventListener('online', wake)
65
+ document.removeEventListener('visibilitychange', wake)
58
66
  }
59
67
 
60
- const connect = () => {
61
- if (manuallyClosed)
68
+ const scheduleReconnect = () => {
69
+ const maxRetries = options?.maxRetries ?? (hasOpened ? Infinity : DEFAULT_INITIAL_MAX_RETRIES)
70
+ if (attempt >= maxRetries)
62
71
  return
72
+ const cap = Math.min(options?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS, (options?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS) * 2 ** attempt++)
73
+ reconnectTimer = setTimeout(() => {
74
+ reconnectTimer = undefined
75
+ wake()
76
+ }, Math.random() * cap)
77
+ }
78
+
79
+ const connect = () => {
63
80
  clearReconnectTimer()
64
81
  status.value = 'connecting'
65
82
  const es = options?.withCredentials !== undefined
@@ -70,38 +87,22 @@ export function useLive<TMessage>(
70
87
  es.onopen = () => {
71
88
  if (source !== es || manuallyClosed)
72
89
  return
90
+ hasOpened = true
73
91
  attempt = 0
74
92
  status.value = 'open'
75
93
  }
76
94
 
77
- es.onerror = (ev?: Event) => {
95
+ es.onerror = () => {
78
96
  if (source !== es || manuallyClosed)
79
97
  return
80
- const errStatus = (ev as { status?: unknown } | undefined)?.status
81
- if (errStatus === 401 || errStatus === 403 || errStatus === 404) {
82
- es.close()
83
- source = undefined
84
- status.value = 'closed'
85
- return
86
- }
87
- if (es.readyState === EventSource.CLOSED) {
88
- status.value = 'closed'
89
- source = undefined
90
- if (attempt >= (options?.maxRetries ?? DEFAULT_MAX_RETRIES))
91
- return
92
- const base = options?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS
93
- const max = options?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS
94
- const exp = Math.min(max, base * 2 ** attempt++)
95
- const maxJitter = options?.jitterMs ?? Math.max(1, Math.floor(exp * 0.3))
96
- const jitter = maxJitter > 0 ? Math.floor(Math.random() * maxJitter) : 0
97
- reconnectTimer = setTimeout(() => {
98
- reconnectTimer = undefined
99
- connect()
100
- }, exp + jitter)
101
- }
102
- else {
98
+ if (es.readyState !== EventSource.CLOSED) {
103
99
  status.value = 'connecting'
100
+ return
104
101
  }
102
+ es.close()
103
+ status.value = 'closed'
104
+ source = undefined
105
+ scheduleReconnect()
105
106
  }
106
107
 
107
108
  const handleEvent = (ev: Event) => {
@@ -110,14 +111,15 @@ export function useLive<TMessage>(
110
111
  const data = (ev as MessageEvent<unknown>).data
111
112
  if (typeof data !== 'string')
112
113
  return
114
+ let parsed: TMessage
113
115
  try {
114
- const parsed = JSON.parse(data) as TMessage
115
- last.value = parsed
116
- onMessage?.(parsed)
116
+ parsed = JSON.parse(data) as TMessage
117
117
  }
118
118
  catch {
119
- // Ignore malformed non-JSON SSE frames.
119
+ return // a frame that is not JSON carries no message
120
120
  }
121
+ last.value = parsed
122
+ onMessage?.(parsed, ev.type)
121
123
  }
122
124
 
123
125
  es.onmessage = handleEvent
@@ -131,6 +133,8 @@ export function useLive<TMessage>(
131
133
 
132
134
  onMount(() => {
133
135
  manuallyClosed = false
136
+ addEventListener('online', wake)
137
+ document.addEventListener('visibilitychange', wake)
134
138
  connect()
135
139
  return close
136
140
  })
package/src/index.ts CHANGED
@@ -107,26 +107,26 @@ const RETRY_CHUNK = encoder.encode('retry: 2000\n\n')
107
107
  interface RoomState<TMember> {
108
108
  readonly defaultOpts: RoomsOptions<TMember>
109
109
  readonly clientCounts: Map<string, number>
110
+ /** Pings `sub` every `ms` on the timer all subscribers of that interval share; returns the call that stops it. */
111
+ schedulePing(ms: number, sub: Subscriber<TMember>): () => void
110
112
  join(room: string, sub: Subscriber<TMember>): void
111
113
  leave(room: string, sub: Subscriber<TMember>): void
112
114
  size(room: string): number
113
115
  getActiveConnections(): number
114
116
  }
115
117
 
116
- function openRoomStream<TMember>(
117
- state: RoomState<TMember>,
118
- ctx: RequestContext,
119
- opts: StreamOptions<TMember>,
120
- ): Response {
121
- const { room, member, pingMs = 20_000, onJoin, onLeave } = opts
118
+ function clientIdOf<TMember>(state: RoomState<TMember>, ctx: RequestContext, opts: ConnectionLimits): string | undefined {
119
+ const rawClientId = (opts.clientKey ?? state.defaultOpts.clientKey ?? defaultClientKey)(ctx)
120
+ return rawClientId !== undefined && rawClientId.length > 0 ? rawClientId : undefined
121
+ }
122
+
123
+ /** The 429 or 503 a request meets when a cap is full, undefined while it fits: counts only, so it can run before `authorize`. */
124
+ function refusalForCaps<TMember>(state: RoomState<TMember>, ctx: RequestContext, room: string, opts: ConnectionLimits): Response | undefined {
122
125
  const { defaultOpts, clientCounts } = state
123
126
  const maxPerRoom = opts.maxConnectionsPerRoom ?? defaultOpts.maxConnectionsPerRoom ?? DEFAULT_MAX_PER_ROOM
124
127
  const maxPerClient = opts.maxConnectionsPerClient ?? defaultOpts.maxConnectionsPerClient ?? DEFAULT_MAX_PER_CLIENT
125
128
  const maxTotal = opts.maxTotalConnections ?? defaultOpts.maxTotalConnections ?? DEFAULT_MAX_TOTAL
126
- const highWaterMark = opts.highWaterMark ?? defaultOpts.highWaterMark ?? DEFAULT_HIGH_WATER_MARK
127
- const resolveClientKey = opts.clientKey ?? defaultOpts.clientKey ?? defaultClientKey
128
- const rawClientId = resolveClientKey(ctx)
129
- const clientId = rawClientId !== undefined && rawClientId.length > 0 ? rawClientId : undefined
129
+ const clientId = clientIdOf(state, ctx, opts)
130
130
 
131
131
  if (clientId !== undefined && maxPerClient > 0 && (clientCounts.get(clientId) ?? 0) >= maxPerClient) {
132
132
  return new Response('Too Many Requests', {
@@ -141,10 +141,26 @@ function openRoomStream<TMember>(
141
141
  headers: { 'retry-after': '5' },
142
142
  })
143
143
  }
144
+ return undefined
145
+ }
146
+
147
+ function openRoomStream<TMember>(
148
+ state: RoomState<TMember>,
149
+ ctx: RequestContext,
150
+ opts: StreamOptions<TMember>,
151
+ ): Response {
152
+ const { room, member, pingMs = 20_000, onJoin, onLeave } = opts
153
+ const { defaultOpts, clientCounts } = state
154
+ const highWaterMark = opts.highWaterMark ?? defaultOpts.highWaterMark ?? DEFAULT_HIGH_WATER_MARK
155
+ const clientId = clientIdOf(state, ctx, opts)
156
+
157
+ const refused = refusalForCaps(state, ctx, room, opts)
158
+ if (refused !== undefined)
159
+ return refused
144
160
 
145
161
  let cleaned = false
146
162
  let joined = false
147
- let timer: ReturnType<typeof setInterval> | undefined
163
+ let stopPing: (() => void) | undefined
148
164
  let sub: Subscriber<TMember> | undefined
149
165
  let countedClient = false
150
166
  let abortHandler: (() => void) | undefined
@@ -157,10 +173,8 @@ function openRoomStream<TMember>(
157
173
  ctx.request.signal.removeEventListener('abort', abortHandler)
158
174
  abortHandler = undefined
159
175
  }
160
- if (timer !== undefined) {
161
- clearInterval(timer)
162
- timer = undefined
163
- }
176
+ stopPing?.()
177
+ stopPing = undefined
164
178
  if (countedClient && clientId !== undefined) {
165
179
  countedClient = false
166
180
  const remaining = (clientCounts.get(clientId) ?? 1) - 1
@@ -171,8 +185,15 @@ function openRoomStream<TMember>(
171
185
  }
172
186
  if (sub !== undefined) {
173
187
  state.leave(room, sub)
174
- if (joined)
175
- onLeave?.(room, member)
188
+ // A throwing hook of the app must not stop the stream from closing.
189
+ if (joined) {
190
+ try {
191
+ onLeave?.(room, member)
192
+ }
193
+ catch (error) {
194
+ console.error(`@prunellejs/live: onLeave of room "${room}" threw:`, error)
195
+ }
196
+ }
176
197
  }
177
198
  }
178
199
 
@@ -216,20 +237,20 @@ function openRoomStream<TMember>(
216
237
  try {
217
238
  controller.enqueue(RETRY_CHUNK)
218
239
  state.join(room, sub)
219
- onJoin?.(room, member)
220
240
  joined = true
241
+ onJoin?.(room, member)
221
242
  }
222
243
  catch (err) {
244
+ joined = false
223
245
  cleanup()
224
246
  throw err
225
247
  }
226
248
 
227
- if (pingMs > 0) {
228
- timer = setInterval(() => {
229
- sub?.send(PING_CHUNK)
230
- }, pingMs)
231
- ;(timer as unknown as { unref?: () => void }).unref?.()
232
- }
249
+ if (cleaned)
250
+ return
251
+
252
+ if (pingMs > 0)
253
+ stopPing = state.schedulePing(pingMs, sub)
233
254
 
234
255
  if (ctx.request.signal.aborted) {
235
256
  drop()
@@ -324,17 +345,50 @@ export function createRooms<TMessage, TMember = undefined>(
324
345
  if (pending.has(room))
325
346
  return
326
347
  pending.add(room)
348
+ // Nothing awaits this microtask, so a throwing builder or an unencodable message (a BigInt) would exit the process.
327
349
  queueMicrotask(() => {
328
350
  pending.delete(room)
329
- if (size(room) > 0)
351
+ if (size(room) === 0)
352
+ return
353
+ try {
330
354
  publish(room, build(room), event)
355
+ }
356
+ catch (error) {
357
+ console.error(`@prunellejs/live: coalesced message for room "${room}" was dropped:`, error)
358
+ }
331
359
  })
332
360
  }
333
361
  }
334
362
 
363
+ // One timer per ping interval, however many subscribers share it; it stops with the last of them.
364
+ const pingers = new Map<number, { subs: Set<Subscriber<TMember>>, timer: ReturnType<typeof setInterval> }>()
365
+ function schedulePing(ms: number, sub: Subscriber<TMember>): () => void {
366
+ let pinger = pingers.get(ms)
367
+ if (pinger === undefined) {
368
+ const subs = new Set<Subscriber<TMember>>()
369
+ const timer = setInterval(() => {
370
+ for (const each of [...subs])
371
+ each.send(PING_CHUNK)
372
+ }, ms)
373
+ ;(timer as unknown as { unref?: () => void }).unref?.()
374
+ pinger = { subs, timer }
375
+ pingers.set(ms, pinger)
376
+ }
377
+ const held = pinger
378
+ held.subs.add(sub)
379
+ return () => {
380
+ held.subs.delete(sub)
381
+ if (held.subs.size === 0 && pingers.get(ms) === held) {
382
+ clearInterval(held.timer)
383
+ pingers.delete(ms)
384
+ }
385
+ }
386
+ }
387
+
335
388
  const roomState: RoomState<TMember> = {
336
389
  defaultOpts,
337
390
  clientCounts,
391
+ schedulePing,
338
392
  join,
339
393
  leave,
340
394
  size,
@@ -358,10 +412,18 @@ export function createRooms<TMessage, TMember = undefined>(
358
412
  throw new TypeError(`@prunellejs/live: createRooms({ path: '${opts.path}' }) needs member(ctx), the member each stream joins as`)
359
413
  return definePlugin({
360
414
  name: `@prunellejs/live(${opts.path})`,
415
+ check(ctx) {
416
+ if (opts.authorize === undefined)
417
+ ctx.warn(`prunelle.config.ts:1:1: warning: [live/authorize] the channel at ${opts.path} has no authorize, so anyone who can reach it joins the room and reads what it publishes: pass authorize(ctx, room) to say who may join, or authorize: () => true to say the channel is public.`)
418
+ },
361
419
  server(api) {
362
420
  api.onShutdown(closeAll)
363
421
  api.route('GET', opts.path, async (ctx) => {
364
422
  const room = typeof opts.room === 'function' ? opts.room(ctx) : (opts.room ?? 'default')
423
+ // Counts first: a flood of requests a full cap would refuse anyway never reaches the app's authorize.
424
+ const refused = refusalForCaps(roomState, ctx, room, opts)
425
+ if (refused !== undefined)
426
+ return refused
365
427
  if (opts.authorize !== undefined) {
366
428
  const decision = await opts.authorize(ctx, room)
367
429
  if (decision instanceof Response)