@20baht/live 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +142 -2
- package/dist/browser.d.ts +164 -0
- package/dist/browser.js +404 -0
- package/dist/elysia.d.ts +332 -0
- package/dist/elysia.js +131 -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/elysia.d.ts
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import { Elysia } from 'elysia';
|
|
2
|
+
import type { Caller, Live, Runner } from './live.js';
|
|
3
|
+
/** What a live route's `topics` and `share` are handed when it runs for a stream. */
|
|
4
|
+
export interface LiveRouteContext<C extends Caller | null> {
|
|
5
|
+
params: Record<string, string>;
|
|
6
|
+
query: Record<string, string | undefined>;
|
|
7
|
+
body: unknown;
|
|
8
|
+
/** The stream's caller, as `createLive`'s `caller` port said (null without one). */
|
|
9
|
+
caller: C;
|
|
10
|
+
}
|
|
11
|
+
/** The `live` route option. */
|
|
12
|
+
export interface LiveRoute<C extends Caller | null> {
|
|
13
|
+
/** The topics the answer depends on, worked out on the server from the request and its caller. */
|
|
14
|
+
topics: (context: LiveRouteContext<C>) => readonly string[];
|
|
15
|
+
/** The row key: frames after the first become patches of the rows that changed. */
|
|
16
|
+
key?: string | undefined;
|
|
17
|
+
/** The answer's key holding the rows, when the answer is not itself the list (`'rows'`). */
|
|
18
|
+
rows?: string | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* Share one run across callers: the same request with the same share key is run once, with
|
|
21
|
+
* one caller's credentials, and its answer goes to all of them. Only for an answer that is the
|
|
22
|
+
* same for everyone with that key (spec 09 §5).
|
|
23
|
+
*/
|
|
24
|
+
share?: ((context: LiveRouteContext<C>) => string) | undefined;
|
|
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>;
|
|
38
|
+
type HookList = {
|
|
39
|
+
fn?: unknown;
|
|
40
|
+
}[] | {
|
|
41
|
+
fn?: unknown;
|
|
42
|
+
} | undefined;
|
|
43
|
+
interface RouteLike {
|
|
44
|
+
method: string;
|
|
45
|
+
path: string;
|
|
46
|
+
hooks?: {
|
|
47
|
+
beforeHandle?: HookList;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
interface AppLike {
|
|
51
|
+
handle: (request: Request) => Promise<Response>;
|
|
52
|
+
routes: readonly RouteLike[];
|
|
53
|
+
}
|
|
54
|
+
export interface LivePluginOptions<Path extends string = '/live'> {
|
|
55
|
+
/** Where the stream is served. Default `/live`; health is `<path>/health`. */
|
|
56
|
+
path?: Path | undefined;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
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.
|
|
106
|
+
*
|
|
107
|
+
* const app = new Elysia()
|
|
108
|
+
* .use(livePlugin(live))
|
|
109
|
+
* .use(issues(live))
|
|
110
|
+
* bindLive(live, app)
|
|
111
|
+
*/
|
|
112
|
+
export declare function livePlugin<C extends Caller | null, Path extends string = '/live'>(live: Live<C>, options?: LivePluginOptions<Path>): Elysia<"", {
|
|
113
|
+
decorator: {};
|
|
114
|
+
store: {};
|
|
115
|
+
derive: {};
|
|
116
|
+
resolve: {};
|
|
117
|
+
}, {
|
|
118
|
+
typebox: {};
|
|
119
|
+
error: {};
|
|
120
|
+
}, {
|
|
121
|
+
schema: {};
|
|
122
|
+
standaloneSchema: {};
|
|
123
|
+
macro: {};
|
|
124
|
+
macroFn: {};
|
|
125
|
+
parser: {};
|
|
126
|
+
response: {};
|
|
127
|
+
} & {
|
|
128
|
+
schema: {};
|
|
129
|
+
standaloneSchema: {};
|
|
130
|
+
macro: Partial<{
|
|
131
|
+
readonly live: LiveRoute<C>;
|
|
132
|
+
}>;
|
|
133
|
+
macroFn: {
|
|
134
|
+
readonly live: (route: LiveRoute<C>) => {
|
|
135
|
+
readonly beforeHandle: ({ request, ...rest }: {
|
|
136
|
+
request: Request;
|
|
137
|
+
}) => void;
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
parser: {};
|
|
141
|
+
response: {};
|
|
142
|
+
}, {} & import("elysia").CreateEden<import("elysia/types").JoinPath<"", Path>, {
|
|
143
|
+
post: {
|
|
144
|
+
body: {};
|
|
145
|
+
params: import("elysia/types").IsNever<keyof import("elysia/types").IntersectIfObject<import("elysia").ResolvePath<import("elysia/types").JoinPath<"", Path>>, unknown>> extends true ? import("elysia").ResolvePath<Path> : import("elysia/types").IntersectIfObject<import("elysia").ResolvePath<import("elysia/types").JoinPath<"", Path>>, unknown> extends infer T ? { [K in keyof T]: T[K]; } : never;
|
|
146
|
+
query: {};
|
|
147
|
+
headers: {};
|
|
148
|
+
response: import("elysia").ComposeElysiaResponse<import("elysia/types").IntersectIfObjectSchema<import("elysia").UnwrapRoute<Partial<{
|
|
149
|
+
readonly live: LiveRoute<C>;
|
|
150
|
+
}> & import("elysia").InputSchema<never>, {}, import("elysia/types").JoinPath<"", Path>>, {}> & {
|
|
151
|
+
return: unknown;
|
|
152
|
+
}, ({ request, body }: {
|
|
153
|
+
body: unknown;
|
|
154
|
+
query: Record<string, string>;
|
|
155
|
+
params: undefined extends import("elysia/types").IntersectIfObject<import("elysia").ResolvePath<import("elysia/types").JoinPath<"", Path>>, unknown> ? Record<string, string> : import("elysia/types").IntersectIfObject<import("elysia").ResolvePath<import("elysia/types").JoinPath<"", Path>>, unknown> extends infer T_2 ? T_2 extends import("elysia/types").IntersectIfObject<import("elysia").ResolvePath<import("elysia/types").JoinPath<"", Path>>, unknown> ? T_2 extends object ? { [K_2 in keyof T_2]: T_2[K_2]; } : T_2 : never : never;
|
|
156
|
+
headers: Record<string, string | undefined>;
|
|
157
|
+
cookie: Record<string, import("elysia").Cookie<unknown>>;
|
|
158
|
+
server: import("elysia/universal/server").Server | null;
|
|
159
|
+
redirect: import("elysia").redirect;
|
|
160
|
+
set: {
|
|
161
|
+
headers: import("elysia").HTTPHeaders;
|
|
162
|
+
status?: number | keyof import("elysia").StatusMap;
|
|
163
|
+
redirect?: string;
|
|
164
|
+
cookie?: Record<string, import("elysia/cookies").ElysiaCookie>;
|
|
165
|
+
};
|
|
166
|
+
path: string;
|
|
167
|
+
route: string;
|
|
168
|
+
request: Request;
|
|
169
|
+
store: {};
|
|
170
|
+
status: <const Code extends number | keyof import("elysia").StatusMap, const T_3 = Code extends 401 | 200 | 100 | 500 | 403 | 300 | 404 | 503 | 400 | 101 | 102 | 103 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 301 | 302 | 303 | 304 | 307 | 308 | 402 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 501 | 502 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ? {
|
|
171
|
+
readonly 100: "Continue";
|
|
172
|
+
readonly 101: "Switching Protocols";
|
|
173
|
+
readonly 102: "Processing";
|
|
174
|
+
readonly 103: "Early Hints";
|
|
175
|
+
readonly 200: "OK";
|
|
176
|
+
readonly 201: "Created";
|
|
177
|
+
readonly 202: "Accepted";
|
|
178
|
+
readonly 203: "Non-Authoritative Information";
|
|
179
|
+
readonly 204: "No Content";
|
|
180
|
+
readonly 205: "Reset Content";
|
|
181
|
+
readonly 206: "Partial Content";
|
|
182
|
+
readonly 207: "Multi-Status";
|
|
183
|
+
readonly 208: "Already Reported";
|
|
184
|
+
readonly 300: "Multiple Choices";
|
|
185
|
+
readonly 301: "Moved Permanently";
|
|
186
|
+
readonly 302: "Found";
|
|
187
|
+
readonly 303: "See Other";
|
|
188
|
+
readonly 304: "Not Modified";
|
|
189
|
+
readonly 307: "Temporary Redirect";
|
|
190
|
+
readonly 308: "Permanent Redirect";
|
|
191
|
+
readonly 400: "Bad Request";
|
|
192
|
+
readonly 401: "Unauthorized";
|
|
193
|
+
readonly 402: "Payment Required";
|
|
194
|
+
readonly 403: "Forbidden";
|
|
195
|
+
readonly 404: "Not Found";
|
|
196
|
+
readonly 405: "Method Not Allowed";
|
|
197
|
+
readonly 406: "Not Acceptable";
|
|
198
|
+
readonly 407: "Proxy Authentication Required";
|
|
199
|
+
readonly 408: "Request Timeout";
|
|
200
|
+
readonly 409: "Conflict";
|
|
201
|
+
readonly 410: "Gone";
|
|
202
|
+
readonly 411: "Length Required";
|
|
203
|
+
readonly 412: "Precondition Failed";
|
|
204
|
+
readonly 413: "Payload Too Large";
|
|
205
|
+
readonly 414: "URI Too Long";
|
|
206
|
+
readonly 415: "Unsupported Media Type";
|
|
207
|
+
readonly 416: "Range Not Satisfiable";
|
|
208
|
+
readonly 417: "Expectation Failed";
|
|
209
|
+
readonly 418: "I'm a teapot";
|
|
210
|
+
readonly 420: "Enhance Your Calm";
|
|
211
|
+
readonly 421: "Misdirected Request";
|
|
212
|
+
readonly 422: "Unprocessable Content";
|
|
213
|
+
readonly 423: "Locked";
|
|
214
|
+
readonly 424: "Failed Dependency";
|
|
215
|
+
readonly 425: "Too Early";
|
|
216
|
+
readonly 426: "Upgrade Required";
|
|
217
|
+
readonly 428: "Precondition Required";
|
|
218
|
+
readonly 429: "Too Many Requests";
|
|
219
|
+
readonly 431: "Request Header Fields Too Large";
|
|
220
|
+
readonly 451: "Unavailable For Legal Reasons";
|
|
221
|
+
readonly 500: "Internal Server Error";
|
|
222
|
+
readonly 501: "Not Implemented";
|
|
223
|
+
readonly 502: "Bad Gateway";
|
|
224
|
+
readonly 503: "Service Unavailable";
|
|
225
|
+
readonly 504: "Gateway Timeout";
|
|
226
|
+
readonly 505: "HTTP Version Not Supported";
|
|
227
|
+
readonly 506: "Variant Also Negotiates";
|
|
228
|
+
readonly 507: "Insufficient Storage";
|
|
229
|
+
readonly 508: "Loop Detected";
|
|
230
|
+
readonly 510: "Not Extended";
|
|
231
|
+
readonly 511: "Network Authentication Required";
|
|
232
|
+
}[Code] : Code>(code: Code, response?: T_3) => import("elysia").ElysiaCustomStatusResponse<Code, T_3, Code extends "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Enhance Your Calm" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required" ? {
|
|
233
|
+
readonly Continue: 100;
|
|
234
|
+
readonly "Switching Protocols": 101;
|
|
235
|
+
readonly Processing: 102;
|
|
236
|
+
readonly "Early Hints": 103;
|
|
237
|
+
readonly OK: 200;
|
|
238
|
+
readonly Created: 201;
|
|
239
|
+
readonly Accepted: 202;
|
|
240
|
+
readonly "Non-Authoritative Information": 203;
|
|
241
|
+
readonly "No Content": 204;
|
|
242
|
+
readonly "Reset Content": 205;
|
|
243
|
+
readonly "Partial Content": 206;
|
|
244
|
+
readonly "Multi-Status": 207;
|
|
245
|
+
readonly "Already Reported": 208;
|
|
246
|
+
readonly "Multiple Choices": 300;
|
|
247
|
+
readonly "Moved Permanently": 301;
|
|
248
|
+
readonly Found: 302;
|
|
249
|
+
readonly "See Other": 303;
|
|
250
|
+
readonly "Not Modified": 304;
|
|
251
|
+
readonly "Temporary Redirect": 307;
|
|
252
|
+
readonly "Permanent Redirect": 308;
|
|
253
|
+
readonly "Bad Request": 400;
|
|
254
|
+
readonly Unauthorized: 401;
|
|
255
|
+
readonly "Payment Required": 402;
|
|
256
|
+
readonly Forbidden: 403;
|
|
257
|
+
readonly "Not Found": 404;
|
|
258
|
+
readonly "Method Not Allowed": 405;
|
|
259
|
+
readonly "Not Acceptable": 406;
|
|
260
|
+
readonly "Proxy Authentication Required": 407;
|
|
261
|
+
readonly "Request Timeout": 408;
|
|
262
|
+
readonly Conflict: 409;
|
|
263
|
+
readonly Gone: 410;
|
|
264
|
+
readonly "Length Required": 411;
|
|
265
|
+
readonly "Precondition Failed": 412;
|
|
266
|
+
readonly "Payload Too Large": 413;
|
|
267
|
+
readonly "URI Too Long": 414;
|
|
268
|
+
readonly "Unsupported Media Type": 415;
|
|
269
|
+
readonly "Range Not Satisfiable": 416;
|
|
270
|
+
readonly "Expectation Failed": 417;
|
|
271
|
+
readonly "I'm a teapot": 418;
|
|
272
|
+
readonly "Enhance Your Calm": 420;
|
|
273
|
+
readonly "Misdirected Request": 421;
|
|
274
|
+
readonly "Unprocessable Content": 422;
|
|
275
|
+
readonly Locked: 423;
|
|
276
|
+
readonly "Failed Dependency": 424;
|
|
277
|
+
readonly "Too Early": 425;
|
|
278
|
+
readonly "Upgrade Required": 426;
|
|
279
|
+
readonly "Precondition Required": 428;
|
|
280
|
+
readonly "Too Many Requests": 429;
|
|
281
|
+
readonly "Request Header Fields Too Large": 431;
|
|
282
|
+
readonly "Unavailable For Legal Reasons": 451;
|
|
283
|
+
readonly "Internal Server Error": 500;
|
|
284
|
+
readonly "Not Implemented": 501;
|
|
285
|
+
readonly "Bad Gateway": 502;
|
|
286
|
+
readonly "Service Unavailable": 503;
|
|
287
|
+
readonly "Gateway Timeout": 504;
|
|
288
|
+
readonly "HTTP Version Not Supported": 505;
|
|
289
|
+
readonly "Variant Also Negotiates": 506;
|
|
290
|
+
readonly "Insufficient Storage": 507;
|
|
291
|
+
readonly "Loop Detected": 508;
|
|
292
|
+
readonly "Not Extended": 510;
|
|
293
|
+
readonly "Network Authentication Required": 511;
|
|
294
|
+
}[Code] : Code>;
|
|
295
|
+
}) => Response | Promise<Response>, {}> extends infer T_1 ? { [K_1 in keyof T_1]: T_1[K_1]; } : never;
|
|
296
|
+
};
|
|
297
|
+
}> & import("elysia").CreateEden<import("elysia/types").JoinPath<"", `${Path}/health`>, {
|
|
298
|
+
get: {
|
|
299
|
+
body: {};
|
|
300
|
+
params: import("elysia/types").IsNever<keyof import("elysia/types").IntersectIfObject<import("elysia").ResolvePath<import("elysia/types").JoinPath<"", `${Path}/health`>>, unknown>> extends true ? import("elysia").ResolvePath<`${Path}/health`> : import("elysia/types").IntersectIfObject<import("elysia").ResolvePath<import("elysia/types").JoinPath<"", `${Path}/health`>>, unknown> extends infer T_2 ? { [K_2 in keyof T_2]: T_2[K_2]; } : never;
|
|
301
|
+
query: {};
|
|
302
|
+
headers: {};
|
|
303
|
+
response: import("elysia").ComposeElysiaResponse<import("elysia/types").IntersectIfObjectSchema<import("elysia").UnwrapRoute<Partial<{
|
|
304
|
+
readonly live: LiveRoute<C>;
|
|
305
|
+
}> & import("elysia").InputSchema<never>, {}, import("elysia/types").JoinPath<"", `${Path}/health`>>, {}> & {
|
|
306
|
+
return: unknown;
|
|
307
|
+
}, () => import("./live.js").LiveHealth, {}> extends infer T_3 ? { [K_3 in keyof T_3]: T_3[K_3]; } : never;
|
|
308
|
+
};
|
|
309
|
+
}>, {
|
|
310
|
+
derive: {};
|
|
311
|
+
resolve: {};
|
|
312
|
+
schema: {};
|
|
313
|
+
standaloneSchema: {};
|
|
314
|
+
response: {};
|
|
315
|
+
}, {
|
|
316
|
+
derive: {};
|
|
317
|
+
resolve: {};
|
|
318
|
+
schema: {};
|
|
319
|
+
standaloneSchema: {};
|
|
320
|
+
response: {};
|
|
321
|
+
} & {
|
|
322
|
+
derive: {};
|
|
323
|
+
resolve: {};
|
|
324
|
+
schema: {};
|
|
325
|
+
standaloneSchema: {};
|
|
326
|
+
response: {};
|
|
327
|
+
}>;
|
|
328
|
+
/** Tell the hub which app its live routes are in. Call it once the app is built. */
|
|
329
|
+
export declare function bindLive<C extends Caller | null>(live: Live<C>, app: AppLike): void;
|
|
330
|
+
/** Runs a route through `app.handle`, refusing any not marked live by this hub. */
|
|
331
|
+
export declare function appRunner(app: AppLike, marks: WeakSet<object>): Runner;
|
|
332
|
+
export {};
|
package/dist/elysia.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { Elysia } from 'elysia';
|
|
2
|
+
import { requestTarget } from './protocol.js';
|
|
3
|
+
export function liveRoute(_live, route) {
|
|
4
|
+
return route;
|
|
5
|
+
}
|
|
6
|
+
const apps = new WeakMap();
|
|
7
|
+
export function liveMacro(live) {
|
|
8
|
+
const marks = marksOf(live);
|
|
9
|
+
return new Elysia({ name: '@20baht/live/macro', seed: live }).macro({
|
|
10
|
+
live: (route) => {
|
|
11
|
+
const beforeHandle = ({ request, ...rest }) => {
|
|
12
|
+
const run = runs.get(request);
|
|
13
|
+
if (run === undefined)
|
|
14
|
+
return;
|
|
15
|
+
const context = rest;
|
|
16
|
+
const handed = {
|
|
17
|
+
params: (context.params ?? {}),
|
|
18
|
+
query: (context.query ?? {}),
|
|
19
|
+
body: context.body,
|
|
20
|
+
caller: run.caller,
|
|
21
|
+
};
|
|
22
|
+
run.answer = {
|
|
23
|
+
topics: [...route.topics(handed)],
|
|
24
|
+
key: route.key,
|
|
25
|
+
rows: route.rows,
|
|
26
|
+
share: route.share?.(handed),
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
marks.add(beforeHandle);
|
|
30
|
+
return { beforeHandle };
|
|
31
|
+
},
|
|
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 } }));
|
|
40
|
+
}
|
|
41
|
+
const runs = new WeakMap();
|
|
42
|
+
const allMarks = new WeakMap();
|
|
43
|
+
function marksOf(live) {
|
|
44
|
+
const found = allMarks.get(live) ?? new WeakSet();
|
|
45
|
+
allMarks.set(live, found);
|
|
46
|
+
return found;
|
|
47
|
+
}
|
|
48
|
+
export function bindLive(live, app) {
|
|
49
|
+
apps.set(live, app);
|
|
50
|
+
}
|
|
51
|
+
function open(live, request, body) {
|
|
52
|
+
const app = apps.get(live);
|
|
53
|
+
if (app === undefined) {
|
|
54
|
+
return new Response(JSON.stringify({ code: 'LIVE_UNBOUND', message: 'bindLive(live, app) was not called' }), { status: 500, headers: { 'content-type': 'application/json' } });
|
|
55
|
+
}
|
|
56
|
+
return live.open(request, body, appRunner(app, marksOf(live)));
|
|
57
|
+
}
|
|
58
|
+
export function appRunner(app, marks) {
|
|
59
|
+
let known;
|
|
60
|
+
const liveRoutes = () => {
|
|
61
|
+
if (known?.count !== app.routes.length) {
|
|
62
|
+
known = {
|
|
63
|
+
count: app.routes.length,
|
|
64
|
+
routes: app.routes
|
|
65
|
+
.filter((route) => hooksOf(route).some((fn) => typeof fn === 'function' && marks.has(fn)))
|
|
66
|
+
.map((route) => ({ method: route.method, segments: segmentsOf(route.path) })),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
return known.routes;
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
isLive: (request) => {
|
|
73
|
+
const segments = segmentsOf(request.path);
|
|
74
|
+
return liveRoutes().some((route) => route.method === request.method && matches(route.segments, segments));
|
|
75
|
+
},
|
|
76
|
+
run: async (request, headers, caller) => {
|
|
77
|
+
const made = toRequest(request, headers);
|
|
78
|
+
const run = { caller };
|
|
79
|
+
runs.set(made, run);
|
|
80
|
+
const response = await app.handle(made);
|
|
81
|
+
return { status: response.status, body: await bodyOf(response), live: run.answer };
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
function hooksOf(route) {
|
|
86
|
+
const list = route.hooks?.beforeHandle;
|
|
87
|
+
if (list === undefined)
|
|
88
|
+
return [];
|
|
89
|
+
return (Array.isArray(list) ? list : [list]).map((hook) => hook.fn);
|
|
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
|
+
}
|
|
97
|
+
function matches(pattern, segments) {
|
|
98
|
+
for (const [index, part] of pattern.entries()) {
|
|
99
|
+
if (part === '*')
|
|
100
|
+
return true;
|
|
101
|
+
const segment = segments[index];
|
|
102
|
+
const param = part.startsWith(':');
|
|
103
|
+
if (param && part.endsWith('?') && segment === undefined)
|
|
104
|
+
continue;
|
|
105
|
+
if (segment === undefined)
|
|
106
|
+
return false;
|
|
107
|
+
if (param ? segment === '' : part !== segment)
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
return segments.length <= pattern.length;
|
|
111
|
+
}
|
|
112
|
+
function toRequest(request, headers) {
|
|
113
|
+
const sent = new Headers(headers);
|
|
114
|
+
const init = { method: request.method, headers: sent };
|
|
115
|
+
if (request.method === 'POST') {
|
|
116
|
+
sent.set('content-type', 'application/json');
|
|
117
|
+
init.body = JSON.stringify(request.body ?? null);
|
|
118
|
+
}
|
|
119
|
+
return new Request(`http://localhost${requestTarget(request)}`, init);
|
|
120
|
+
}
|
|
121
|
+
async function bodyOf(response) {
|
|
122
|
+
const text = await response.text();
|
|
123
|
+
if (!(response.headers.get('content-type') ?? '').includes('json'))
|
|
124
|
+
return text;
|
|
125
|
+
try {
|
|
126
|
+
return JSON.parse(text);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return text;
|
|
130
|
+
}
|
|
131
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createLive, type Caller, type Live, type LiveAnswer, type LiveHealth, type LiveOptions, type Runner, type RunResult, } from './live.js';
|
|
2
|
+
export { memorySource, type ChangeSource, type SourceStatus } from './source.js';
|
|
3
|
+
export { cleanTopics, MAX_TOPIC_LENGTH, rowTopic, scopeTopic, tableTopic } from './topics.js';
|
|
4
|
+
export { applyPatch, diffRows, encodeFrame, MAX_SUBSCRIPTIONS, parseSubscriptions, requestKey, requestTarget, rowsOf, stableJson, versionOf, type EndReason, type Frame, type LiveMethod, type LiveRequest, type RowKey, type RowsAt, type Subscription, } from './protocol.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createLive, } from './live.js';
|
|
2
|
+
export { memorySource } from './source.js';
|
|
3
|
+
export { cleanTopics, MAX_TOPIC_LENGTH, rowTopic, scopeTopic, tableTopic } from './topics.js';
|
|
4
|
+
export { applyPatch, diffRows, encodeFrame, MAX_SUBSCRIPTIONS, parseSubscriptions, requestKey, requestTarget, rowsOf, stableJson, versionOf, } from './protocol.js';
|
package/dist/live.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { type LiveRequest } from './protocol.js';
|
|
2
|
+
import type { ChangeSource, SourceStatus } from './source.js';
|
|
3
|
+
/** Who a stream is for, as the host's `caller` port says. Only `id` is read here. */
|
|
4
|
+
export interface Caller {
|
|
5
|
+
id: string;
|
|
6
|
+
}
|
|
7
|
+
/** What a live route said about itself when it ran (its `live` option, worked out). */
|
|
8
|
+
export interface LiveAnswer {
|
|
9
|
+
topics: string[];
|
|
10
|
+
/** The row key, for patches. */
|
|
11
|
+
key?: string | undefined;
|
|
12
|
+
/** The answer's key holding the rows, when the answer is not itself the list. */
|
|
13
|
+
rows?: string | undefined;
|
|
14
|
+
/** Runs with the same request and share key are shared across callers. */
|
|
15
|
+
share?: string | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** One run of a route: its status, its body, and what it said as a live route. */
|
|
18
|
+
export interface RunResult {
|
|
19
|
+
status: number;
|
|
20
|
+
body: unknown;
|
|
21
|
+
live?: LiveAnswer | undefined;
|
|
22
|
+
}
|
|
23
|
+
/** How a route is found and run: through Elysia's `app.handle`, or a fetch. */
|
|
24
|
+
export interface Runner<C extends Caller | null = Caller | null> {
|
|
25
|
+
/** Whether the request names a route marked `live`; others are never run. */
|
|
26
|
+
isLive: (request: LiveRequest) => boolean;
|
|
27
|
+
/** Run it with the stream's credentials (`headers`) on behalf of its caller. */
|
|
28
|
+
run: (request: LiveRequest, headers: Headers, caller: C) => Promise<RunResult>;
|
|
29
|
+
}
|
|
30
|
+
export interface LiveOptions<C extends Caller = Caller> {
|
|
31
|
+
source: ChangeSource;
|
|
32
|
+
/**
|
|
33
|
+
* Who the request's headers stand for, or null for nobody; throws when nobody can say. Asked
|
|
34
|
+
* when a stream opens and every `recheckMs`. Without it, a stream is whoever its credentials
|
|
35
|
+
* are, and only a run answering 401 ends it.
|
|
36
|
+
*/
|
|
37
|
+
caller?: ((headers: Headers) => Promise<C | null>) | undefined;
|
|
38
|
+
/** The stream request's headers a run carries. Default `cookie` and `authorization`. */
|
|
39
|
+
forward?: readonly string[] | undefined;
|
|
40
|
+
/** Changes gathered before a run, in ms. Default 100. */
|
|
41
|
+
settleMs?: number | undefined;
|
|
42
|
+
/** Runs at once, at most. Default 8. */
|
|
43
|
+
concurrency?: number | undefined;
|
|
44
|
+
/** How often a stream's caller is asked again, in ms. Default 5 minutes. */
|
|
45
|
+
recheckMs?: number | undefined;
|
|
46
|
+
/** A comment line this often keeps a quiet stream open through proxies. Default 15 s. */
|
|
47
|
+
heartbeatMs?: number | undefined;
|
|
48
|
+
/** Subscriptions one stream may hold. Default 50. */
|
|
49
|
+
maxSubscriptions?: number | undefined;
|
|
50
|
+
}
|
|
51
|
+
export interface LiveHealth {
|
|
52
|
+
source: SourceStatus;
|
|
53
|
+
streams: number;
|
|
54
|
+
runs: number;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The hub of one process. `C` is the caller the `caller` port answers (null without one): what a
|
|
58
|
+
* live route's `topics` is handed.
|
|
59
|
+
*/
|
|
60
|
+
export interface Live<C extends Caller | null = Caller | null> {
|
|
61
|
+
/** `POST /live`: the stream for `body`'s subscriptions, or the 400 / 401 / 503 refusing it. */
|
|
62
|
+
open: (request: Request, body: unknown, runner: Runner<C>) => Promise<Response>;
|
|
63
|
+
/** Raise topics from code, through the source. */
|
|
64
|
+
emit: (topics: readonly string[]) => Promise<void>;
|
|
65
|
+
health: () => LiveHealth;
|
|
66
|
+
/** Every stream ends with `end { reason: 'shutdown' }` and the source stops. */
|
|
67
|
+
close: () => void;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The live query hub of one process. Make it once at the root and hand it to every module:
|
|
71
|
+
*
|
|
72
|
+
* const live = createLive({ source: pgSource(listener), caller })
|
|
73
|
+
* const app = new Elysia().use(livePlugin(live)).use(issues(live))
|
|
74
|
+
* live.attach(app) // through `/elysia`
|
|
75
|
+
*/
|
|
76
|
+
export declare function createLive<C extends Caller>(options: LiveOptions<C> & {
|
|
77
|
+
caller: NonNullable<LiveOptions<C>['caller']>;
|
|
78
|
+
}): Live<C>;
|
|
79
|
+
export declare function createLive(options: LiveOptions & {
|
|
80
|
+
caller?: undefined;
|
|
81
|
+
}): Live<null>;
|