@20baht/live 0.1.0 → 0.1.2

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
@@ -17,7 +17,7 @@ bun add @20baht/live
17
17
  | Entry | What it holds |
18
18
  | --- | --- |
19
19
  | `@20baht/live` | `createLive` (the hub of one process), `memorySource`, topics, the frame protocol |
20
- | `@20baht/live/elysia` | `livePlugin` (the `live` route option, `POST /live`, `GET /live/health`), `bindLive` |
20
+ | `@20baht/live/elysia` | `livePlugin` (once, at the root: the option, `POST /live`, `GET /live/health`), `liveMacro` (the option alone, for modules), `liveRoute`, `bindLive` |
21
21
  | `@20baht/live/pg` | `liveTriggers` (the SQL for a migration), `pgSource`, `postgresJsListener`, `pgliteListener`, `changed` |
22
22
  | `@20baht/live/browser` | `liveClient` / `createLiveClient`, `typedLive`, `guess`, `rebase` |
23
23
 
@@ -29,7 +29,7 @@ bun add @20baht/live
29
29
  import postgres from 'postgres';
30
30
  import { Elysia } from 'elysia';
31
31
  import { createLive } from '@20baht/live';
32
- import { bindLive, livePlugin } from '@20baht/live/elysia';
32
+ import { bindLive, liveMacro, livePlugin, liveRoute } from '@20baht/live/elysia';
33
33
  import { pgSource, postgresJsListener } from '@20baht/live/pg';
34
34
 
35
35
  // once per process, at the root: one LISTEN connection, one hub, one run table
@@ -39,24 +39,34 @@ const live = createLive({
39
39
  caller: async (headers) => (await session(headers))?.user ?? null,
40
40
  });
41
41
 
