@stacksjs/realtime 0.75.582 → 0.75.585

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
@@ -1,37 +1,40 @@
1
1
  # Stacks Realtime
2
2
 
3
- wip
3
+ Native WebSocket broadcasting and authenticated HTTP event streams, with
4
+ opt-in process-local replay, explicit durable SQL replay, and Redis invalidation hints.
4
5
 
5
- ## ☘️ Features
6
+ ```ts
7
+ import { emit, createBroadcastResponse } from '@stacksjs/realtime'
6
8
 
7
- wip
8
-
9
- - ⚡️
10
-
11
- wip
12
-
13
- ## 🤖 Usage
14
-
15
- wip
16
-
17
- ```bash
18
- bun install -d @stacksjs/realtime
9
+ emit('orders.42', 'changed', { orderId: 42 }, { private: true })
19
10
  ```
20
11
 
21
- Now, you can use it in your project:
12
+ Initialize the native broadcast server/hub before emitting. Stream consumers
13
+ supply current per-request authorization; a channel name is not authority.
22
14
 
23
- ```js
24
- import realtime from '@stacksjs/realtime'
15
+ For durable history, use `createSqlDurableReplayStore` with app-owned generated
16
+ tables and a transaction-bound SQL adapter. Await `append` before notifying.
17
+ `createDurableReplayResponse` checks authorization before and after replay.
18
+ Existing synchronous broadcasting and `replaySince` remain unchanged.
25
19
 
26
- // wip
27
- ```
20
+ The [durable replay contract and model examples](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/realtime/docs/durable-replay.md)
21
+ cover atomic per-channel sequences, incarnation-bound cursors, bounded retention
22
+ and idempotency, response gaps, and the absence of live cluster fan-out or
23
+ exactly-once delivery. The deterministic fake is `createMemoryDurableReplayStore`.
28
24
 
29
- Learn more in the docs.
25
+ For cross-worker HTTP wake-ups, explicitly create `createRedisInvalidationBus`
26
+ and pass it as `createBroadcastResponse({ invalidations, ... })`. The bus uses
27
+ operator-owned Redis connections and namespaces, carries only metadata, and
28
+ retains current per-request/channel authorization. Local callers are unchanged.
29
+ The [Redis invalidation contract](https://github.com/stacksjs/stacks/blob/main/storage/framework/core/realtime/docs/redis-invalidations.md)
30
+ covers Bun's experimental Pub/Sub interface, owned-service evidence, bounds,
31
+ reconnect resync, readonly status and at-most-once limitations. Set
32
+ `STACKS_TEST_REDIS_BINARY` to run the isolated live Redis fixture cases.
30
33
 
31
- ## 🧪 Testing
34
+ Run the package tests from the framework root:
32
35
 
33
36
  ```bash
