@20baht/live 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +132 -2
- package/dist/browser.d.ts +164 -0
- package/dist/browser.js +404 -0
- package/dist/elysia.d.ts +268 -0
- package/dist/elysia.js +118 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/live.d.ts +81 -0
- package/dist/live.js +393 -0
- package/dist/pg.d.ts +81 -0
- package/dist/pg.js +214 -0
- package/dist/protocol.d.ts +112 -0
- package/dist/protocol.js +122 -0
- package/dist/source.d.ts +17 -0
- package/dist/source.js +24 -0
- package/dist/topics.d.ts +10 -0
- package/dist/topics.js +25 -0
- package/package.json +86 -4
package/dist/pg.js
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import { sql } from 'drizzle-orm';
|
|
2
|
+
import { getTableConfig } from 'drizzle-orm/pg-core';
|
|
3
|
+
import { cleanTopics } from './topics.js';
|
|
4
|
+
export const DEFAULT_CHANNEL = 'live';
|
|
5
|
+
const MAX_PAYLOAD = 7900;
|
|
6
|
+
const IDENT = /^[A-Za-z_][A-Za-z0-9_$]{0,62}$/;
|
|
7
|
+
function ident(name) {
|
|
8
|
+
if (!IDENT.test(name))
|
|
9
|
+
throw new Error(`live: "${name}" is not a plain SQL identifier`);
|
|
10
|
+
return `"${name}"`;
|
|
11
|
+
}
|
|
12
|
+
function literal(text) {
|
|
13
|
+
return `'${text.replaceAll("'", "''")}'`;
|
|
14
|
+
}
|
|
15
|
+
const nameOf = (column) => typeof column === 'string' ? column : column.name;
|
|
16
|
+
function resolve(tracked, needKey = true) {
|
|
17
|
+
let schema = tracked.schema ?? 'public';
|
|
18
|
+
let name;
|
|
19
|
+
let key = tracked.key?.map(nameOf);
|
|
20
|
+
if (typeof tracked.table === 'string') {
|
|
21
|
+
name = tracked.table;
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
const config = getTableConfig(tracked.table);
|
|
25
|
+
name = config.name;
|
|
26
|
+
schema = config.schema ?? schema;
|
|
27
|
+
key ??= [
|
|
28
|
+
...config.columns.filter((column) => column.primary).map((column) => column.name),
|
|
29
|
+
...(config.primaryKeys[0]?.columns.map((column) => column.name) ?? []),
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
if (needKey && (key === undefined || key.length === 0)) {
|
|
33
|
+
throw new Error(`live: table "${name}" needs its key columns (key: [...])`);
|
|
34
|
+
}
|
|
35
|
+
const scope = tracked.scope?.map(nameOf) ?? [];
|
|
36
|
+
for (const column of [name, schema, ...(key ?? []), ...scope])
|
|
37
|
+
ident(column);
|
|
38
|
+
return { schema, name, key: key ?? [], scope };
|
|
39
|
+
}
|
|
40
|
+
export function liveTriggers(tables, options = {}) {
|
|
41
|
+
const channel = options.channel ?? DEFAULT_CHANNEL;
|
|
42
|
+
const fn = ident(options.functionName ?? 'live_notify');
|
|
43
|
+
const truncateFn = ident(`${options.functionName ?? 'live_notify'}_truncate`);
|
|
44
|
+
const parts = [
|
|
45
|
+
`CREATE OR REPLACE FUNCTION ${fn}() RETURNS trigger LANGUAGE plpgsql AS $live$
|
|
46
|
+
DECLARE
|
|
47
|
+
key_columns text[] := string_to_array(TG_ARGV[1], ',');
|
|
48
|
+
scope_columns text[] := coalesce(string_to_array(nullif(TG_ARGV[2], ''), ','), ARRAY[]::text[]);
|
|
49
|
+
records jsonb[] := ARRAY[]::jsonb[];
|
|
50
|
+
r jsonb;
|
|
51
|
+
c text;
|
|
52
|
+
k text;
|
|
53
|
+
topic text;
|
|
54
|
+
topics text[] := ARRAY[TG_TABLE_NAME::text];
|
|
55
|
+
payload text;
|
|
56
|
+
BEGIN
|
|
57
|
+
IF TG_OP IN ('UPDATE', 'DELETE') THEN records := records || to_jsonb(OLD); END IF;
|
|
58
|
+
IF TG_OP IN ('UPDATE', 'INSERT') THEN records := records || to_jsonb(NEW); END IF;
|
|
59
|
+
FOREACH r IN ARRAY records LOOP
|
|
60
|
+
SELECT string_agg(coalesce(r ->> u.col, ''), ',' ORDER BY u.ord) INTO k
|
|
61
|
+
FROM unnest(key_columns) WITH ORDINALITY AS u(col, ord);
|
|
62
|
+
topic := TG_TABLE_NAME || ':' || k;
|
|
63
|
+
topics := topics || CASE WHEN length(topic) > 200 THEN TG_TABLE_NAME || '*' ELSE topic END;
|
|
64
|
+
FOREACH c IN ARRAY scope_columns LOOP
|
|
65
|
+
topic := TG_TABLE_NAME || '@' || c || '=' || coalesce(r ->> c, '');
|
|
66
|
+
topics := topics || CASE WHEN length(topic) > 200 THEN TG_TABLE_NAME || '*' ELSE topic END;
|
|
67
|
+
END LOOP;
|
|
68
|
+
END LOOP;
|
|
69
|
+
payload := json_build_object('topics', (SELECT array_agg(DISTINCT t) FROM unnest(topics) AS t))::text;
|
|
70
|
+
IF octet_length(payload) > 7900 THEN
|
|
71
|
+
payload := json_build_object('topics', ARRAY[TG_TABLE_NAME || '*'])::text;
|
|
72
|
+
END IF;
|
|
73
|
+
PERFORM pg_notify(TG_ARGV[0], payload);
|
|
74
|
+
RETURN NULL;
|
|
75
|
+
END
|
|
76
|
+
$live$;`,
|
|
77
|
+
`CREATE OR REPLACE FUNCTION ${truncateFn}() RETURNS trigger LANGUAGE plpgsql AS $live$
|
|
78
|
+
BEGIN
|
|
79
|
+
PERFORM pg_notify(TG_ARGV[0], json_build_object('topics', ARRAY[TG_TABLE_NAME || '*'])::text);
|
|
80
|
+
RETURN NULL;
|
|
81
|
+
END
|
|
82
|
+
$live$;`,
|
|
83
|
+
];
|
|
84
|
+
for (const tracked of tables) {
|
|
85
|
+
const { schema, name, key, scope } = resolve(tracked);
|
|
86
|
+
const table = `${ident(schema)}.${ident(name)}`;
|
|
87
|
+
const row = ident(`${name}_live`);
|
|
88
|
+
const truncate = ident(`${name}_live_truncate`);
|
|
89
|
+
const args = [channel, key.join(','), scope.join(',')].map(literal).join(', ');
|
|
90
|
+
parts.push(`DROP TRIGGER IF EXISTS ${row} ON ${table};`, `CREATE TRIGGER ${row} AFTER INSERT OR UPDATE OR DELETE ON ${table} FOR EACH ROW EXECUTE FUNCTION ${fn}(${args});`, `DROP TRIGGER IF EXISTS ${truncate} ON ${table};`, `CREATE TRIGGER ${truncate} AFTER TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION ${truncateFn}(${literal(channel)});`);
|
|
91
|
+
}
|
|
92
|
+
return `${parts.join('\n')}\n`;
|
|
93
|
+
}
|
|
94
|
+
export function dropLiveTriggers(tables) {
|
|
95
|
+
return `${tables
|
|
96
|
+
.flatMap((tracked) => {
|
|
97
|
+
const { schema, name } = resolve(tracked, false);
|
|
98
|
+
const table = `${ident(schema)}.${ident(name)}`;
|
|
99
|
+
return [
|
|
100
|
+
`DROP TRIGGER IF EXISTS ${ident(`${name}_live`)} ON ${table};`,
|
|
101
|
+
`DROP TRIGGER IF EXISTS ${ident(`${name}_live_truncate`)} ON ${table};`,
|
|
102
|
+
];
|
|
103
|
+
})
|
|
104
|
+
.join('\n')}\n`;
|
|
105
|
+
}
|
|
106
|
+
export function postgresJsListener(client) {
|
|
107
|
+
return {
|
|
108
|
+
listen: async (channel, onPayload, onListen) => {
|
|
109
|
+
const { unlisten } = await client.listen(channel, onPayload, onListen);
|
|
110
|
+
return unlisten;
|
|
111
|
+
},
|
|
112
|
+
notify: (channel, payload) => client.notify(channel, payload),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
export function pgliteListener(pg) {
|
|
116
|
+
return {
|
|
117
|
+
listen: async (channel, onPayload, onListen) => {
|
|
118
|
+
const stop = await pg.listen(channel, onPayload);
|
|
119
|
+
onListen();
|
|
120
|
+
return stop;
|
|
121
|
+
},
|
|
122
|
+
notify: (channel, payload) => pg.query('SELECT pg_notify($1, $2)', [channel, payload]),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
const MAX_RETRY_MS = 30_000;
|
|
126
|
+
export function pgSource(listener, options = {}) {
|
|
127
|
+
const channel = options.channel ?? DEFAULT_CHANNEL;
|
|
128
|
+
const log = options.log ??
|
|
129
|
+
((line) => {
|
|
130
|
+
console.error(line);
|
|
131
|
+
});
|
|
132
|
+
const firstRetry = options.retryMs ?? 1000;
|
|
133
|
+
let status = 'connecting';
|
|
134
|
+
return {
|
|
135
|
+
listen(onChange, onReset) {
|
|
136
|
+
let missed = false;
|
|
137
|
+
let up = false;
|
|
138
|
+
let stopped = false;
|
|
139
|
+
let stop;
|
|
140
|
+
let wait = firstRetry;
|
|
141
|
+
let timer;
|
|
142
|
+
const attempt = () => {
|
|
143
|
+
listener
|
|
144
|
+
.listen(channel, (payload) => {
|
|
145
|
+
const topics = topicsOf(payload);
|
|
146
|
+
if (topics.length > 0)
|
|
147
|
+
onChange(topics);
|
|
148
|
+
}, () => {
|
|
149
|
+
status = 'connected';
|
|
150
|
+
wait = firstRetry;
|
|
151
|
+
if (up || missed)
|
|
152
|
+
onReset();
|
|
153
|
+
up = true;
|
|
154
|
+
missed = false;
|
|
155
|
+
})
|
|
156
|
+
.then((unlisten) => {
|
|
157
|
+
if (stopped)
|
|
158
|
+
void unlisten();
|
|
159
|
+
else
|
|
160
|
+
stop = unlisten;
|
|
161
|
+
}, (error) => {
|
|
162
|
+
status = 'reconnecting';
|
|
163
|
+
missed = true;
|
|
164
|
+
log(`live: could not listen on "${channel}": ${String(error)}; trying again in ${wait} ms`);
|
|
165
|
+
if (stopped)
|
|
166
|
+
return;
|
|
167
|
+
timer = setTimeout(attempt, wait);
|
|
168
|
+
wait = Math.min(wait * 2, MAX_RETRY_MS);
|
|
169
|
+
});
|
|
170
|
+
};
|
|
171
|
+
attempt();
|
|
172
|
+
return () => {
|
|
173
|
+
stopped = true;
|
|
174
|
+
clearTimeout(timer);
|
|
175
|
+
void stop?.();
|
|
176
|
+
};
|
|
177
|
+
},
|
|
178
|
+
emit: async (topics) => {
|
|
179
|
+
for (const payload of payloads(cleanTopics(topics)))
|
|
180
|
+
await listener.notify(channel, payload);
|
|
181
|
+
},
|
|
182
|
+
status: () => status,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
function topicsOf(payload) {
|
|
186
|
+
try {
|
|
187
|
+
const parsed = JSON.parse(payload);
|
|
188
|
+
return Array.isArray(parsed?.topics) ? cleanTopics(parsed.topics) : [];
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return [];
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function payloads(topics) {
|
|
195
|
+
const out = [];
|
|
196
|
+
let batch = [];
|
|
197
|
+
for (const topic of topics) {
|
|
198
|
+
const next = [...batch, topic];
|
|
199
|
+
if (batch.length > 0 && JSON.stringify({ topics: next }).length > MAX_PAYLOAD) {
|
|
200
|
+
out.push(JSON.stringify({ topics: batch }));
|
|
201
|
+
batch = [topic];
|
|
202
|
+
}
|
|
203
|
+
else
|
|
204
|
+
batch = next;
|
|
205
|
+
}
|
|
206
|
+
if (batch.length > 0)
|
|
207
|
+
out.push(JSON.stringify({ topics: batch }));
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
export async function changed(tx, topics, channel = DEFAULT_CHANNEL) {
|
|
211
|
+
for (const payload of payloads(cleanTopics(topics))) {
|
|
212
|
+
await tx.execute(sql `SELECT pg_notify(${channel}, ${payload})`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
export type LiveMethod = 'GET' | 'POST';
|
|
2
|
+
/** A route and its input, as a fetch of it would send them. */
|
|
3
|
+
export interface LiveRequest {
|
|
4
|
+
method: LiveMethod;
|
|
5
|
+
/** The path with its parameters filled in, starting with `/`, without a query. */
|
|
6
|
+
path: string;
|
|
7
|
+
query?: Record<string, string> | undefined;
|
|
8
|
+
body?: unknown;
|
|
9
|
+
}
|
|
10
|
+
/** One subscription in `POST /live`'s body: its id on this stream, the route, what the client holds. */
|
|
11
|
+
export type Subscription = LiveRequest & {
|
|
12
|
+
id: string;
|
|
13
|
+
version?: string | undefined;
|
|
14
|
+
};
|
|
15
|
+
export type RowKey = string | number;
|
|
16
|
+
export type Frame = {
|
|
17
|
+
event: 'snapshot';
|
|
18
|
+
data: {
|
|
19
|
+
id: string;
|
|
20
|
+
version: string;
|
|
21
|
+
body: unknown;
|
|
22
|
+
};
|
|
23
|
+
} | {
|
|
24
|
+
event: 'patch';
|
|
25
|
+
data: {
|
|
26
|
+
id: string;
|
|
27
|
+
version: string;
|
|
28
|
+
/** The row key the patch is keyed by. */
|
|
29
|
+
key: string;
|
|
30
|
+
/** The answer's key holding the rows; absent when the answer is the list. */
|
|
31
|
+
rows?: string;
|
|
32
|
+
upsert: unknown[];
|
|
33
|
+
remove: RowKey[];
|
|
34
|
+
/** Every row's key, in order: sent only when the order changed. */
|
|
35
|
+
order?: RowKey[];
|
|
36
|
+
/** The answer's other keys, when its rows sit under `rows`. */
|
|
37
|
+
rest?: Record<string, unknown>;
|
|
38
|
+
};
|
|
39
|
+
} | {
|
|
40
|
+
event: 'unchanged';
|
|
41
|
+
data: {
|
|
42
|
+
id: string;
|
|
43
|
+
version: string;
|
|
44
|
+
};
|
|
45
|
+
} | {
|
|
46
|
+
event: 'error';
|
|
47
|
+
data: {
|
|
48
|
+
id: string;
|
|
49
|
+
status: number;
|
|
50
|
+
body: unknown;
|
|
51
|
+
};
|
|
52
|
+
} | {
|
|
53
|
+
event: 'end';
|
|
54
|
+
data: {
|
|
55
|
+
reason: EndReason;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
export type EndReason = 'unauthorized' | 'signed-out' | 'caller-changed' | 'shutdown' | 'too-many';
|
|
59
|
+
/** One frame as server-sent event text. */
|
|
60
|
+
export declare const encodeFrame: (frame: Frame) => string;
|
|
61
|
+
/** The most subscriptions one stream may hold, unless the server says otherwise. */
|
|
62
|
+
export declare const MAX_SUBSCRIPTIONS = 50;
|
|
63
|
+
/**
|
|
64
|
+
* `POST /live`'s body, checked: a list of subscriptions with unique ids, each a `GET` or `POST`
|
|
65
|
+
* of a path on this server. Returns a message for the 400 instead when it is not.
|
|
66
|
+
*/
|
|
67
|
+
export declare function parseSubscriptions(body: unknown, max?: number): {
|
|
68
|
+
ok: true;
|
|
69
|
+
subscriptions: Subscription[];
|
|
70
|
+
} | {
|
|
71
|
+
ok: false;
|
|
72
|
+
message: string;
|
|
73
|
+
};
|
|
74
|
+
/** The URL path and query of a request, in a stable order. */
|
|
75
|
+
export declare function requestTarget(request: LiveRequest): string;
|
|
76
|
+
/** A name for a request: two subscriptions with the same one ask the same thing. */
|
|
77
|
+
export declare const requestKey: (request: LiveRequest) => string;
|
|
78
|
+
/** JSON with object keys sorted, so the same value always writes the same text. */
|
|
79
|
+
export declare function stableJson(value: unknown): string;
|
|
80
|
+
/**
|
|
81
|
+
* An answer's version: a 64-bit FNV-1a hash of its stable JSON, as 16 hex digits. Not a secret
|
|
82
|
+
* and not a guard, only a way to say "this is the answer you already hold".
|
|
83
|
+
*/
|
|
84
|
+
export declare function versionOf(body: unknown): string;
|
|
85
|
+
/** Where a keyed answer's rows are: the answer itself, or one of its keys. */
|
|
86
|
+
export interface RowsAt {
|
|
87
|
+
key: string;
|
|
88
|
+
rows?: string | undefined;
|
|
89
|
+
}
|
|
90
|
+
/** The rows of `body` and its other keys, or null when they are not where `at` says. */
|
|
91
|
+
export declare function rowsOf(body: unknown, at: RowsAt): {
|
|
92
|
+
rows: Record<string, unknown>[];
|
|
93
|
+
rest: Record<string, unknown> | undefined;
|
|
94
|
+
} | null;
|
|
95
|
+
/**
|
|
96
|
+
* What turns the answer `before` into `after`, both keyed lists of rows: the rows new or changed,
|
|
97
|
+
* the keys gone, and the order when it is no longer the one left by those changes.
|
|
98
|
+
*/
|
|
99
|
+
export declare function diffRows(before: readonly Record<string, unknown>[], after: readonly Record<string, unknown>[], key: string): {
|
|
100
|
+
upsert: Record<string, unknown>[];
|
|
101
|
+
remove: RowKey[];
|
|
102
|
+
order?: RowKey[];
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* `rows` with a patch applied: removed keys go, a changed row stays in its place, a new one is
|
|
106
|
+
* added at the end; then `order`, when given, puts them in its order.
|
|
107
|
+
*/
|
|
108
|
+
export declare function applyPatch<Row extends Record<string, unknown>>(rows: readonly Row[], patch: {
|
|
109
|
+
upsert: readonly unknown[];
|
|
110
|
+
remove: readonly RowKey[];
|
|
111
|
+
order?: readonly RowKey[];
|
|
112
|
+
}, key: string): Row[];
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
export const encodeFrame = (frame) => `event: ${frame.event}\ndata: ${JSON.stringify(frame.data)}\n\n`;
|
|
2
|
+
export const MAX_SUBSCRIPTIONS = 50;
|
|
3
|
+
const ID = /^[\w.:-]{1,64}$/;
|
|
4
|
+
export function parseSubscriptions(body, max = MAX_SUBSCRIPTIONS) {
|
|
5
|
+
const list = body?.subscriptions;
|
|
6
|
+
if (!Array.isArray(list))
|
|
7
|
+
return { ok: false, message: 'subscriptions must be a list' };
|
|
8
|
+
if (list.length > max)
|
|
9
|
+
return { ok: false, message: `at most ${max} subscriptions` };
|
|
10
|
+
const ids = new Set();
|
|
11
|
+
const subscriptions = [];
|
|
12
|
+
for (const [index, item] of list.entries()) {
|
|
13
|
+
const sub = item;
|
|
14
|
+
const problem = problemOf(sub, ids);
|
|
15
|
+
if (problem !== undefined)
|
|
16
|
+
return { ok: false, message: `subscriptions[${index}].${problem}` };
|
|
17
|
+
const ok = sub;
|
|
18
|
+
ids.add(ok.id);
|
|
19
|
+
subscriptions.push({
|
|
20
|
+
id: ok.id,
|
|
21
|
+
method: ok.method,
|
|
22
|
+
path: ok.path,
|
|
23
|
+
...(ok.query === undefined ? {} : { query: ok.query }),
|
|
24
|
+
...(ok.body === undefined ? {} : { body: ok.body }),
|
|
25
|
+
...(ok.version === undefined ? {} : { version: ok.version }),
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
return { ok: true, subscriptions };
|
|
29
|
+
}
|
|
30
|
+
function problemOf(sub, ids) {
|
|
31
|
+
if (typeof sub?.id !== 'string' || !ID.test(sub.id) || ids.has(sub.id)) {
|
|
32
|
+
return 'id must be a unique name of 1 to 64 characters';
|
|
33
|
+
}
|
|
34
|
+
if (sub.method !== 'GET' && sub.method !== 'POST')
|
|
35
|
+
return 'method must be GET or POST';
|
|
36
|
+
if (!isPath(sub.path))
|
|
37
|
+
return 'path must be a path on this server';
|
|
38
|
+
if (sub.query !== undefined && !isStringRecord(sub.query))
|
|
39
|
+
return 'query must map names to strings';
|
|
40
|
+
if (sub.version !== undefined && typeof sub.version !== 'string')
|
|
41
|
+
return 'version must be a string';
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
function isPath(path) {
|
|
45
|
+
return (typeof path === 'string' &&
|
|
46
|
+
path.startsWith('/') &&
|
|
47
|
+
!path.startsWith('//') &&
|
|
48
|
+
path.length <= 2048 &&
|
|
49
|
+
!/[?#\s]/.test(path));
|
|
50
|
+
}
|
|
51
|
+
function isStringRecord(value) {
|
|
52
|
+
return (typeof value === 'object' &&
|
|
53
|
+
value !== null &&
|
|
54
|
+
!Array.isArray(value) &&
|
|
55
|
+
Object.values(value).every((v) => typeof v === 'string'));
|
|
56
|
+
}
|
|
57
|
+
export function requestTarget(request) {
|
|
58
|
+
const query = Object.entries(request.query ?? {}).sort(([a], [b]) => (a < b ? -1 : 1));
|
|
59
|
+
return query.length === 0 ? request.path : `${request.path}?${new URLSearchParams(query)}`;
|
|
60
|
+
}
|
|
61
|
+
export const requestKey = (request) => `${request.method} ${requestTarget(request)} ${request.body === undefined ? '' : stableJson(request.body)}`;
|
|
62
|
+
export function stableJson(value) {
|
|
63
|
+
return JSON.stringify(value ?? null, (_key, inner) => inner !== null && typeof inner === 'object' && !Array.isArray(inner)
|
|
64
|
+
? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => (a < b ? -1 : 1)))
|
|
65
|
+
: inner);
|
|
66
|
+
}
|
|
67
|
+
export function versionOf(body) {
|
|
68
|
+
const text = stableJson(body);
|
|
69
|
+
let hi = 0xcbf29ce4;
|
|
70
|
+
let lo = 0x84222325;
|
|
71
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
72
|
+
lo = (lo ^ text.charCodeAt(index)) >>> 0;
|
|
73
|
+
const loMul = lo * 0x1b3;
|
|
74
|
+
const carry = Math.floor(loMul / 0x100000000);
|
|
75
|
+
hi = (Math.imul(hi, 0x1b3) + Math.imul(lo, 0x100) + carry) >>> 0;
|
|
76
|
+
lo = loMul >>> 0;
|
|
77
|
+
}
|
|
78
|
+
return hi.toString(16).padStart(8, '0') + lo.toString(16).padStart(8, '0');
|
|
79
|
+
}
|
|
80
|
+
export function rowsOf(body, at) {
|
|
81
|
+
const list = at.rows === undefined ? body : body?.[at.rows];
|
|
82
|
+
if (!Array.isArray(list) || !list.every((row) => keyOf(row, at.key) !== undefined))
|
|
83
|
+
return null;
|
|
84
|
+
if (at.rows === undefined)
|
|
85
|
+
return { rows: list, rest: undefined };
|
|
86
|
+
const { [at.rows]: _rows, ...rest } = body;
|
|
87
|
+
return { rows: list, rest };
|
|
88
|
+
}
|
|
89
|
+
function keyOf(row, key) {
|
|
90
|
+
const value = row?.[key];
|
|
91
|
+
return typeof value === 'string' || typeof value === 'number' ? value : undefined;
|
|
92
|
+
}
|
|
93
|
+
export function diffRows(before, after, key) {
|
|
94
|
+
const old = new Map(before.map((row) => [keyOf(row, key), stableJson(row)]));
|
|
95
|
+
const keys = after.map((row) => keyOf(row, key));
|
|
96
|
+
const kept = new Set(keys);
|
|
97
|
+
const upsert = after.filter((row) => old.get(keyOf(row, key)) !== stableJson(row));
|
|
98
|
+
const remove = [...old.keys()].filter((k) => !kept.has(k));
|
|
99
|
+
const patched = applyPatch(before, { upsert, remove }, key);
|
|
100
|
+
const sameOrder = patched.length === keys.length && patched.every((row, i) => keyOf(row, key) === keys[i]);
|
|
101
|
+
return sameOrder ? { upsert, remove } : { upsert, remove, order: keys };
|
|
102
|
+
}
|
|
103
|
+
export function applyPatch(rows, patch, key) {
|
|
104
|
+
const gone = new Set(patch.remove);
|
|
105
|
+
const changed = new Map(patch.upsert.map((row) => [keyOf(row, key), row]));
|
|
106
|
+
const next = [];
|
|
107
|
+
for (const row of rows) {
|
|
108
|
+
const k = keyOf(row, key);
|
|
109
|
+
if (gone.has(k))
|
|
110
|
+
continue;
|
|
111
|
+
next.push(changed.get(k) ?? row);
|
|
112
|
+
changed.delete(k);
|
|
113
|
+
}
|
|
114
|
+
next.push(...changed.values());
|
|
115
|
+
if (patch.order === undefined)
|
|
116
|
+
return next;
|
|
117
|
+
const byKey = new Map(next.map((row) => [keyOf(row, key), row]));
|
|
118
|
+
return patch.order.flatMap((k) => {
|
|
119
|
+
const row = byKey.get(k);
|
|
120
|
+
return row === undefined ? [] : [row];
|
|
121
|
+
});
|
|
122
|
+
}
|
package/dist/source.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** What a source's connection is doing, for `/live/health`. */
|
|
2
|
+
export type SourceStatus = 'connecting' | 'connected' | 'reconnecting';
|
|
3
|
+
export interface ChangeSource {
|
|
4
|
+
/** Start hearing changes; returns how to stop. Called once per `createLive`. */
|
|
5
|
+
listen: (onChange: (topics: string[]) => void, onReset: () => void) => () => void;
|
|
6
|
+
/** Raise `topics` from code, through the source's bus. */
|
|
7
|
+
emit: (topics: readonly string[]) => Promise<void>;
|
|
8
|
+
status: () => SourceStatus;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* One process, no bus: `emit` calls the listeners. For tests, and for an app whose changes all
|
|
12
|
+
* come from its own code in one process.
|
|
13
|
+
*/
|
|
14
|
+
export declare function memorySource(): ChangeSource & {
|
|
15
|
+
/** Say that changes may have been missed, as a dropped connection would. */
|
|
16
|
+
reset: () => void;
|
|
17
|
+
};
|
package/dist/source.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export function memorySource() {
|
|
2
|
+
const changes = new Set();
|
|
3
|
+
const resets = new Set();
|
|
4
|
+
return {
|
|
5
|
+
listen(onChange, onReset) {
|
|
6
|
+
changes.add(onChange);
|
|
7
|
+
resets.add(onReset);
|
|
8
|
+
return () => {
|
|
9
|
+
changes.delete(onChange);
|
|
10
|
+
resets.delete(onReset);
|
|
11
|
+
};
|
|
12
|
+
},
|
|
13
|
+
emit(topics) {
|
|
14
|
+
for (const listener of [...changes])
|
|
15
|
+
listener([...topics]);
|
|
16
|
+
return Promise.resolve();
|
|
17
|
+
},
|
|
18
|
+
status: () => 'connected',
|
|
19
|
+
reset() {
|
|
20
|
+
for (const listener of [...resets])
|
|
21
|
+
listener();
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
package/dist/topics.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** The longest topic kept; a longer one is dropped where it is raised. */
|
|
2
|
+
export declare const MAX_TOPIC_LENGTH = 200;
|
|
3
|
+
/** Every insert, update or delete in `table`. */
|
|
4
|
+
export declare const tableTopic: (table: string) => string;
|
|
5
|
+
/** A change to one row of `table`; a composite key is its parts joined by `,`. */
|
|
6
|
+
export declare const rowTopic: (table: string, key: unknown) => string;
|
|
7
|
+
/** A change to a row of `table` whose `column` held `value` before or after. */
|
|
8
|
+
export declare const scopeTopic: (table: string, column: string, value: unknown) => string;
|
|
9
|
+
/** The topics worth keeping: strings, not empty, at most `MAX_TOPIC_LENGTH`, each once. */
|
|
10
|
+
export declare function cleanTopics(topics: readonly unknown[]): string[];
|
package/dist/topics.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export const MAX_TOPIC_LENGTH = 200;
|
|
2
|
+
export const tableTopic = (table) => table;
|
|
3
|
+
export const rowTopic = (table, key) => `${table}:${Array.isArray(key) ? key.map(cell).join(',') : cell(key)}`;
|
|
4
|
+
export const scopeTopic = (table, column, value) => `${table}@${column}=${cell(value)}`;
|
|
5
|
+
function cell(value) {
|
|
6
|
+
if (value === null || value === undefined)
|
|
7
|
+
return '';
|
|
8
|
+
if (value instanceof Date)
|
|
9
|
+
return value.toISOString();
|
|
10
|
+
if (typeof value === 'string')
|
|
11
|
+
return value;
|
|
12
|
+
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
|
|
13
|
+
return String(value);
|
|
14
|
+
}
|
|
15
|
+
return JSON.stringify(value);
|
|
16
|
+
}
|
|
17
|
+
export function cleanTopics(topics) {
|
|
18
|
+
const kept = new Set();
|
|
19
|
+
for (const topic of topics) {
|
|
20
|
+
if (typeof topic === 'string' && topic !== '' && topic.length <= MAX_TOPIC_LENGTH) {
|
|
21
|
+
kept.add(topic);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return [...kept];
|
|
25
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,88 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@20baht/live",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"engines": {
|
|
6
|
+
"node": ">=20.19.0"
|
|
7
|
+
},
|
|
8
|
+
"description": "Server-authoritative live queries for Elysia over server-sent events: a route marked live runs again when the data under it changes (Postgres triggers, or the server's own code) and every viewer gets the new answer, as a snapshot or a keyed patch. Optimistic edits in the browser settle against it.",
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"author": "Nattapong Promthong",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/bank20baht/20baht.git",
|
|
14
|
+
"directory": "packages/core/live"
|
|
15
|
+
},
|
|
16
|
+
"homepage": "https://github.com/bank20baht/20baht/tree/main/packages/core/live#readme",
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/bank20baht/20baht/issues"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"live-query",
|
|
22
|
+
"realtime",
|
|
23
|
+
"sse",
|
|
24
|
+
"server-sent-events",
|
|
25
|
+
"elysia",
|
|
26
|
+
"postgres",
|
|
27
|
+
"listen-notify",
|
|
28
|
+
"drizzle",
|
|
29
|
+
"optimistic-update"
|
|
30
|
+
],
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"dist"
|
|
36
|
+
],
|
|
37
|
+
"exports": {
|
|
38
|
+
".": {
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"import": "./dist/index.js",
|
|
41
|
+
"default": "./dist/index.js"
|
|
42
|
+
},
|
|
43
|
+
"./elysia": {
|
|
44
|
+
"types": "./dist/elysia.d.ts",
|
|
45
|
+
"import": "./dist/elysia.js",
|
|
46
|
+
"default": "./dist/elysia.js"
|
|
47
|
+
},
|
|
48
|
+
"./pg": {
|
|
49
|
+
"types": "./dist/pg.d.ts",
|
|
50
|
+
"import": "./dist/pg.js",
|
|
51
|
+
"default": "./dist/pg.js"
|
|
52
|
+
},
|
|
53
|
+
"./browser": {
|
|
54
|
+
"types": "./dist/browser.d.ts",
|
|
55
|
+
"import": "./dist/browser.js",
|
|
56
|
+
"default": "./dist/browser.js"
|
|
57
|
+
},
|
|
58
|
+
"./package.json": "./package.json"
|
|
59
|
+
},
|
|
60
|
+
"scripts": {
|
|
61
|
+
"build": "rm -rf dist && tsc -p tsconfig.json --removeComments && tsc -p tsconfig.json --emitDeclarationOnly",
|
|
62
|
+
"test": "vitest run",
|
|
63
|
+
"test:watch": "vitest",
|
|
64
|
+
"test:coverage": "vitest run --coverage"
|
|
65
|
+
},
|
|
66
|
+
"devDependencies": {
|
|
67
|
+
"@electric-sql/pglite": "^0.3.0",
|
|
68
|
+
"drizzle-orm": "^0.44.0",
|
|
69
|
+
"elysia": "^1.4.0",
|
|
70
|
+
"typescript": "^5.9.3",
|
|
71
|
+
"vitest": "^3.2.4"
|
|
72
|
+
},
|
|
73
|
+
"peerDependencies": {
|
|
74
|
+
"drizzle-orm": ">=0.44.0 <1.0.0",
|
|
75
|
+
"elysia": ">=1.4.0 <2.0.0"
|
|
76
|
+
},
|
|
77
|
+
"peerDependenciesMeta": {
|
|
78
|
+
"drizzle-orm": {
|
|
79
|
+
"optional": true
|
|
80
|
+
},
|
|
81
|
+
"elysia": {
|
|
82
|
+
"optional": true
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
"main": "./dist/index.js",
|
|
86
|
+
"types": "./dist/index.d.ts",
|
|
87
|
+
"sideEffects": false
|
|
88
|
+
}
|