@prunellejs/live 0.6.0 → 0.7.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.
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.6.0",
3
+ "version": "0.7.1",
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.6.0"
25
+ "prunelle": "^0.7.1"
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,16 +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
32
29
  const DEFAULT_INITIAL_MAX_RETRIES = 2
33
30
 
34
- function isPermanentHttpStatus(status: unknown): boolean {
35
- return typeof status === 'number' && status >= 400 && status < 500 && status !== 408 && status !== 429
36
- }
37
-
38
31
  export function useLive<TMessage>(
39
32
  url: string,
40
- onMessage?: (message: TMessage) => void,
33
+ onMessage?: (message: TMessage, type: string) => void,
41
34
  options?: UseLiveOptions,
42
35
  ): LiveConnection<TMessage> {
43
36
  const status = signal<LiveStatus>('connecting')
@@ -47,6 +40,7 @@ export function useLive<TMessage>(
47
40
  let attempt = 0
48
41
  let hasOpened = false
49
42
  let manuallyClosed = false
43
+ let exhausted = false
50
44
 
51
45
  const clearReconnectTimer = () => {
52
46
  if (reconnectTimer !== undefined) {
@@ -55,17 +49,43 @@ export function useLive<TMessage>(
55
49
  }
56
50
  }
57
51
 
52
+ const detachWake = () => {
53
+ removeEventListener('online', wake)
54
+ document.removeEventListener('visibilitychange', wake)
55
+ }
56
+
57
+ // A closed connection the app did not close reconnects now; a hidden page waits until it is shown.
58
+ const wake = () => {
59
+ if (source !== undefined || document.hidden || manuallyClosed || exhausted)
60
+ return
61
+ connect()
62
+ }
63
+
58
64
  const close = () => {
59
65
  manuallyClosed = true
60
66
  clearReconnectTimer()
61
67
  source?.close()
62
68
  source = undefined
63
69
  status.value = 'closed'
70
+ detachWake()
64
71
  }
65
72
 
66
- const connect = () => {
67
- if (manuallyClosed)
73
+ const scheduleReconnect = () => {
74
+ const maxRetries = options?.maxRetries ?? (hasOpened ? Infinity : DEFAULT_INITIAL_MAX_RETRIES)
75
+ if (attempt >= maxRetries) {
76
+ exhausted = true
77
+ detachWake()
68
78
  return
79
+ }
80
+ const exp = Math.min(attempt++, 30)
81
+ const cap = Math.min(options?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS, (options?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS) * 2 ** exp)
82
+ reconnectTimer = setTimeout(() => {
83
+ reconnectTimer = undefined
84
+ wake()
85
+ }, Math.random() * cap)
86
+ }
87
+
88
+ const connect = () => {
69
89
  clearReconnectTimer()
70
90
  status.value = 'connecting'
71
91
  const es = options?.withCredentials !== undefined
@@ -81,36 +101,17 @@ export function useLive<TMessage>(
81
101
  status.value = 'open'
82
102
  }
83
103
 
84
- es.onerror = (ev?: Event) => {
104
+ es.onerror = () => {
85
105
  if (source !== es || manuallyClosed)
86
106
  return
87
- const errStatus = (ev as { status?: unknown } | undefined)?.status
88
- if (isPermanentHttpStatus(errStatus)) {
89
- es.close()
90
- source = undefined
91
- status.value = 'closed'
92
- return
93
- }
94
- if (es.readyState === EventSource.CLOSED) {
95
- es.close()
96
- status.value = 'closed'
97
- source = undefined
98
- const maxRetries = options?.maxRetries ?? (hasOpened ? DEFAULT_MAX_RETRIES : DEFAULT_INITIAL_MAX_RETRIES)
99
- if (attempt >= maxRetries)
100
- return
101
- const base = options?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS
102
- const max = options?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS
103
- const exp = Math.min(max, base * 2 ** attempt++)
104
- const maxJitter = options?.jitterMs ?? Math.max(1, Math.floor(exp * 0.3))
105
- const jitter = maxJitter > 0 ? Math.floor(Math.random() * maxJitter) : 0
106
- reconnectTimer = setTimeout(() => {
107
- reconnectTimer = undefined
108
- connect()
109
- }, exp + jitter)
110
- }
111
- else {
107
+ if (es.readyState !== EventSource.CLOSED) {
112
108
  status.value = 'connecting'
109
+ return
113
110
  }
111
+ es.close()
112
+ status.value = 'closed'
113
+ source = undefined
114
+ scheduleReconnect()
114
115
  }
115
116
 
116
117
  const handleEvent = (ev: Event) => {
@@ -119,14 +120,15 @@ export function useLive<TMessage>(
119
120
  const data = (ev as MessageEvent<unknown>).data
120
121
  if (typeof data !== 'string')
121
122
  return
123
+ let parsed: TMessage
122
124
  try {
123
- const parsed = JSON.parse(data) as TMessage
124
- last.value = parsed
125
- onMessage?.(parsed)
125
+ parsed = JSON.parse(data) as TMessage
126
126
  }
127
127
  catch {
128
- // Ignore malformed non-JSON SSE frames.
128
+ return // a frame that is not JSON carries no message
129
129
  }
130
+ last.value = parsed
131
+ onMessage?.(parsed, ev.type)
130
132
  }
131
133
 
132
134
  es.onmessage = handleEvent
@@ -140,6 +142,9 @@ export function useLive<TMessage>(
140
142
 
141
143
  onMount(() => {
142
144
  manuallyClosed = false
145
+ exhausted = false
146
+ addEventListener('online', wake)
147
+ document.addEventListener('visibilitychange', wake)
143
148
  connect()
144
149
  return close
145
150
  })
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
 
@@ -228,12 +249,8 @@ function openRoomStream<TMember>(
228
249
  if (cleaned)
229
250
  return
230
251
 
231
- if (pingMs > 0) {
232
- timer = setInterval(() => {
233
- sub?.send(PING_CHUNK)
234
- }, pingMs)
235
- ;(timer as unknown as { unref?: () => void }).unref?.()
236
- }
252
+ if (pingMs > 0)
253
+ stopPing = state.schedulePing(pingMs, sub)
237
254
 
238
255
  if (ctx.request.signal.aborted) {
239
256
  drop()
@@ -328,17 +345,50 @@ export function createRooms<TMessage, TMember = undefined>(
328
345
  if (pending.has(room))
329
346
  return
330
347
  pending.add(room)
348
+ // Nothing awaits this microtask, so a throwing builder or an unencodable message (a BigInt) would exit the process.
331
349
  queueMicrotask(() => {
332
350
  pending.delete(room)
333
- if (size(room) > 0)
351
+ if (size(room) === 0)
352
+ return
353
+ try {
334
354
  publish(room, build(room), event)
355
+ }
356
+ catch (error) {
357
+ console.error(`@prunellejs/live: coalesced message for room "${room}" was dropped:`, error)
358
+ }
335
359
  })
336
360
  }
337
361
  }
338
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
+
339
388
  const roomState: RoomState<TMember> = {
340
389
  defaultOpts,
341
390
  clientCounts,
391
+ schedulePing,
342
392
  join,
343
393
  leave,
344
394
  size,
@@ -362,10 +412,18 @@ export function createRooms<TMessage, TMember = undefined>(
362
412
  throw new TypeError(`@prunellejs/live: createRooms({ path: '${opts.path}' }) needs member(ctx), the member each stream joins as`)
363
413
  return definePlugin({
364
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
+ },
365
419
  server(api) {
366
420
  api.onShutdown(closeAll)
367
421
  api.route('GET', opts.path, async (ctx) => {
368
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
369
427
  if (opts.authorize !== undefined) {
370
428
  const decision = await opts.authorize(ctx, room)
371
429
  if (decision instanceof Response)