34
- bun test
37
+ bun test ./storage/framework/core/realtime/tests
35
38
  ```
36
39
 
37
40
  ## 📈 Changelog
@@ -0,0 +1,40 @@
1
+ export declare function replayOptions(options: DurableReplayOptions, incarnationFactory?: () => string): { policy: ReplayPolicy, policyKey: string, now: () => number, newIncarnation: () => string };
2
+ export declare function channelName(value: unknown): string;
3
+ export declare function prepareAppend(input: DurableReplayAppend, policy: ReplayPolicy): PreparedAppend;
4
+ export declare function readInput(input: DurableReplayRead): { limit: number, after: DurableReplayCursor | null };
5
+ export declare function replayGap(state: ReplayState, after: DurableReplayCursor | null): DurableReplayPage['gap'];
6
+ export declare function replayPage(state: ReplayState, after: DurableReplayCursor | null, candidates: DurableReplayMessage[], maxBytes: number): DurableReplayPage;
7
+ export declare interface DurableReplayCursor { incarnation: string, seq: number }
8
+ export declare interface DurableReplayMessage { seq: number, ts: number, event: string, data: unknown }
9
+ export declare interface DurableReplayAppend { channel: string, event: string, data?: unknown, idempotencyKey: string }
10
+ export declare interface DurableReplayRead { channel: string, after: DurableReplayCursor | null, limit?: number }
11
+ export declare interface DurableReplayPage {
12
+ messages: DurableReplayMessage[]
13
+ cursor: DurableReplayCursor | null
14
+ head: DurableReplayCursor
15
+ prunedThrough: number
16
+ hasMore: boolean
17
+ gap: 'retention' | 'incarnation' | 'cursor_ahead' | null
18
+ }
19
+ export declare interface DurableReplayStore {
20
+ append: (input: DurableReplayAppend) => Promise<{ message: DurableReplayMessage, cursor: DurableReplayCursor, duplicate: boolean }>
21
+ replay: (input: DurableReplayRead) => Promise<DurableReplayPage>
22
+ prune: (channel: string) => Promise<{ prunedThrough: number, head: DurableReplayCursor }>
23
+ }
24
+ export declare interface DurableReplayOptions {
25
+ maxEvents?: number
26
+ ttlMs?: number
27
+ maxPayloadBytes?: number
28
+ maxReplayBytes?: number
29
+ clock?: () => number
30
+ }
31
+ export declare interface MemoryDurableReplayOptions extends DurableReplayOptions {
32
+ incarnation?: () => string
33
+ }
34
+ export declare interface ReplayPolicy { maxEvents: number, ttlMs: number, maxPayloadBytes: number, maxReplayBytes: number }
35
+ export declare interface ReplayState { incarnation: string, highWaterMark: number, prunedThrough: number, lastRecordedAt: number }
36
+ export declare interface PreparedAppend { channel: string, event: string, operationKey: string, payload: string, fingerprint: string }
37
+ export declare class DurableReplayError extends Error {
38
+ readonly code: string;
39
+ constructor(code: string, message: string);
40
+ }
@@ -0,0 +1 @@
1
+ import{createHash,randomUUID}from"node:crypto";const MAX_JSON_NODES=4096;export class DurableReplayError extends Error{code;constructor(code,message){super(message);this.code=code;this.name="DurableReplayError"}}export function replayOptions(options,incarnationFactory=randomUUID){const policy={maxEvents:options.maxEvents??100,ttlMs:options.ttlMs??300000,maxPayloadBytes:options.maxPayloadBytes??65536,maxReplayBytes:options.maxReplayBytes??1048576};if(!Number.isSafeInteger(policy.maxEvents)||policy.maxEvents<1||policy.maxEvents>1e4||!Number.isSafeInteger(policy.ttlMs)||policy.ttlMs<1||policy.ttlMs>31536000000||!Number.isSafeInteger(policy.maxPayloadBytes)||policy.maxPayloadBytes<1||policy.maxPayloadBytes>65536||!Number.isSafeInteger(policy.maxReplayBytes)||policy.maxReplayBytes<policy.maxPayloadBytes+512||policy.maxReplayBytes>16777216)throw new TypeError("Invalid bounded replay policy");const clock=options.clock?.bind(options)??Date.now,incarnation=incarnationFactory.bind(options);return{policy,policyKey:JSON.stringify(policy),now(){const value=clock();if(!Number.isSafeInteger(value)||value<0)throw new TypeError("Replay clock must return a nonnegative safe integer");return value},newIncarnation(){const value=incarnation();if(typeof value!=="string"||!/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(value))throw new TypeError("Replay incarnation must be a UUID");return value}}}export function channelName(value){if(typeof value!=="string"||!/^[\w.:-]{1,200}$/.test(value))throw new TypeError("Replay requires a bounded exact channel name");return value}export function prepareAppend(input,policy){channelName(input?.channel);if(typeof input.event!=="string"||!/^[\w.:-]{1,200}$/.test(input.event)||typeof input.idempotencyKey!=="string"||!input.idempotencyKey.trim()||input.idempotencyKey.length>200)throw new TypeError("Replay event and operation ID must be bounded strings");let nodes=0,bytes=0;const seen=new Set;function visit(value,depth){if(++nodes>MAX_JSON_NODES||depth>32)throw new TypeError("Replay JSON exceeds structural bounds");if(value===null||typeof value==="boolean")return value;if(typeof value==="string"){bytes+=Buffer.byteLength(value);if(bytes>policy.maxPayloadBytes)throw new TypeError("Replay payload exceeds its byte bound");return value}if(typeof value==="number"&&Number.isFinite(value))return value;if(typeof value!=="object"||!value||seen.has(value)||!Array.isArray(value)&&![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw new TypeError("Replay payload must be finite, acyclic JSON");seen.add(value);let result;if(Array.isArray(value)){const length=value.length;if(!Number.isSafeInteger(length)||length<0||length>MAX_JSON_NODES-nodes)throw new TypeError("Replay JSON exceeds structural bounds");const array=[];for(let index=0;index<length;index++){if(!Object.hasOwn(value,index))throw new TypeError("Replay JSON arrays must be dense");array.push(visit(value[index],depth+1))}result=array}else{const object=Object.create(null);for(const key of Object.keys(value).sort()){bytes+=Buffer.byteLength(key);if(bytes>policy.maxPayloadBytes)throw new TypeError("Replay payload exceeds its byte bound");object[key]=visit(value[key],depth+1)}result=object}seen.delete(value);return result}const payload=JSON.stringify(visit(input.data===undefined?null:input.data,0));if(Buffer.byteLength(payload)>policy.maxPayloadBytes)throw new TypeError("Replay payload exceeds its byte bound");return{channel:input.channel,event:input.event,operationKey:input.idempotencyKey,payload,fingerprint:createHash("sha256").update(JSON.stringify([input.event,payload])).digest("hex")}}export function readInput(input){channelName(input?.channel);const limit=input.limit??100;if(!Number.isSafeInteger(limit)||limit<1||limit>100)throw new TypeError("Replay limit must be an integer from 1 to 100");const cursor=input.after;if(cursor!==null&&(typeof cursor!=="object"||!cursor||Object.keys(cursor).some((key)=>!["incarnation","seq"].includes(key))||typeof cursor.incarnation!=="string"||!/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(cursor.incarnation)||!Number.isSafeInteger(cursor.seq)||cursor.seq<0))throw new TypeError("Replay requires a complete incarnation-bound cursor or null");return{limit,after:cursor?{incarnation:cursor.incarnation,seq:cursor.seq}:null}}export function replayGap(state,after){return after&&after.incarnation!==state.incarnation?"incarnation":(after?.seq??0)>state.highWaterMark?"cursor_ahead":(after?.seq??0)<state.prunedThrough?"retention":null}export function replayPage(state,after,candidates,maxBytes){const gap=replayGap(state,after),head={incarnation:state.incarnation,seq:state.highWaterMark};if(gap)return{messages:[],cursor:null,head,prunedThrough:state.prunedThrough,gap,hasMore:false};const messages=[];let bytes=0;for(const message of candidates){const size=Buffer.byteLength(JSON.stringify(message));if(bytes+size>maxBytes)break;messages.push(message);bytes+=size}const cursor={incarnation:state.incarnation,seq:messages.at(-1)?.seq??after?.seq??0};return{messages,cursor,head,prunedThrough:state.prunedThrough,gap:null,hasMore:cursor.seq<state.highWaterMark}}
@@ -0,0 +1,8 @@
1
+ import type { DurableReplayAppend, DurableReplayCursor, DurableReplayMessage, DurableReplayStore } from './durable-replay-contract';
2
+ /** Finite authenticated replay request. Select the channel on the server; the
3
+ * store's partition labels and the cursor are never proof of current authority. */
4
+ export declare function createDurableReplayResponse(options: { store: DurableReplayStore, channel: string, after: DurableReplayCursor | null, limit?: number, authorize: (channel: string) => boolean | Promise<boolean> }): Promise<Response>;
5
+ /** Persist first, then notify. Notification is an at-least-once hint: retries
6
+ * notify retained duplicates too, so consumers deduplicate by incarnation/seq.
7
+ * A crash or failed notify never removes the event from replay. No fan-out is provided. */
8
+ export declare function publishDurableReplay(options: { store: DurableReplayStore, input: DurableReplayAppend, notify: (channel: string, message: DurableReplayMessage, cursor: DurableReplayCursor) => void | Promise<void> }): Promise<Awaited<ReturnType<DurableReplayStore['append']>>>;
@@ -0,0 +1 @@
1
+ import{channelName,DurableReplayError,readInput}from"./durable-replay-contract";export async function createDurableReplayResponse(options){channelName(options.channel);if(typeof options.authorize!=="function")throw new TypeError("Durable replay requires current channel authorization");const{store,channel,after,limit}=options,authorize=options.authorize.bind(options);const response=(data,status)=>Response.json(data,{status,headers:{"Cache-Control":"no-store"}});try{if(!await authorize(channel))return response({error:"replay_forbidden"},403);let input;try{input=readInput({channel,after,limit})}catch(error){if(error instanceof TypeError)return response({error:"replay_input_invalid"},422);throw error}const result=await store.replay({channel,...input});if(!await authorize(channel))return response({error:"replay_forbidden"},403);return response(result,result.gap?409:200)}catch(error){return response({error:error instanceof DurableReplayError?error.code:"replay_unavailable"},error instanceof DurableReplayError&&error.code==="replay_idempotency_conflict"?409:503)}}export async function publishDurableReplay(options){const notify=options.notify.bind(options),channel=options.input.channel;const result=await options.store.append(options.input);await notify(channel,result.message,result.cursor);return result}
@@ -0,0 +1,12 @@
1
+ import type { DurableReplayOptions, DurableReplayStore } from './durable-replay-contract';
2
+ /** Production SQL implementation over app-owned, model-generated tables. Never runs DDL. */
3
+ export declare function createSqlDurableReplayStore(options: SqlDurableReplayOptions): DurableReplayStore;
4
+ export declare interface SqlDurableReplayOptions extends DurableReplayOptions {
5
+ dialect: 'sqlite' | 'postgres'
6
+ tables: { channels: string, events: string }
7
+ transaction: <T>(callback: (query: ReplaySqlQuery) => Promise<T>) => Promise<T>
8
+ scope?: Readonly<Record<string, string | number>>
9
+ }
10
+ declare type Row = Record<string, unknown>;
11
+ export type ReplaySqlQuery = (sql: string, values: unknown[]) => Promise<Row[]> | Row[];
12
+ export {};
@@ -0,0 +1 @@
1
+ import{channelName,DurableReplayError,prepareAppend,readInput,replayGap,replayOptions,replayPage}from"./durable-replay-contract";const reserved=new Set(["id","name","incarnation","high_water_mark","pruned_through","last_recorded_at","policy","channel_id","seq","operation_key","fingerprint","event","payload","recorded_at"]);function identifier(value){if(typeof value!=="string"||!/^[a-z][a-z0-9_]{0,62}$/.test(value))throw new TypeError("Invalid replay SQL identifier");return`"${value}"`}function sequence(value){const number=typeof value==="number"?value:typeof value==="bigint"||typeof value==="string"&&/^\d+$/.test(value)?Number(value):NaN;if(!Number.isSafeInteger(number)||number<0)throw new DurableReplayError("replay_storage_invalid","Replay checkpoint is invalid");return number}function message(row){return{seq:sequence(row.seq),ts:sequence(row.recorded_at),event:String(row.event),data:JSON.parse(String(row.payload))}}export function createSqlDurableReplayStore(options){if(!["sqlite","postgres"].includes(options.dialect)||typeof options.transaction!=="function")throw new TypeError("Replay requires a supported transactional SQL adapter");const channels=identifier(options.tables.channels),events=identifier(options.tables.events),dialect=options.dialect;const configuration=replayOptions(options),transaction=options.transaction.bind(options);const scope=Object.entries(options.scope??{}).sort(([a],[b])=>a.localeCompare(b));if(scope.length>8)throw new TypeError("Replay partition exceeds its column bound");for(const[column,value]of scope){identifier(column);if(reserved.has(column)||!(typeof value==="string"&&value.length>0&&value.length<=200||typeof value==="number"&&Number.isSafeInteger(value)))throw new TypeError("Invalid immutable replay partition")}const predicates=scope.map(([name])=>`${identifier(name)} = ?`),scopeValues=scope.map(([,value])=>value);async function locked(name,operation){channelName(name);return await transaction(async(query)=>{if(typeof query!=="function")throw new TypeError("Replay transaction must supply its own query handle");const run=async(sql,values=[])=>{let index=0;return await query(dialect==="postgres"?sql.replace(/\?/g,()=>`$${++index}`):sql,values)};const columns=[...scope.map(([column])=>identifier(column)),"name","incarnation","high_water_mark","pruned_through","last_recorded_at","policy"];const values=[...scopeValues,name,configuration.newIncarnation(),0,0,0,configuration.policyKey];await run(`INSERT INTO ${channels} (${columns.join(", ")}) VALUES (${values.map(()=>"?").join(", ")}) ON CONFLICT DO NOTHING`,values);const row=(await run(`UPDATE ${channels} SET name = name WHERE ${[...predicates,"name = ?"].join(" AND ")} RETURNING *`,[...scopeValues,name]))[0];if(!row||row.policy!==configuration.policyKey)throw new DurableReplayError("replay_policy_mismatch","Replay channel policy differs from its persisted configuration");const channelId=row.id;const state={incarnation:String(row.incarnation),highWaterMark:sequence(row.high_water_mark),prunedThrough:sequence(row.pruned_through),lastRecordedAt:sequence(row.last_recorded_at)};const eventWhere=["channel_id = ?",...predicates].join(" AND "),eventValues=[row.id,...scopeValues];async function prune(){const cutoff=Math.max(configuration.now(),state.lastRecordedAt)-configuration.policy.ttlMs;const expired=(await run(`SELECT MAX(seq) AS expired FROM ${events} WHERE ${eventWhere} AND recorded_at <= ?`,[...eventValues,cutoff]))[0]?.expired;const floor=Math.max(state.prunedThrough,state.highWaterMark-configuration.policy.maxEvents,expired===null||expired===undefined?0:sequence(expired));if(floor>state.prunedThrough){await run(`DELETE FROM ${events} WHERE ${eventWhere} AND seq <= ?`,[...eventValues,floor]);await run(`UPDATE ${channels} SET pruned_through = ? WHERE id = ? AND ${predicates.length?predicates.join(" AND "):"1 = 1"}`,[floor,channelId,...scopeValues]);state.prunedThrough=floor}}await prune();return await operation(state,run,row,prune)})}return{async append(input){const prepared=prepareAppend(input,configuration.policy);return await locked(prepared.channel,async(state,run,row,prune)=>{const prior=(await run(`SELECT * FROM ${events} WHERE channel_id = ? AND ${[...predicates,"operation_key = ?"].join(" AND ")}`,[row.id,...scopeValues,prepared.operationKey]))[0];if(prior){if(prior.fingerprint!==prepared.fingerprint)throw new DurableReplayError("replay_idempotency_conflict","Operation ID was used with different event data");const retained=message(prior);return{message:retained,cursor:{incarnation:state.incarnation,seq:retained.seq},duplicate:true}}if(state.highWaterMark===Number.MAX_SAFE_INTEGER)throw new DurableReplayError("replay_sequence_exhausted","Channel sequence is exhausted");const seq=state.highWaterMark+1,ts=Math.max(configuration.now(),state.lastRecordedAt);const columns=[...scope.map(([column])=>identifier(column)),"channel_id","seq","operation_key","fingerprint","event","payload","recorded_at"];const values=[...scopeValues,row.id,seq,prepared.operationKey,prepared.fingerprint,prepared.event,prepared.payload,ts];await run(`INSERT INTO ${events} (${columns.join(", ")}) VALUES (${values.map(()=>"?").join(", ")})`,values);await run(`UPDATE ${channels} SET high_water_mark = ?, last_recorded_at = ? WHERE id = ? AND ${predicates.length?predicates.join(" AND "):"1 = 1"}`,[seq,ts,row.id,...scopeValues]);state.highWaterMark=seq;state.lastRecordedAt=ts;await prune();return{message:{seq,ts,event:prepared.event,data:JSON.parse(prepared.payload)},cursor:{incarnation:state.incarnation,seq},duplicate:false}})},async replay(input){const read=readInput(input);return await locked(input.channel,async(state,run,row)=>{const rows=replayGap(state,read.after)?[]:await run(`SELECT seq, recorded_at, event, payload FROM ${events} WHERE channel_id = ? AND ${[...predicates,"seq > ?"].join(" AND ")} ORDER BY seq ASC LIMIT ?`,[row.id,...scopeValues,read.after?.seq??0,read.limit]);const messages=rows.map(message);if(messages.some((entry,index)=>entry.seq!==(read.after?.seq??0)+index+1)||!replayGap(state,read.after)&&messages.length!==Math.min(read.limit,state.highWaterMark-(read.after?.seq??0)))throw new DurableReplayError("replay_storage_gap","Replay storage contains an unexplained sequence gap");return replayPage(state,read.after,messages,configuration.policy.maxReplayBytes)})},async prune(channel){return await locked(channel,async(state)=>({prunedThrough:state.prunedThrough,head:{incarnation:state.incarnation,seq:state.highWaterMark}}))}}}
@@ -0,0 +1,6 @@
1
+ import { DurableReplayError } from './durable-replay-contract';
2
+ import type { MemoryDurableReplayOptions, DurableReplayStore } from './durable-replay-contract';
3
+ export type { DurableReplayAppend, DurableReplayCursor, DurableReplayMessage, DurableReplayOptions, DurableReplayPage, DurableReplayRead, DurableReplayStore, MemoryDurableReplayOptions } from './durable-replay-contract';
4
+ /** Deterministic in-memory fake for the durable contract. Existing replay buffer is unchanged. */
5
+ export declare function createMemoryDurableReplayStore(options?: MemoryDurableReplayOptions): DurableReplayStore;
6
+ export { DurableReplayError } from './durable-replay-contract';
@@ -0,0 +1 @@
1
+ import{channelName,DurableReplayError,prepareAppend,readInput,replayOptions,replayPage}from"./durable-replay-contract";export{DurableReplayError}from"./durable-replay-contract";export function createMemoryDurableReplayStore(options={}){const configuration=replayOptions(options,options.incarnation);const channels=new Map;function state(channel){channelName(channel);let value=channels.get(channel);if(!value){value={incarnation:configuration.newIncarnation(),highWaterMark:0,prunedThrough:0,lastRecordedAt:0,entries:[]};channels.set(channel,value)}const now=Math.max(configuration.now(),value.lastRecordedAt);value.prunedThrough=Math.max(value.prunedThrough,value.highWaterMark-configuration.policy.maxEvents,...value.entries.filter((entry)=>entry.ts<=now-configuration.policy.ttlMs).map((entry)=>entry.seq));value.entries=value.entries.filter((entry)=>entry.seq>value.prunedThrough);return value}return{async append(input){const prepared=prepareAppend(input,configuration.policy),value=state(prepared.channel);const prior=value.entries.find((entry)=>entry.operationKey===prepared.operationKey);if(prior&&prior.fingerprint!==prepared.fingerprint)throw new DurableReplayError("replay_idempotency_conflict","Operation ID was used with different event data");if(value.highWaterMark===Number.MAX_SAFE_INTEGER&&!prior)throw new DurableReplayError("replay_sequence_exhausted","Channel sequence is exhausted");const entry=prior??{...prepared,seq:value.highWaterMark+1,ts:Math.max(configuration.now(),value.lastRecordedAt)};if(!prior){value.highWaterMark=entry.seq;value.lastRecordedAt=entry.ts;value.entries.push(entry);state(prepared.channel)}return{message:{seq:entry.seq,ts:entry.ts,event:entry.event,data:JSON.parse(entry.payload)},cursor:{incarnation:value.incarnation,seq:entry.seq},duplicate:!!prior}},async replay(input){const read=readInput(input),value=state(input.channel);const messages=value.entries.filter((entry)=>entry.seq>(read.after?.seq??0)).slice(0,read.limit).map((entry)=>({seq:entry.seq,ts:entry.ts,event:entry.event,data:JSON.parse(entry.payload)}));return replayPage(value,read.after,messages,configuration.policy.maxReplayBytes)},async prune(channel){const value=state(channel);return{prunedThrough:value.prunedThrough,head:{incarnation:value.incarnation,seq:value.highWaterMark}}}}}
package/dist/index.d.ts CHANGED
@@ -3,6 +3,10 @@ export type { EmitOptions } from './emit';
3
3
  export type { BroadcastInstance } from './broadcast';
4
4
  export type { BufferedMessage, ReplayBufferConfig } from './replay-buffer';
5
5
  export type { WsAuthenticator, WsAuthResult } from './ws';
6
+ export type { DurableReplayAppend, DurableReplayCursor, DurableReplayMessage, DurableReplayOptions, DurableReplayPage, DurableReplayRead, DurableReplayStore, MemoryDurableReplayOptions } from './durable-replay';
7
+ export type { ReplaySqlQuery, SqlDurableReplayOptions } from './durable-replay-sql';
8
+ export type { InvalidationBounds, InvalidationBus, InvalidationNotice, InvalidationStatus, InvalidationSubscription, MemoryInvalidationBus } from './invalidation-bus';
9
+ export type { RedisInvalidationOptions } from './redis-invalidations';
6
10
  /**
7
11
  * Stacks Realtime Module
8
12
  *
@@ -33,3 +37,11 @@ export { storeWebSocketEvent } from './ws';
33
37
  // on the server `createServer()` starts; without one, upgrades proceed
34
38
  // unauthed.
35
39
  export { setWsAuthenticator, getWsAuthenticator } from './ws';
40
+ // Explicit awaited durable replay over application-owned, model-generated SQL.
41
+ // Existing synchronous broadcast/replay APIs remain in-memory and unchanged.
42
+ export { createMemoryDurableReplayStore, DurableReplayError } from './durable-replay';
43
+ export { createSqlDurableReplayStore } from './durable-replay-sql';
44
+ export { createDurableReplayResponse, publishDurableReplay } from './durable-replay-http';
45
+ // Opt-in metadata-only hints. SQL replay/domain state remain authoritative.
46
+ export { createMemoryInvalidationBus, InvalidationError } from './invalidation-bus';
47
+ export { createRedisInvalidationBus } from './redis-invalidations';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export*from"ts-broadcasting";export{getServer,setServer,createServer,createBroadcastHub,stopServer}from"./server-instance";export{createBroadcastResponse}from"./stream";export{emit,emitToUser,emitToUsers}from"./emit";export{channel,channel as createChannel,Channel as StacksChannel}from"./channel";export{broadcast as dispatchBroadcast,runBroadcast,Broadcast as LegacyBroadcast}from"./broadcast";export{debugSnapshot,getReplayBuffer,pruneExpired,recordBroadcast,replaySince,setReplayBuffer}from"./replay-buffer";export{storeWebSocketEvent}from"./ws";export{setWsAuthenticator,getWsAuthenticator}from"./ws";
1
+ export*from"ts-broadcasting";export{getServer,setServer,createServer,createBroadcastHub,stopServer}from"./server-instance";export{createBroadcastResponse}from"./stream";export{emit,emitToUser,emitToUsers}from"./emit";export{channel,channel as createChannel,Channel as StacksChannel}from"./channel";export{broadcast as dispatchBroadcast,runBroadcast,Broadcast as LegacyBroadcast}from"./broadcast";export{debugSnapshot,getReplayBuffer,pruneExpired,recordBroadcast,replaySince,setReplayBuffer}from"./replay-buffer";export{storeWebSocketEvent}from"./ws";export{setWsAuthenticator,getWsAuthenticator}from"./ws";export{createMemoryDurableReplayStore,DurableReplayError}from"./durable-replay";export{createSqlDurableReplayStore}from"./durable-replay-sql";export{createDurableReplayResponse,publishDurableReplay}from"./durable-replay-http";export{createMemoryInvalidationBus,InvalidationError}from"./invalidation-bus";export{createRedisInvalidationBus}from"./redis-invalidations";
@@ -0,0 +1,54 @@
1
+ /** @internal */
2
+ export declare function createInvalidationListeners(options?: InvalidationBounds, changed?: () => void): InvalidationListeners;
3
+ /** Explicit deterministic local fake; it does not simulate durable delivery. */
4
+ export declare function createMemoryInvalidationBus(options?: InvalidationBounds): MemoryInvalidationBus;
5
+ export declare interface InvalidationNotice { readonly channels: readonly string[], readonly reason: 'hint' | 'resync' }
6
+ export declare interface InvalidationSubscription {
7
+ channels: readonly string[]
8
+ onInvalidate: (notice: InvalidationNotice) => void | Promise<void>
9
+ onClose?: () => void
10
+ signal?: AbortSignal
11
+ }
12
+ export declare interface InvalidationBus {
13
+ readonly status: InvalidationStatus
14
+ publish: (channel: string) => Promise<{ subscriberConnections: number }>
15
+ subscribe: (options: InvalidationSubscription) => Promise<() => void>
16
+ close: () => Promise<void>
17
+ }
18
+ export declare interface InvalidationBounds {
19
+ maxChannels?: number
20
+ maxSubscriptions?: number
21
+ maxPending?: number
22
+ callbackTimeoutMs?: number
23
+ }
24
+ export declare interface MemoryInvalidationBus extends InvalidationBus { resync: () => void }
25
+ declare interface Registration {
26
+ channels: readonly string[]
27
+ callback: (notice: InvalidationNotice) => void | Promise<void>
28
+ closeObserver?: () => void
29
+ active: boolean
30
+ removed: boolean
31
+ running: boolean
32
+ resync: boolean
33
+ pending: Set<string>
34
+ abort: AbortController
35
+ ended: Promise<void>
36
+ end: () => void
37
+ detach: () => void
38
+ }
39
+ /** @internal Shared bounded delivery contract; drivers never carry domain payloads. */
40
+ export declare interface InvalidationListeners {
41
+ add: (options: InvalidationSubscription) => Registration
42
+ activate: (record: Registration) => void
43
+ remove: (record: Registration, terminal?: boolean) => void
44
+ notify: (channel: string) => void
45
+ resync: () => void
46
+ channels: () => string[]
47
+ close: () => void
48
+ }
49
+ export type InvalidationStatus = 'idle' | 'connecting' | 'ready' | 'disconnected' | 'closed';
50
+ export declare class InvalidationError extends Error {
51
+ readonly code: string;
52
+ constructor(code: string, message: string);
53
+ }
54
+ export {};
@@ -0,0 +1 @@
1
+ import{AsyncResource}from"node:async_hooks";import{channelName}from"./durable-replay-contract";export class InvalidationError extends Error{code;constructor(code,message){super(message);this.code=code;this.name="InvalidationError"}}export function createInvalidationListeners(options={},changed=()=>{}){const maxChannels=options.maxChannels??1024,maxSubscriptions=options.maxSubscriptions??1024,maxPending=options.maxPending??64,timeoutMs=options.callbackTimeoutMs??5000;if(!Number.isSafeInteger(maxChannels)||maxChannels<1||maxChannels>4096||!Number.isSafeInteger(maxSubscriptions)||maxSubscriptions<1||maxSubscriptions>4096||!Number.isSafeInteger(maxPending)||maxPending<1||maxPending>1024||!Number.isSafeInteger(timeoutMs)||timeoutMs<1||timeoutMs>30000)throw new TypeError("Invalid invalidation delivery bounds");const records=new Set,channels=new Map;let closed=false;function remove(record,terminal=false){if(record.removed)return;record.removed=true;record.pending.clear();record.resync=false;record.abort.abort();record.detach();record.end();records.delete(record);for(const channel of record.channels){const members=channels.get(channel);members?.delete(record);if(!members?.size)channels.delete(channel)}changed();if(terminal&&record.active){try{const result=record.closeObserver?.();if(result!==undefined)Promise.resolve(result).catch(()=>{})}catch{}}}async function pump(record){if(record.running||!record.active||record.removed)return;record.running=true;try{while(!record.removed&&(record.resync||record.pending.size)){const resync=record.resync,channel=record.pending.values().next().value;record.resync=false;if(resync)record.pending.clear();else record.pending.delete(channel);const notice=Object.freeze({channels:resync?record.channels:Object.freeze([channel]),reason:resync?"resync":"hint"});let timer;const deadline=Promise.withResolvers(),aborted=()=>deadline.reject(new InvalidationError("invalidation_closed","Invalidation subscription ended"));record.abort.signal.addEventListener("abort",aborted,{once:true});timer=setTimeout(()=>deadline.reject(new InvalidationError("invalidation_callback_timeout","Invalidation callback exceeded its deadline")),timeoutMs);try{await Promise.race([Promise.resolve().then(()=>record.removed?undefined:record.callback(notice)),deadline.promise])}catch{remove(record,true);return}finally{clearTimeout(timer);record.abort.signal.removeEventListener("abort",aborted)}}}finally{record.running=false}}function enqueue(record,channel){if(record.removed)return;if(channel===undefined||!record.pending.has(channel)&&record.pending.size>=maxPending){record.pending.clear();record.resync=true}else if(!record.resync)record.pending.add(channel);pump(record)}return{add(input){if(closed)throw new InvalidationError("invalidation_closed","Invalidation bus is closed");if(!Array.isArray(input.channels)||!input.channels.length||input.channels.length>maxChannels||typeof input.onInvalidate!=="function"||records.size>=maxSubscriptions)throw new InvalidationError("invalidation_capacity","Invalid invalidation subscription or capacity exceeded");const selected=new Set;for(let index=0;index<input.channels.length;index++){if(!Object.hasOwn(input.channels,index))throw new TypeError("Invalidation channels must be dense");selected.add(channelName(input.channels[index]))}if(channels.size+[...selected].filter((channel)=>!channels.has(channel)).length>maxChannels)throw new InvalidationError("invalidation_capacity","Invalidation channel capacity exceeded");const signal=input.signal;if(signal?.aborted)throw new InvalidationError("invalidation_closed","Invalidation subscription is aborted");const ended=Promise.withResolvers();const record={channels:Object.freeze([...selected]),callback:AsyncResource.bind(input.onInvalidate,undefined,input),closeObserver:input.onClose?AsyncResource.bind(input.onClose,undefined,input):undefined,active:false,removed:false,running:false,resync:false,pending:new Set,abort:new AbortController,ended:ended.promise,end:()=>ended.resolve(),detach:()=>{}};const abort=()=>remove(record,true);record.detach=()=>signal?.removeEventListener("abort",abort);signal?.addEventListener("abort",abort,{once:true});records.add(record);for(const channel of record.channels){let members=channels.get(channel);if(!members){members=new Set;channels.set(channel,members)}members.add(record)}changed();return record},activate(record){if(record.removed)throw new InvalidationError("invalidation_closed","Invalidation subscription ended before readiness");record.active=true;pump(record)},remove,notify(channel){for(const record of channels.get(channel)??[])enqueue(record,channel)},resync(){for(const record of records)enqueue(record)},channels:()=>[...channels.keys()],close(){if(closed)return;closed=true;for(const record of[...records])remove(record,true)}}}export function createMemoryInvalidationBus(options={}){const listeners=createInvalidationListeners(options);let closed=false;return{get status(){return closed?"closed":"ready"},async publish(channel){if(closed)throw new InvalidationError("invalidation_closed","Invalidation bus is closed");channelName(channel);const subscribed=listeners.channels().includes(channel);listeners.notify(channel);return{subscriberConnections:subscribed?1:0}},async subscribe(input){const record=listeners.add(input);listeners.activate(record);return()=>listeners.remove(record)},resync(){if(!closed)listeners.resync()},async close(){if(closed)return;closed=true;listeners.close()}}}
@@ -0,0 +1,16 @@
1
+ import type { InvalidationBounds, InvalidationBus, InvalidationStatus } from './invalidation-bus';
2
+ /** @internal Capability detection without importing an unavailable optional driver. */
3
+ export declare function supportsRedisInvalidations(runtime: unknown): boolean;
4
+ /** Opt-in metadata-only, at-most-once hints over Bun's experimental native Pub/Sub. */
5
+ export declare function createRedisInvalidationBus(options: RedisInvalidationOptions): InvalidationBus;
6
+ export declare interface RedisInvalidationOptions extends InvalidationBounds {
7
+ url: string
8
+ namespace: string
9
+ connectTimeoutMs?: number
10
+ operationTimeoutMs?: number
11
+ reconnectDelayMs?: number
12
+ maxReconnectDelayMs?: number
13
+ maxPendingPublishes?: number
14
+ maxRememberedHints?: number
15
+ onStatus?: (status: InvalidationStatus) => void
16
+ }
@@ -0,0 +1 @@
1
+ import{createHash,randomUUID}from"node:crypto";import{createInvalidationListeners,InvalidationError}from"./invalidation-bus";import{channelName}from"./durable-replay-contract";export function supportsRedisInvalidations(runtime){const client=runtime?.RedisClient;return!!client?.prototype&&["connect","close","publish","subscribe","unsubscribe"].every((name)=>typeof client.prototype[name]==="function")}function bound(value,maximum){if(!Number.isSafeInteger(value)||value<1||value>maximum)throw new TypeError("Invalid Redis invalidation bounds");return value}const UUID=/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i;export function createRedisInvalidationBus(options){if(!supportsRedisInvalidations(globalThis.Bun))throw new InvalidationError("invalidation_pubsub_unavailable","This Bun runtime does not provide native Redis Pub/Sub");let endpoint;try{endpoint=new URL(options.url)}catch{throw new TypeError("A server-owned Redis URL is required")}if(!["redis:","rediss:","redis+tls:"].includes(endpoint.protocol)||!endpoint.hostname||endpoint.hash||endpoint.search||typeof options.namespace!=="string"||!/^[\w.:-]{1,100}$/.test(options.namespace))throw new TypeError("Invalid Redis invalidation endpoint or namespace");const Client=globalThis.Bun.RedisClient;const connectTimeout=bound(options.connectTimeoutMs??2000,30000),operationTimeout=bound(options.operationTimeoutMs??2000,30000);const delay=bound(options.reconnectDelayMs??50,1e4),maxDelay=bound(options.maxReconnectDelayMs??2000,30000);const maxPublishes=bound(options.maxPendingPublishes??64,1024),maxSeen=bound(options.maxRememberedHints??1024,1e4);if(maxDelay<delay)throw new TypeError("Invalid Redis reconnect delay range");const url=endpoint.href,namespace=options.namespace,origin=randomUUID(),statusObserver=options.onStatus?.bind(options);let status="idle",closed=false,pair,connecting,synchronizing;let timer,attempts=0,activePublishes=0,previouslyReady=false;const remembered=new Map,cancelPending=new Set;const listeners=createInvalidationListeners(options,()=>{queueMicrotask(()=>{if(closed)return;if(!listeners.channels().length&&!pair){clearTimeout(timer);timer=undefined;return}synchronize().catch(()=>{})})});const topic=(channel)=>`${namespace}:invalidation:v1:${createHash("sha256").update(channel).digest("hex")}`;function state(next){if(status===next)return;status=next;try{const result=statusObserver?.(next);if(result!==undefined)Promise.resolve(result).catch(()=>{})}catch{}}function closePair(target){target.publisher.onclose=null;target.subscriber.onclose=null;target.publisher.close();target.subscriber.close()}function schedule(){if(closed||timer||!listeners.channels().length)return;const wait=Math.min(maxDelay,delay*2**attempts);attempts=Math.min(attempts+1,16);timer=setTimeout(()=>{timer=undefined;synchronize().catch(()=>{schedule()})},wait)}function lost(target){if(pair!==target)return;pair=undefined;closePair(target);if(!closed){state("disconnected");schedule()}}async function timed(promise,target,milliseconds){const deadline=Promise.withResolvers(),cancel=()=>deadline.reject(new InvalidationError("invalidation_closed","Redis invalidation bus is closed"));cancelPending.add(cancel);const timeout=setTimeout(()=>{lost(target);deadline.reject(new InvalidationError("invalidation_unavailable","Redis invalidation operation exceeded its deadline"))},milliseconds);try{return await Promise.race([promise,deadline.promise])}finally{clearTimeout(timeout);cancelPending.delete(cancel)}}function receive(target,message,physical){if(closed||pair!==target||typeof message!=="string"||message.length>256||Buffer.byteLength(message)>256)return;const channel=target.logical.get(physical);if(!channel)return;try{const hint=JSON.parse(message);if(!hint||typeof hint!=="object"||Array.isArray(hint)||Object.keys(hint).length!==3||!["v","origin","id"].every((key)=>Object.hasOwn(hint,key))||hint.v!==1||typeof hint.origin!=="string"||typeof hint.id!=="string"||!UUID.test(hint.origin)||!UUID.test(hint.id)||hint.origin===origin)return;const identity=`${hint.origin}:${hint.id}`;if(remembered.has(identity))return;if(remembered.size>=maxSeen)remembered.delete(remembered.keys().next().value);remembered.set(identity,true);listeners.notify(channel)}catch{}}function connection(){if(closed)return Promise.reject(new InvalidationError("invalidation_closed","Redis invalidation bus is closed"));if(pair?.publisher.connected&&pair.subscriber.connected)return Promise.resolve(pair);if(connecting)return connecting;if(pair){const stale=pair;pair=undefined;closePair(stale)}state("connecting");const settings={autoReconnect:false,maxRetries:0,enableOfflineQueue:false,enableAutoPipelining:false,connectionTimeout:connectTimeout,idleTimeout:0};let target;try{target={publisher:new Client(url,settings),subscriber:new Client(url,settings),topics:new Set,logical:new Map,receive:(message,physical)=>receive(target,message,physical),initialized:false}}catch{state("disconnected");schedule();return Promise.reject(new InvalidationError("invalidation_unavailable","Redis invalidation connection is unavailable"))}pair=target;target.publisher.onclose=target.subscriber.onclose=()=>lost(target);const pending=(async()=>{try{await timed(Promise.all([target.publisher.connect(),target.subscriber.connect()]),target,connectTimeout);if(closed||pair!==target)throw new InvalidationError("invalidation_unavailable","Redis invalidation connection changed");return target}catch{lost(target);throw new InvalidationError(closed?"invalidation_closed":"invalidation_unavailable","Redis invalidation connection is unavailable")}})();connecting=pending;pending.then(()=>{if(connecting===pending)connecting=undefined},()=>{if(connecting===pending)connecting=undefined});return pending}function synchronize(){if(closed)return Promise.reject(new InvalidationError("invalidation_closed","Redis invalidation bus is closed"));if(synchronizing)return synchronizing;const pending=(async()=>{const target=await connection(),end=Date.now()+operationTimeout;try{while(!closed&&pair===target){const desired=new Map(listeners.channels().map((channel)=>[topic(channel),channel]));const add=[...desired.keys()].filter((name)=>!target.topics.has(name)),remove=[...target.topics].filter((name)=>!desired.has(name));for(const[physical,logical]of desired)target.logical.set(physical,logical);if(add.length){await timed(target.subscriber.subscribe(add,target.receive),target,Math.max(1,end-Date.now()));for(const name of add)target.topics.add(name)}if(remove.length){await timed(target.subscriber.unsubscribe(remove),target,Math.max(1,end-Date.now()));for(const name of remove){target.topics.delete(name);target.logical.delete(name)}}if(closed||pair!==target)break;const latest=listeners.channels();if(latest.length===target.topics.size&&latest.every((channel)=>target.topics.has(topic(channel)))){clearTimeout(timer);timer=undefined;attempts=0;state("ready");if(!target.initialized&&previouslyReady)listeners.resync();target.initialized=true;previouslyReady=true;return}if(Date.now()>=end)throw new InvalidationError("invalidation_unavailable","Redis subscription synchronization exceeded its deadline")}throw new InvalidationError("invalidation_unavailable","Redis invalidation connection changed")}catch{lost(target);throw new InvalidationError(closed?"invalidation_closed":"invalidation_unavailable","Redis invalidation subscription is unavailable")}})();synchronizing=pending;pending.then(()=>{if(synchronizing===pending)synchronizing=undefined},()=>{if(synchronizing===pending)synchronizing=undefined;schedule()});return pending}return{get status(){return status},async publish(channel){if(closed)throw new InvalidationError("invalidation_closed","Redis invalidation bus is closed");channelName(channel);listeners.notify(channel);if(activePublishes>=maxPublishes)throw new InvalidationError("invalidation_capacity","Redis invalidation publish capacity exceeded");activePublishes++;try{await synchronize();const target=pair;if(!target)throw new InvalidationError("invalidation_unavailable","Redis invalidation connection is unavailable");const count=await timed(target.publisher.publish(topic(channel),JSON.stringify({v:1,origin,id:randomUUID()})),target,operationTimeout);if(!Number.isSafeInteger(count)||count<0)throw new InvalidationError("invalidation_unavailable","Redis invalidation response is invalid");return{subscriberConnections:count}}catch{throw new InvalidationError(closed?"invalidation_closed":"invalidation_unavailable","Redis invalidation publish is unavailable")}finally{activePublishes--}},async subscribe(input){const record=listeners.add(input);try{await Promise.race([synchronize(),record.ended.then(()=>{throw new InvalidationError("invalidation_closed","Invalidation subscription ended before readiness")})]);listeners.activate(record);return()=>listeners.remove(record)}catch(error){listeners.remove(record);throw error instanceof InvalidationError?error:new InvalidationError("invalidation_unavailable","Redis invalidation subscription is unavailable")}},async close(){if(closed)return;closed=true;clearTimeout(timer);timer=undefined;for(const cancel of cancelPending)cancel();const target=pair;pair=undefined;if(target)closePair(target);listeners.close();remembered.clear();state("closed")}}}
package/dist/stream.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { InvalidationBus } from './invalidation-bus';
1
2
  /** Authenticated SSE transport for the same engine used by emit(), channels and model broadcasts. */
2
3
  export declare function createBroadcastResponse(options: BroadcastStreamOptions): Promise<Response>;
3
4
  export declare interface BroadcastStreamMetadata {
@@ -11,6 +12,7 @@ export declare interface BroadcastStreamOptions {
11
12
  signal?: AbortSignal
12
13
  heartbeatMs?: number
13
14
  maxPending?: number
15
+ invalidations?: InvalidationBus
14
16
  onEnqueue?: (chunk: Uint8Array, broadcast: BroadcastStreamMetadata | null) => void
15
17
  onClose?: () => void
16
18
  }
package/dist/stream.js CHANGED
@@ -1,7 +1,9 @@
1
- import{AsyncResource}from"node:async_hooks";import{getServer}from"./server-instance";export async function createBroadcastResponse(options){if(!options.channels.length||typeof options.authorize!=="function")throw new Error("Broadcast streams require channels and authorization");const authorize=AsyncResource.bind(options.authorize,undefined,options);const enqueueObserver=options.onEnqueue?AsyncResource.bind(options.onEnqueue,undefined,options):undefined;const closeObserver=options.onClose?AsyncResource.bind(options.onClose,undefined,options):undefined;if(!await authorize())return new Response("Unauthorized",{status:401});const server=getServer();if(!server)throw new Error("Broadcast server not initialized");const channels=new Set(options.channels);const encoder=new TextEncoder;const maxPending=options.maxPending??64;if(!Number.isSafeInteger(maxPending)||maxPending<1||maxPending>1024||options.heartbeatMs!==undefined&&(!Number.isFinite(options.heartbeatMs)||options.heartbeatMs<1))throw new Error("Invalid broadcast stream configuration");let cleanup=()=>{};const stream=new ReadableStream({start(controller){let closed=false,pending=0;let chain=Promise.resolve();let timer;let remove=()=>{};function close(){if(closed)return;closed=true;remove();clearInterval(timer);options.signal?.removeEventListener("abort",close);try{controller.close()}catch{}try{const result=closeObserver?.();if(result!==undefined)Promise.resolve(result).catch(()=>{})}catch{}}function enqueue(frame,broadcast=null){if(closed)return;if((controller.desiredSize??0)<=0){close();return}const chunk=encoder.encode(frame);controller.enqueue(chunk);try{const result=enqueueObserver?.(chunk,broadcast);if(result!==undefined)Promise.resolve(result).catch(close)}catch{close()}}function deliver(frame,broadcast=null){if(closed)return;if(++pending>maxPending){close();return}chain=chain.then(async()=>{if(closed)return;if(!await authorize()){close();return}enqueue(frame,broadcast)}).catch(close).finally(()=>{pending--})}cleanup=close;remove=server.addBroadcastHook(({channel,event,data})=>{if(channels.has(channel))deliver(`data: ${JSON.stringify({channel,event,data})}
1
+ import{AsyncResource}from"node:async_hooks";import{getServer}from"./server-instance";export async function createBroadcastResponse(options){if(!options.channels.length||typeof options.authorize!=="function")throw new Error("Broadcast streams require channels and authorization");const channels=new Set(options.channels),invalidations=options.invalidations;const authorize=AsyncResource.bind(options.authorize,undefined,options);const enqueueObserver=options.onEnqueue?AsyncResource.bind(options.onEnqueue,undefined,options):undefined;const closeObserver=options.onClose?AsyncResource.bind(options.onClose,undefined,options):undefined;if(!await authorize())return new Response("Unauthorized",{status:401});const server=getServer();if(!server)throw new Error("Broadcast server not initialized");const encoder=new TextEncoder;const maxPending=options.maxPending??64;if(!Number.isSafeInteger(maxPending)||maxPending<1||maxPending>1024||options.heartbeatMs!==undefined&&(!Number.isFinite(options.heartbeatMs)||options.heartbeatMs<1))throw new Error("Invalid broadcast stream configuration");let cleanup=()=>{};let releaseInvalidations;let hintDelivery;let pendingResync=false,invalidationsClosed=false;if(invalidations){try{releaseInvalidations=await invalidations.subscribe({channels:[...channels],signal:options.signal,onInvalidate(notice){if(hintDelivery)hintDelivery(notice);else pendingResync=true},onClose(){invalidationsClosed=true;cleanup()}});if(!await authorize()){releaseInvalidations();return new Response("Unauthorized",{status:401})}if(invalidationsClosed){releaseInvalidations();return new Response("Invalidation transport unavailable",{status:503,headers:{"Cache-Control":"no-store"}})}}catch{releaseInvalidations?.();return new Response("Invalidation transport unavailable",{status:503,headers:{"Cache-Control":"no-store"}})}}const stream=new ReadableStream({start(controller){let closed=false,pending=0;let chain=Promise.resolve();let timer;let remove=()=>{};function close(){if(closed)return;closed=true;remove();const release=releaseInvalidations;releaseInvalidations=undefined;release?.();clearInterval(timer);options.signal?.removeEventListener("abort",close);try{controller.close()}catch{}try{const result=closeObserver?.();if(result!==undefined)Promise.resolve(result).catch(()=>{})}catch{}}function enqueue(frame,broadcast=null){if(closed)return;if((controller.desiredSize??0)<=0){close();return}const chunk=encoder.encode(frame);controller.enqueue(chunk);try{const result=enqueueObserver?.(chunk,broadcast);if(result!==undefined)Promise.resolve(result).catch(close)}catch{close()}}function deliver(frame,broadcast=null){if(closed)return;if(++pending>maxPending){close();return}chain=chain.then(async()=>{if(closed)return;if(!await authorize()){close();return}enqueue(frame,broadcast)}).catch(close).finally(()=>{pending--})}cleanup=close;remove=server.addBroadcastHook(({channel,event,data})=>{if(channels.has(channel))deliver(`data: ${JSON.stringify({channel,event,data})}
2
2
 
3
- `,{channel,event,data})});enqueue(`: connected
3
+ `,{channel,event,data})});hintDelivery=(notice)=>{for(const channel of notice.channels)if(channels.has(channel))deliver(`data: ${JSON.stringify({channel,event:"invalidated",data:null})}
4
4
 
5
- `);if(!closed){timer=setInterval(()=>deliver(`: heartbeat
5
+ `,{channel,event:"invalidated",data:null})};enqueue(`: connected
6
+
7
+ `);if(pendingResync)hintDelivery({channels:[...channels],reason:"resync"});if(!closed){timer=setInterval(()=>deliver(`: heartbeat
6
8
 
7
9
  `),options.heartbeatMs??15000);options.signal?.addEventListener("abort",close,{once:true});if(options.signal?.aborted)close()}},cancel(){cleanup()}},{highWaterMark:maxPending});return new Response(stream,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-store","X-Accel-Buffering":"no"}})}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/realtime",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.582",
5
+ "version": "0.75.585",
6
6
  "description": "The Stacks realtime integration. Built on top of ts-broadcasting.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,8 +58,8 @@
58
58
  "prepublishOnly": "bun run build"
59
59
  },
60
60
  "dependencies": {
61
- "@stacksjs/logging": "0.75.582",
62
- "@stacksjs/path": "0.75.582",
61
+ "@stacksjs/logging": "0.75.585",
62
+ "@stacksjs/path": "0.75.585",
63
63
  "ts-broadcasting": "^0.0.12"
64
64
  },
65
65
  "devDependencies": {