42
- export const app = new Elysia()
43
- .use(livePlugin(live))
44
- .get('/boards/:id/issues', ({ params }) => issuesOf(params.id), {
45
- live: {
46
- // worked out on the server; a browser names a route, never a topic
42
+ // a module: liveMacro adds the `live` option and no route
43
+ const boards = new Elysia({ prefix: '/boards' })
44
+ .use(liveMacro(live))
45
+ .get('/:id/issues', ({ params }) => issuesOf(params.id), {
46
+ // worked out on the server; a browser names a route, never a topic
47
+ live: liveRoute(live, {
47
48
  topics: ({ params }) => [`board_issues@board_id=${params.id}`, 'board_assignees'],
48
49
  key: 'id', // frames after the first are patches of the rows that changed
49
- },
50
+ }),
50
51
  })
51
52
  .post('/tickets/search', ({ body }) => search(body), {
52
53
  ...tableRoute(ticketsTable),
53
- live: { topics: ({ caller }) => [`tickets@org_id=${caller.orgId}`], key: 'id', rows: 'rows' },
54
+ live: liveRoute(live, {
55
+ topics: ({ caller }) => [`tickets@org_id=${caller.orgId}`],
56
+ key: 'id',
57
+ rows: 'rows',
58
+ }),
54
59
  });
55
60
 
61
+ // the root: livePlugin adds the option and POST /live + GET /live/health, once
62
+ export const app = new Elysia().use(livePlugin(live)).use(boards);
56
63
  bindLive(live, app);
57
64
  process.on('SIGTERM', () => live.close());
58
65
  ```
59
66
 
67
+ - Write the option through `liveRoute(live, …)`: it types `caller` from the hub, and a callback
68
+ placed directly in a route's options would stop TypeScript inferring the route's own `query`,
69
+ `body` and `params` types.
60
70
  - A run goes through `app.handle` with the stream's own `cookie` and `authorization` headers
61
71
  (`forward`), so the route's guard and handler are the ones a fetch would meet. A route not
62
72
  marked `live` is never run for a stream.
@@ -93,6 +103,18 @@ await db.transaction(async (tx) => {
93
103
 
94
104
  Without Postgres: `memorySource()` and `live.emit(topics)` (one process).
95
105
 
106
+ ### Which source
107
+
108
+ `changed(tx, topics)` is a `pg_notify` inside the transaction: only a `pgSource` that LISTENs hears
109
+ it. With `memorySource()`, raise topics with `live.emit(topics)` instead.
110
+
111
+ | Source | Topics come from | Heard | Writers it sees |
112
+ | --- | --- | --- | --- |
113
+ | `memorySource()` | `live.emit(topics)` in your code | when `emit` runs; a rollback after it does not take it back | this process's code only |
114
+ | `pgSource(listener)` | `liveTriggers` on tables, `changed(tx, topics)`, or `live.emit` (a NOTIFY of its own) | on commit, never on rollback | any writer, any process (`psql`, a job, another server) |
115
+
116
+ `pgliteListener` gives PGlite the same LISTEN, so tests and a single-file app can use `pgSource` too.
117
+
96
118
  ## Browser
97
119
 
98
120
  ```ts
@@ -115,6 +137,9 @@ await live.mutate(
115
137
  - It reconnects with backoff, sending the version it holds; an answer that did not change costs an
116
138
  `unchanged` frame. Without a stream it tries again when the page is shown again or the network is
117
139
  back, never on a timer.
140
+ - A page put away (`pagehide`: navigating off, or into the back/forward cache) closes its stream, so
141
+ a cached page holds none of the host's six HTTP/1.1 connections; back from the cache (`pageshow`
142
+ with `persisted`), it reconnects.
118
143
  - A mutation carries an `Idempotency-Key` (`@20baht/elysia-idempotency`). Its guess stays until a
119
144
  frame follows the write's answer (or `settleMs`, 5 s); a refused write takes it off at once and
120
145
  throws `LiveMutationError` with the status and body.
package/dist/browser.d.ts CHANGED
@@ -26,6 +26,11 @@ export interface LiveEnvironment {
26
26
  clearTimeout: (handle: unknown) => void;
27
27
  /** Hear `online` and the page being shown again; returns how to stop. */
28
28
  onWake: (wake: () => void) => () => void;
29
+ /**
30
+ * Hear the page being put away (`pagehide`: a navigation, or the back/forward cache, where a
31
+ * stream left open would hold one of the host's few HTTP/1.1 connections); returns how to stop.
32
+ */
33
+ onHide?: ((hide: () => void) => () => void) | undefined;
29
34
  /** A fresh id for a mutation's `Idempotency-Key`. */
30
35
  uuid: () => string;
31
36
  }
package/dist/browser.js CHANGED
@@ -24,13 +24,27 @@ const browserEnvironment = () => ({
24
24
  if (document.visibilityState === 'visible')
25
25
  wake();
26
26
  };
27
+ const shown = (event) => {
28
+ if (event.persisted)
29
+ wake();
30
+ };
27
31
  window.addEventListener('online', wake);
32
+ window.addEventListener('pageshow', shown);
28
33
  document.addEventListener('visibilitychange', visible);
29
34
  return () => {
30
35
  window.removeEventListener('online', wake);
36
+ window.removeEventListener('pageshow', shown);
31
37
  document.removeEventListener('visibilitychange', visible);
32
38
  };
33
39
  },
40
+ onHide: (hide) => {
41
+ if (typeof window === 'undefined')
42
+ return () => undefined;
43
+ window.addEventListener('pagehide', hide);
44
+ return () => {
45
+ window.removeEventListener('pagehide', hide);
46
+ };
47
+ },
34
48
  uuid: () => crypto.randomUUID(),
35
49
  });
36
50
  const MIN_BACKOFF = 1000;
@@ -203,6 +217,13 @@ export function createLiveClient(options) {
203
217
  backoff = MIN_BACKOFF;
204
218
  schedule(0);
205
219
  });
220
+ const stopHiding = env.onHide?.(() => {
221
+ env.clearTimeout(pending);
222
+ env.clearTimeout(retry);
223
+ retry = undefined;
224
+ connection?.abort();
225
+ connection = undefined;
226
+ }) ?? (() => undefined);
206
227
  const handleOf = new WeakMap();
207
228
  const subscribe = (request, listener) => {
208
229
  const key = requestKey(request);
@@ -312,6 +333,7 @@ export function createLiveClient(options) {
312
333
  close: () => {
313
334
  closed = true;
314
335
  stopWaking();
336
+ stopHiding();
315
337
  env.clearTimeout(pending);
316
338
  env.clearTimeout(retry);
317
339
  connection?.abort();
package/dist/elysia.d.ts CHANGED
@@ -23,6 +23,18 @@ export interface LiveRoute<C extends Caller | null> {
23
23
  */
24
24
  share?: ((context: LiveRouteContext<C>) => string) | undefined;
25
25
  }
26
+ /**
27
+ * A route's `live` option, typed by the hub (its caller) and kept apart from the route's own
28
+ * types. Write the option through it whenever `topics` or `share` reads its argument: a callback
29
+ * TypeScript must type from context, placed directly in a route's options, stops it from inferring
30
+ * the route's `query`, `body` and `params` from their schemas.
31
+ *
32
+ * .get('/activity', ({ query }) => list(query), {
33
+ * query: t.Object({ limit: t.Optional(t.Numeric()) }),
34
+ * live: liveRoute(live, { topics: ({ caller }) => [`events@project_id=${caller.projectId}`] }),
35
+ * })
36
+ */
37
+ export declare function liveRoute<C extends Caller | null>(_live: Live<C>, route: LiveRoute<C>): LiveRoute<C>;
26
38
  type HookList = {
27
39
  fn?: unknown;
28
40
  }[] | {
@@ -44,15 +56,57 @@ export interface LivePluginOptions<Path extends string = '/live'> {
44
56
  path?: Path | undefined;
45
57
  }
46
58
  /**
47
- * The `live` route option and the stream's routes. Use it in the root app and in every module
48
- * whose routes are live (Elysia applies it once per hub), then `bindLive(live, app)` once the app
49
- * is built.
59
+ * The `live` route option alone. Use it in every module whose routes are live: it adds no route,
60
+ * so a module mounted under a prefix does not get a stream of its own.
61
+ *
62
+ * export const issues = (live: Live<Me>) =>
63
+ * new Elysia({ prefix: '/issues' }).use(liveMacro(live)).get('/', list, {
64
+ * live: liveRoute(live, { topics: ({ caller }) => [`issues@org_id=${caller.orgId}`], key: 'id' }),
65
+ * })
66
+ */
67
+ export declare function liveMacro<C extends Caller | null>(live: Live<C>): Elysia<"", {
68
+ decorator: {};
69
+ store: {};
70
+ derive: {};
71
+ resolve: {};
72
+ }, {
73
+ typebox: {};
74
+ error: {};
75
+ }, {
76
+ schema: {};
77
+ standaloneSchema: {};
78
+ macro: Partial<{
79
+ readonly live: LiveRoute<C>;
80
+ }>;
81
+ macroFn: {
82
+ readonly live: (route: LiveRoute<C>) => {
83
+ readonly beforeHandle: ({ request, ...rest }: {
84
+ request: Request;
85
+ }) => void;
86
+ };
87
+ };
88
+ parser: {};
89
+ response: {};
90
+ }, {}, {
91
+ derive: {};
92
+ resolve: {};
93
+ schema: {};
94
+ standaloneSchema: {};
95
+ response: {};
96
+ }, {
97
+ derive: {};
98
+ resolve: {};
99
+ schema: {};
100
+ standaloneSchema: {};
101
+ response: {};
102
+ }>;
103
+ /**
104
+ * The `live` route option and the stream's routes (`POST /live`, `GET /live/health`). Use it once,
105
+ * in the root app (modules take `liveMacro`), then `bindLive(live, app)` once the app is built.
50
106
  *
51
107
  * const app = new Elysia()
52
108
  * .use(livePlugin(live))
53
- * .get('/boards/:id/issues', ({ params }) => issues(params.id), {
54
- * live: { topics: ({ params }) => [`board_issues@board_id=${params.id}`], key: 'id' },
55
- * })
109
+ * .use(issues(live))
56
110
  * bindLive(live, app)
57
111
  */
58
112
  export declare function livePlugin<C extends Caller | null, Path extends string = '/live'>(live: Live<C>, options?: LivePluginOptions<Path>): Elysia<"", {
@@ -64,6 +118,13 @@ export declare function livePlugin<C extends Caller | null, Path extends string
64
118
  typebox: {};
65
119
  error: {};
66
120
  }, {
121
+ schema: {};
122
+ standaloneSchema: {};
123
+ macro: {};
124
+ macroFn: {};
125
+ parser: {};
126
+ response: {};
127
+ } & {
67
128
  schema: {};
68
129
  standaloneSchema: {};
69
130
  macro: Partial<{
@@ -71,11 +132,8 @@ export declare function livePlugin<C extends Caller | null, Path extends string
71
132
  }>;
72
133
  macroFn: {
73
134
  readonly live: (route: LiveRoute<C>) => {
74
- readonly beforeHandle: (context: {
135
+ readonly beforeHandle: ({ request, ...rest }: {
75
136
  request: Request;
76
- params?: unknown;
77
- query?: unknown;
78
- body?: unknown;
79
137
  }) => void;
80
138
  };
81
139
  };
@@ -260,6 +318,12 @@ export declare function livePlugin<C extends Caller | null, Path extends string
260
318
  schema: {};
261
319
  standaloneSchema: {};
262
320
  response: {};
321
+ } & {
322
+ derive: {};
323
+ resolve: {};
324
+ schema: {};
325
+ standaloneSchema: {};
326
+ response: {};
263
327
  }>;
264
328
  /** Tell the hub which app its live routes are in. Call it once the app is built. */
265
329
  export declare function bindLive<C extends Caller | null>(live: Live<C>, app: AppLike): void;
package/dist/elysia.js CHANGED
@@ -1,16 +1,18 @@
1
1
  import { Elysia } from 'elysia';
2
2
  import { requestTarget } from './protocol.js';
3
+ export function liveRoute(_live, route) {
4
+ return route;
5
+ }
3
6
  const apps = new WeakMap();
4
- export function livePlugin(live, options = {}) {
5
- const path = (options.path ?? '/live');
7
+ export function liveMacro(live) {
6
8
  const marks = marksOf(live);
7
- return new Elysia({ name: '@20baht/live', seed: live })
8
- .macro({
9
+ return new Elysia({ name: '@20baht/live/macro', seed: live }).macro({
9
10
  live: (route) => {
10
- const beforeHandle = (context) => {
11
- const run = runs.get(context.request);
11
+ const beforeHandle = ({ request, ...rest }) => {
12
+ const run = runs.get(request);
12
13
  if (run === undefined)
13
14
  return;
15
+ const context = rest;
14
16
  const handed = {
15
17
  params: (context.params ?? {}),
16
18
  query: (context.query ?? {}),
@@ -27,9 +29,14 @@ export function livePlugin(live, options = {}) {
27
29
  marks.add(beforeHandle);
28
30
  return { beforeHandle };
29
31
  },
30
- })
31
- .post(path, ({ request, body }) => open(live, request, body))
32
- .get(`${path}/health`, () => live.health());
32
+ });
33
+ }
34
+ export function livePlugin(live, options = {}) {
35
+ const path = (options.path ?? '/live');
36
+ return (new Elysia({ name: '@20baht/live', seed: live })
37
+ .use(liveMacro(live))
38
+ .post(path, ({ request, body }) => open(live, request, body), { detail: { hide: true } })
39
+ .get(`${path}/health`, () => live.health(), { detail: { hide: true } }));
33
40
  }
34
41
  const runs = new WeakMap();
35
42
  const allMarks = new WeakMap();
@@ -56,14 +63,14 @@ export function appRunner(app, marks) {
56
63
  count: app.routes.length,
57
64
  routes: app.routes
58
65
  .filter((route) => hooksOf(route).some((fn) => typeof fn === 'function' && marks.has(fn)))
59
- .map((route) => ({ method: route.method, segments: route.path.split('/').slice(1) })),
66
+ .map((route) => ({ method: route.method, segments: segmentsOf(route.path) })),
60
67
  };
61
68
  }
62
69
  return known.routes;
63
70
  };
64
71
  return {
65
72
  isLive: (request) => {
66
- const segments = request.path.split('/').slice(1);
73
+ const segments = segmentsOf(request.path);
67
74
  return liveRoutes().some((route) => route.method === request.method && matches(route.segments, segments));
68
75
  },
69
76
  run: async (request, headers, caller) => {
@@ -81,6 +88,12 @@ function hooksOf(route) {
81
88
  return [];
82
89
  return (Array.isArray(list) ? list : [list]).map((hook) => hook.fn);
83
90
  }
91
+ function segmentsOf(path) {
92
+ const segments = path.split('/').slice(1);
93
+ if (segments.length > 1 && segments.at(-1) === '')
94
+ segments.pop();
95
+ return segments;
96
+ }
84
97
  function matches(pattern, segments) {
85
98
  for (const [index, part] of pattern.entries()) {
86
99
  if (part === '*')
package/dist/protocol.js CHANGED
@@ -46,7 +46,9 @@ function isPath(path) {
46
46
  path.startsWith('/') &&
47
47
  !path.startsWith('//') &&
48
48
  path.length <= 2048 &&
49
- !/[?#\s]/.test(path));
49
+ !/[?#\s\\]/.test(path) &&
50
+ !/%2e|%2f|%5c/i.test(path) &&
51
+ !path.split('/').some((segment) => segment === '.' || segment === '..'));
50
52
  }
51
53
  function isStringRecord(value) {
52
54
  return (typeof value === 'object' &&
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@20baht/live",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"