@articollab/sync 0.0.0-stage → 0.12.0-beta.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 +6 -2
- package/dist/client.d.ts +107 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +568 -0
- package/dist/client.js.map +1 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +28 -0
- package/dist/errors.js.map +1 -0
- package/dist/http-client.d.ts +16 -0
- package/dist/http-client.d.ts.map +1 -0
- package/dist/http-client.js +82 -0
- package/dist/http-client.js.map +1 -0
- package/dist/http-handler.d.ts +65 -0
- package/dist/http-handler.d.ts.map +1 -0
- package/dist/http-handler.js +448 -0
- package/dist/http-handler.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/node.d.ts +31 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +62 -0
- package/dist/node.js.map +1 -0
- package/dist/postgres.d.ts +30 -0
- package/dist/postgres.d.ts.map +1 -0
- package/dist/postgres.js +155 -0
- package/dist/postgres.js.map +1 -0
- package/dist/presence.d.ts +35 -0
- package/dist/presence.d.ts.map +1 -0
- package/dist/presence.js +118 -0
- package/dist/presence.js.map +1 -0
- package/dist/server-file-store.d.ts +19 -0
- package/dist/server-file-store.d.ts.map +1 -0
- package/dist/server-file-store.js +149 -0
- package/dist/server-file-store.js.map +1 -0
- package/dist/server-store.d.ts +59 -0
- package/dist/server-store.d.ts.map +1 -0
- package/dist/server-store.js +97 -0
- package/dist/server-store.js.map +1 -0
- package/dist/socket-client.d.ts +23 -0
- package/dist/socket-client.d.ts.map +1 -0
- package/dist/socket-client.js +219 -0
- package/dist/socket-client.js.map +1 -0
- package/dist/socket-handler.d.ts +74 -0
- package/dist/socket-handler.d.ts.map +1 -0
- package/dist/socket-handler.js +183 -0
- package/dist/socket-handler.js.map +1 -0
- package/dist/sse.d.ts +13 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +61 -0
- package/dist/sse.js.map +1 -0
- package/dist/store.d.ts +79 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +193 -0
- package/dist/store.js.map +1 -0
- package/package.json +60 -3
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { type ServerCommit, type JsonValue } from "@articollab/core";
|
|
2
|
+
import type { SyncAction } from "./http-handler.ts";
|
|
3
|
+
/** The part of a server-side WebSocket that `SyncHandler.accept` uses; `ws` and Deno sockets fit as they are. */
|
|
4
|
+
export interface SyncSocket {
|
|
5
|
+
send(message: string): void;
|
|
6
|
+
close(code?: number, reason?: string): void;
|
|
7
|
+
/** Bytes queued but not yet sent, where the runtime reports it; past 4 MiB the socket is closed with 1013. */
|
|
8
|
+
readonly bufferedAmount?: number;
|
|
9
|
+
}
|
|
10
|
+
/** One socket accepted by `SyncHandler.accept`. */
|
|
11
|
+
export interface SyncConnection {
|
|
12
|
+
/** Handles one received message: text, or the same text as UTF-8 bytes. */
|
|
13
|
+
message(data: string | ArrayBuffer | ArrayBufferView): void;
|
|
14
|
+
/** The socket closed: ends its subscription and clears the presence states it sent. */
|
|
15
|
+
close(): void;
|
|
16
|
+
}
|
|
17
|
+
/** Something a subscriber receives, formatted by its transport. */
|
|
18
|
+
export type PushEvent = {
|
|
19
|
+
readonly type: "commits";
|
|
20
|
+
readonly commits: readonly ServerCommit[];
|
|
21
|
+
readonly last: number;
|
|
22
|
+
} | {
|
|
23
|
+
readonly type: "presence";
|
|
24
|
+
readonly clientId: string;
|
|
25
|
+
readonly state: JsonValue | null;
|
|
26
|
+
} | {
|
|
27
|
+
readonly type: "gap";
|
|
28
|
+
} | {
|
|
29
|
+
readonly type: "ping";
|
|
30
|
+
};
|
|
31
|
+
/** An event stream or a subscribed socket. */
|
|
32
|
+
export interface Subscriber {
|
|
33
|
+
/** The last server sequence pushed. */
|
|
34
|
+
sent: number;
|
|
35
|
+
readonly closed: boolean;
|
|
36
|
+
/** Returns false when it cannot take more; the caller then closes it. */
|
|
37
|
+
push(event: PushEvent): boolean;
|
|
38
|
+
close(): void;
|
|
39
|
+
}
|
|
40
|
+
/** A transport-neutral answer: an HTTP response, or a socket reply. */
|
|
41
|
+
export interface Reply {
|
|
42
|
+
readonly status: number;
|
|
43
|
+
readonly body?: unknown;
|
|
44
|
+
}
|
|
45
|
+
export type Allow = (action: SyncAction, clientId?: string) => Promise<boolean>;
|
|
46
|
+
export declare const failure: (status: number, message: string) => Reply;
|
|
47
|
+
/** What `createSyncHandler` shares between its HTTP routes and its sockets. */
|
|
48
|
+
export interface SyncCore {
|
|
49
|
+
readonly maxMessageSize: number;
|
|
50
|
+
readonly heartbeatInterval: number;
|
|
51
|
+
readonly maxBufferedBytes: number;
|
|
52
|
+
readonly rejections: boolean;
|
|
53
|
+
readonly presence: boolean;
|
|
54
|
+
readonly failed: boolean;
|
|
55
|
+
/** Binds `authorize` to a request. */
|
|
56
|
+
allow(request: Request): Allow;
|
|
57
|
+
register(allow: Allow): Promise<Reply>;
|
|
58
|
+
write(kind: "submit" | "reject", input: unknown, allow: Allow): Promise<Reply>;
|
|
59
|
+
catchUp(watermark: number, allow: Allow): Promise<Reply>;
|
|
60
|
+
publish(clientId: string, state: unknown, allow: Allow, owner?: object): Promise<Reply>;
|
|
61
|
+
/** Admits the subscriber `create` makes; an error reply, or undefined once it is receiving. */
|
|
62
|
+
subscribe(watermark: number, allow: Allow, create: () => Subscriber): Promise<Reply | undefined>;
|
|
63
|
+
/** Removes a closed subscriber. */
|
|
64
|
+
drop(subscriber: Subscriber): void;
|
|
65
|
+
/** Clears the presence states `owner` sent that no one has sent since. */
|
|
66
|
+
release(owner: object): void;
|
|
67
|
+
/** Tracks an open socket, failed when checkpoint storage fails; returns the untrack function. */
|
|
68
|
+
track(socket: {
|
|
69
|
+
fail(): void;
|
|
70
|
+
}): () => void;
|
|
71
|
+
}
|
|
72
|
+
/** Serves one socket with the same operations as the HTTP routes. */
|
|
73
|
+
export declare function acceptSocket(core: SyncCore, socket: SyncSocket, request: Request): SyncConnection;
|
|
74
|
+
//# sourceMappingURL=socket-handler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket-handler.d.ts","sourceRoot":"","sources":["../src/socket-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,SAAS,EACf,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,iHAAiH;AACjH,MAAM,WAAW,UAAU;IACzB,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5C,8GAA8G;IAC9G,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;CAClC;AAED,mDAAmD;AACnD,MAAM,WAAW,cAAc;IAC7B,2EAA2E;IAC3E,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,eAAe,GAAG,IAAI,CAAC;IAC5D,uFAAuF;IACvF,KAAK,IAAI,IAAI,CAAC;CACf;AAED,mEAAmE;AACnE,MAAM,MAAM,SAAS,GACjB;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9F;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,CAAA;CAAE,GAC1F;IAAE,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAA;CAAE,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AAE,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;IACzD,OAAO,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;IACxF,+FAA+F;IAC/F,SAAS,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,GAAG,OAAO,CAAC,KAAK,GAAG,SAAS,CAAC,CAAC;IACjG,mCAAmC;IACnC,IAAI,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,CAAC;IACnC,0EAA0E;IAC1E,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,iGAAiG;IACjG,KAAK,CAAC,MAAM,EAAE;QAAE,IAAI,IAAI,IAAI,CAAA;KAAE,GAAG,MAAM,IAAI,CAAC;CAC7C;AAOD,qEAAqE;AACrE,wBAAgB,YAAY,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,GAAG,cAAc,CAoIjG"}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import {} from "@articollab/core";
|
|
2
|
+
import { isJsonObject } from "@articollab/core/adapter";
|
|
3
|
+
export const failure = (status, message) => ({ status, body: { error: message } });
|
|
4
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
5
|
+
const encoder = new TextEncoder();
|
|
6
|
+
const isNonNegativeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
7
|
+
/** Serves one socket with the same operations as the HTTP routes. */
|
|
8
|
+
export function acceptSocket(core, socket, request) {
|
|
9
|
+
const allowed = core.allow(request);
|
|
10
|
+
/** Identifies this socket as the sender of presence states. */
|
|
11
|
+
const owner = {};
|
|
12
|
+
let open = true;
|
|
13
|
+
let subscriber;
|
|
14
|
+
/** Bumped by every subscribe and unsubscribe, so only the latest subscribe opens. */
|
|
15
|
+
let generation = 0;
|
|
16
|
+
function end() {
|
|
17
|
+
if (!open)
|
|
18
|
+
return;
|
|
19
|
+
open = false;
|
|
20
|
+
untrack();
|
|
21
|
+
subscriber?.close();
|
|
22
|
+
core.release(owner);
|
|
23
|
+
}
|
|
24
|
+
function shut(code, reason) {
|
|
25
|
+
if (!open)
|
|
26
|
+
return;
|
|
27
|
+
end();
|
|
28
|
+
try {
|
|
29
|
+
socket.close(code, reason);
|
|
30
|
+
}
|
|
31
|
+
catch { /* Already closing. */ }
|
|
32
|
+
}
|
|
33
|
+
function send(value) {
|
|
34
|
+
if (!open)
|
|
35
|
+
return false;
|
|
36
|
+
if ((socket.bufferedAmount ?? 0) > core.maxBufferedBytes) {
|
|
37
|
+
shut(1013, "Send queue full");
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
socket.send(JSON.stringify(value));
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
shut(1011, "Send failed");
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const untrack = core.track({ fail: () => { shut(1011, "Checkpoint storage failed"); } });
|
|
50
|
+
if (core.failed)
|
|
51
|
+
shut(1011, "Checkpoint storage failed");
|
|
52
|
+
function subscription(watermark, live) {
|
|
53
|
+
let active = live;
|
|
54
|
+
let heartbeat;
|
|
55
|
+
const created = {
|
|
56
|
+
sent: watermark,
|
|
57
|
+
get closed() { return !active; },
|
|
58
|
+
push(event) {
|
|
59
|
+
if (!active)
|
|
60
|
+
return false;
|
|
61
|
+
return send(event.type === "commits" ? { type: "commits", commits: event.commits } : event);
|
|
62
|
+
},
|
|
63
|
+
close() {
|
|
64
|
+
if (!active)
|
|
65
|
+
return;
|
|
66
|
+
active = false;
|
|
67
|
+
if (heartbeat !== undefined)
|
|
68
|
+
clearInterval(heartbeat);
|
|
69
|
+
if (subscriber === created)
|
|
70
|
+
subscriber = undefined;
|
|
71
|
+
core.drop(created);
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
if (!live)
|
|
75
|
+
return created;
|
|
76
|
+
subscriber = created;
|
|
77
|
+
if (core.heartbeatInterval > 0)
|
|
78
|
+
heartbeat = setInterval(() => { created.push({ type: "ping" }); }, core.heartbeatInterval);
|
|
79
|
+
return created;
|
|
80
|
+
}
|
|
81
|
+
async function handle(input, id) {
|
|
82
|
+
const size = Object.keys(input).length;
|
|
83
|
+
switch (input.type) {
|
|
84
|
+
case "register":
|
|
85
|
+
return size === 2 ? core.register(allowed) : failure(400, "Expected { id, type }");
|
|
86
|
+
case "submit":
|
|
87
|
+
case "reject":
|
|
88
|
+
if (input.type === "reject" && !core.rejections)
|
|
89
|
+
return failure(404, "Unknown message type");
|
|
90
|
+
return size === 3 && "batch" in input ? core.write(input.type, input.batch, allowed) : failure(400, "Expected { id, type, batch }");
|
|
91
|
+
case "commits":
|
|
92
|
+
return size === 3 && isNonNegativeInteger(input.since) ? core.catchUp(input.since, allowed) : failure(400, "Expected { id, type, since }");
|
|
93
|
+
case "subscribe": {
|
|
94
|
+
if (size !== 3 || !isNonNegativeInteger(input.since))
|
|
95
|
+
return failure(400, "Expected { id, type, since }");
|
|
96
|
+
const since = input.since;
|
|
97
|
+
const mine = ++generation;
|
|
98
|
+
subscriber?.close();
|
|
99
|
+
let opened = false;
|
|
100
|
+
const reply = await core.subscribe(since, allowed, () => {
|
|
101
|
+
const created = subscription(since, open && mine === generation);
|
|
102
|
+
// The reply goes before any push, as an event stream's headers do.
|
|
103
|
+
if (!created.closed)
|
|
104
|
+
opened = send({ id, status: 200 });
|
|
105
|
+
return created;
|
|
106
|
+
});
|
|
107
|
+
// A later subscribe or unsubscribe replaced this one before it opened.
|
|
108
|
+
return reply ?? (opened ? undefined : { status: 204 });
|
|
109
|
+
}
|
|
110
|
+
case "unsubscribe":
|
|
111
|
+
if (size !== 2)
|
|
112
|
+
return failure(400, "Expected { id, type }");
|
|
113
|
+
generation++;
|
|
114
|
+
subscriber?.close();
|
|
115
|
+
return { status: 204 };
|
|
116
|
+
case "presence": {
|
|
117
|
+
if (!core.presence)
|
|
118
|
+
return failure(404, "Unknown message type");
|
|
119
|
+
if (size !== 4 || typeof input.clientId !== "string" || !("state" in input)) {
|
|
120
|
+
return failure(400, "Expected { id, type, clientId, state }");
|
|
121
|
+
}
|
|
122
|
+
const reply = await core.publish(input.clientId, input.state, allowed, owner);
|
|
123
|
+
// The socket may have closed while authorize ran, after its states were cleared.
|
|
124
|
+
if (!open)
|
|
125
|
+
core.release(owner);
|
|
126
|
+
return reply;
|
|
127
|
+
}
|
|
128
|
+
default:
|
|
129
|
+
return failure(404, "Unknown message type");
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
message(data) {
|
|
134
|
+
if (!open)
|
|
135
|
+
return;
|
|
136
|
+
if (core.failed) {
|
|
137
|
+
shut(1011, "Checkpoint storage failed");
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const limit = core.maxMessageSize;
|
|
141
|
+
let text;
|
|
142
|
+
if (typeof data === "string") {
|
|
143
|
+
// UTF-16 length is a lower bound on UTF-8 bytes, and a third of an upper bound.
|
|
144
|
+
if (data.length > limit || (data.length * 3 > limit && encoder.encode(data).byteLength > limit)) {
|
|
145
|
+
shut(1009, "Message too large");
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
text = data;
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
const bytes = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
|
|
152
|
+
if (bytes.byteLength > limit) {
|
|
153
|
+
shut(1009, "Message too large");
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
try {
|
|
157
|
+
text = decoder.decode(bytes);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
shut(1007, "Expected UTF-8 text");
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
let input;
|
|
165
|
+
try {
|
|
166
|
+
input = JSON.parse(text);
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
shut(1008, "Expected a JSON message");
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (!isJsonObject(input) || !isNonNegativeInteger(input.id) || typeof input.type !== "string") {
|
|
173
|
+
shut(1008, "Expected { id, type }");
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const id = input.id;
|
|
177
|
+
void handle(input, id).then((reply) => { if (reply !== undefined)
|
|
178
|
+
send({ id, ...reply }); }, () => { send({ id, ...failure(500, "Internal server error") }); });
|
|
179
|
+
},
|
|
180
|
+
close: end,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
//# sourceMappingURL=socket-handler.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket-handler.js","sourceRoot":"","sources":["../src/socket-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AA4CxD,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,MAAc,EAAE,OAAe,EAAS,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC;AA0B1G,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAC1D,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAClC,MAAM,oBAAoB,GAAG,CAAC,KAAc,EAAmB,EAAE,CAC/D,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;AAEz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
package/dist/sse.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** One dispatched server-sent event. */
|
|
2
|
+
export interface ServerSentEvent {
|
|
3
|
+
readonly type: string;
|
|
4
|
+
readonly data: string;
|
|
5
|
+
readonly id: string | undefined;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Reads a `text/event-stream` body as the HTML standard defines: lines end in CRLF, LF or CR,
|
|
9
|
+
* comments start with a colon, and an event is dispatched at a blank line. A trailing event
|
|
10
|
+
* without its blank line is discarded. `onActivity` runs for every complete line, comments included.
|
|
11
|
+
*/
|
|
12
|
+
export declare function readServerSentEvents(body: ReadableStream<Uint8Array>, onEvent: (event: ServerSentEvent) => void, onActivity?: () => void): Promise<void>;
|
|
13
|
+
//# sourceMappingURL=sse.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA,wCAAwC;AACxC,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,CAAC;CACjC;AAED;;;;GAIG;AACH,wBAAsB,oBAAoB,CACxC,IAAI,EAAE,cAAc,CAAC,UAAU,CAAC,EAChC,OAAO,EAAE,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,EACzC,UAAU,GAAE,MAAM,IAAe,GAChC,OAAO,CAAC,IAAI,CAAC,CA2Cf"}
|
package/dist/sse.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reads a `text/event-stream` body as the HTML standard defines: lines end in CRLF, LF or CR,
|
|
3
|
+
* comments start with a colon, and an event is dispatched at a blank line. A trailing event
|
|
4
|
+
* without its blank line is discarded. `onActivity` runs for every complete line, comments included.
|
|
5
|
+
*/
|
|
6
|
+
export async function readServerSentEvents(body, onEvent, onActivity = () => { }) {
|
|
7
|
+
const reader = body.getReader();
|
|
8
|
+
const decoder = new TextDecoder();
|
|
9
|
+
let buffer = "";
|
|
10
|
+
let type = "";
|
|
11
|
+
let data = [];
|
|
12
|
+
let id;
|
|
13
|
+
let seenCarriageReturn = false;
|
|
14
|
+
function line(text) {
|
|
15
|
+
onActivity();
|
|
16
|
+
if (text === "") {
|
|
17
|
+
if (data.length > 0)
|
|
18
|
+
onEvent({ type: type === "" ? "message" : type, data: data.join("\n"), id });
|
|
19
|
+
type = "";
|
|
20
|
+
data = [];
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (text.startsWith(":"))
|
|
24
|
+
return;
|
|
25
|
+
const colon = text.indexOf(":");
|
|
26
|
+
const field = colon === -1 ? text : text.slice(0, colon);
|
|
27
|
+
let value = colon === -1 ? "" : text.slice(colon + 1);
|
|
28
|
+
if (value.startsWith(" "))
|
|
29
|
+
value = value.slice(1);
|
|
30
|
+
if (field === "event")
|
|
31
|
+
type = value;
|
|
32
|
+
else if (field === "data")
|
|
33
|
+
data.push(value);
|
|
34
|
+
else if (field === "id" && !value.includes("\0"))
|
|
35
|
+
id = value;
|
|
36
|
+
}
|
|
37
|
+
while (true) {
|
|
38
|
+
const { done, value } = await reader.read();
|
|
39
|
+
if (done)
|
|
40
|
+
return;
|
|
41
|
+
buffer += decoder.decode(value, { stream: true }); // Keeps multi-byte characters split across chunks.
|
|
42
|
+
let start = 0;
|
|
43
|
+
for (let index = 0; index < buffer.length; index++) {
|
|
44
|
+
const char = buffer[index];
|
|
45
|
+
if (char === "\n" && seenCarriageReturn && index === start) {
|
|
46
|
+
start = index + 1;
|
|
47
|
+
seenCarriageReturn = false;
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
seenCarriageReturn = false;
|
|
51
|
+
if (char !== "\n" && char !== "\r")
|
|
52
|
+
continue;
|
|
53
|
+
line(buffer.slice(start, index));
|
|
54
|
+
start = index + 1;
|
|
55
|
+
// A CR may be the first half of a CRLF split across chunks.
|
|
56
|
+
seenCarriageReturn = char === "\r";
|
|
57
|
+
}
|
|
58
|
+
buffer = buffer.slice(start);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
//# sourceMappingURL=sse.js.map
|
package/dist/sse.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse.js","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAOA;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,IAAgC,EAChC,OAAyC,EACzC,UAAU,GAAe,GAAG,EAAE,GAAE,CAAC;IAEjC,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;IAChC,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,IAAI,GAAG,EAAE,CAAC;IACd,IAAI,IAAI,GAAa,EAAE,CAAC;IACxB,IAAI,EAAsB,CAAC;IAC3B,IAAI,kBAAkB,GAAG,KAAK,CAAC;IAE/B,SAAS,IAAI,CAAC,IAAY;QACxB,UAAU,EAAE,CAAC;QACb,IAAI,IAAI,KAAK,EAAE,EAAE,CAAC;YAChB,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;gBAAE,OAAO,CAAC,EAAE,IAAI,EAAE,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;YAClG,IAAI,GAAG,EAAE,CAAC;YAAC,IAAI,GAAG,EAAE,CAAC;YACrB,OAAO;QACT,CAAC;QACD,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;YAAE,OAAO;QACjC,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC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gBAAC,kBAAkB,GAAG,KAAK,CAAC;gBAAC,SAAS;YAAC,CAAC;YACxH,kBAAkB,GAAG,KAAK,CAAC;YAC3B,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI;gBAAE,SAAS;YAC7C,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;YACjC,KAAK,GAAG,KAAK,GAAG,CAAC,CAAC;YAClB,4DAA4D;YAC5D,kBAAkB,GAAG,IAAI,KAAK,IAAI,CAAC;QACrC,CAAC;QACD,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC/B,CAAC;AACH,CAAC"}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable storage for one writer's checkpoint. `connectSync({ store })` loads it once, saves through
|
|
3
|
+
* it and closes it when the client closes. Implementations hold an exclusive lock while open, so
|
|
4
|
+
* two clients can never share one stored writer.
|
|
5
|
+
*/
|
|
6
|
+
export interface CheckpointStore {
|
|
7
|
+
/** The saved checkpoint as parsed JSON, or undefined when nothing is saved. */
|
|
8
|
+
load(): Promise<unknown>;
|
|
9
|
+
/** Replaces the saved checkpoint; resolves once it is stored. */
|
|
10
|
+
save(checkpoint: unknown): Promise<void>;
|
|
11
|
+
/** Removes the saved checkpoint. */
|
|
12
|
+
clear(): Promise<void>;
|
|
13
|
+
/**
|
|
14
|
+
* Releases the lock and any connection once operations already started have finished. Further
|
|
15
|
+
* calls are no-ops; other methods then reject.
|
|
16
|
+
*/
|
|
17
|
+
close(): void;
|
|
18
|
+
}
|
|
19
|
+
/** Another client in this browser profile or process already holds this store's lock. */
|
|
20
|
+
export declare class CheckpointLockedError extends Error {
|
|
21
|
+
readonly name = "CheckpointLockedError";
|
|
22
|
+
}
|
|
23
|
+
/** The part of the Web Locks API the stores use; browsers and Node.js provide `navigator.locks`. */
|
|
24
|
+
export interface LockManagerLike {
|
|
25
|
+
request(name: string, options: {
|
|
26
|
+
readonly ifAvailable: true;
|
|
27
|
+
}, callback: (lock: unknown) => Promise<void>): Promise<unknown>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Takes an exclusive lock without waiting for another holder. The returned function waits for
|
|
31
|
+
* `after` before releasing the lock and resolves once the lock manager has freed it. A reopen
|
|
32
|
+
* in this realm waits for a pending release, so it cannot overlap the closing store's operations.
|
|
33
|
+
* @internal Shared by the IndexedDB and file stores.
|
|
34
|
+
*/
|
|
35
|
+
export declare function acquireLock(name: string, locks?: LockManagerLike): Promise<(after?: Promise<unknown>) => Promise<void>>;
|
|
36
|
+
/**
|
|
37
|
+
* Shared state for stores that hold a lock until `close()`. Operations started before `close()`
|
|
38
|
+
* finish first; then `onClose` runs, and the lock is released once it settles.
|
|
39
|
+
* @internal
|
|
40
|
+
*/
|
|
41
|
+
export declare function closable(release: (after: Promise<unknown>) => Promise<void>, onClose?: () => void | Promise<void>): {
|
|
42
|
+
run<T>(operation: () => Promise<T>): Promise<T>;
|
|
43
|
+
close(): Promise<void>;
|
|
44
|
+
};
|
|
45
|
+
/** The part of `indexedDB` the store uses. */
|
|
46
|
+
export interface IdbFactoryLike {
|
|
47
|
+
open(name: string, version: number): unknown;
|
|
48
|
+
}
|
|
49
|
+
export interface IndexedDbStoreOptions {
|
|
50
|
+
/** IndexedDB database name; one database can hold many writers' checkpoints. */
|
|
51
|
+
readonly database: string;
|
|
52
|
+
/** This writer's key within the database, for example a document and writer name. */
|
|
53
|
+
readonly key: string;
|
|
54
|
+
/**
|
|
55
|
+
* How many writers, one per tab, may use `key` at once. Default 1. Slot 0 is `key` itself and slot
|
|
56
|
+
* n is `key#n`; the store takes a free slot, preferring one with pending edits, then one with a
|
|
57
|
+
* saved checkpoint, then the lowest. At most 64.
|
|
58
|
+
*/
|
|
59
|
+
readonly slots?: number;
|
|
60
|
+
/** Defaults to the global `indexedDB`. */
|
|
61
|
+
readonly indexedDB?: IdbFactoryLike;
|
|
62
|
+
/** Defaults to `navigator.locks`. */
|
|
63
|
+
readonly locks?: LockManagerLike;
|
|
64
|
+
}
|
|
65
|
+
/** A browser checkpoint store, with the slot it took. */
|
|
66
|
+
export interface IndexedDbCheckpointStore extends CheckpointStore {
|
|
67
|
+
/** The slot this store holds, from 0 to `slots - 1`. */
|
|
68
|
+
readonly slot: number;
|
|
69
|
+
/** The key its checkpoint is stored under: `key` for slot 0, `key#n` for slot n. */
|
|
70
|
+
readonly key: string;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Opens a browser checkpoint store. It takes the Web Lock `articollab:<database>:<key>` first and
|
|
74
|
+
* throws `CheckpointLockedError` if another tab, or another client in this tab, holds it. With
|
|
75
|
+
* `slots`, each tab takes a free slot instead and the error means every slot is held.
|
|
76
|
+
* Checkpoints are stored as JSON strings in the `checkpoints` object store.
|
|
77
|
+
*/
|
|
78
|
+
export declare function openIndexedDbStore(options: IndexedDbStoreOptions): Promise<IndexedDbCheckpointStore>;
|
|
79
|
+
//# sourceMappingURL=store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,+EAA+E;IAC/E,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IACzB,iEAAiE;IACjE,IAAI,CAAC,UAAU,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzC,oCAAoC;IACpC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB;;;OAGG;IACH,KAAK,IAAI,IAAI,CAAC;CACf;AAED,yFAAyF;AACzF,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,SAAkB,IAAI,2BAA2B;CAClD;AAED,oGAAoG;AACpG,MAAM,WAAW,eAAe;IAC9B,OAAO,CACL,IAAI,EAAE,MAAM,EACZ,OA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wDAAwD;IACxD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,oFAAoF;IACpF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAiBD;;;;;GAKG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAyE1G"}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { integerOption } from "@articollab/core/adapter";
|
|
2
|
+
/** Another client in this browser profile or process already holds this store's lock. */
|
|
3
|
+
export class CheckpointLockedError extends Error {
|
|
4
|
+
name = "CheckpointLockedError";
|
|
5
|
+
}
|
|
6
|
+
function defaultLocks() {
|
|
7
|
+
const locks = globalThis.navigator?.locks;
|
|
8
|
+
if (locks === undefined)
|
|
9
|
+
throw new Error("navigator.locks is unavailable; pass `locks`");
|
|
10
|
+
return locks;
|
|
11
|
+
}
|
|
12
|
+
/** Locks this realm released but the lock manager may not have freed yet, by name. */
|
|
13
|
+
const releasing = new Map();
|
|
14
|
+
/**
|
|
15
|
+
* Takes an exclusive lock without waiting for another holder. The returned function waits for
|
|
16
|
+
* `after` before releasing the lock and resolves once the lock manager has freed it. A reopen
|
|
17
|
+
* in this realm waits for a pending release, so it cannot overlap the closing store's operations.
|
|
18
|
+
* @internal Shared by the IndexedDB and file stores.
|
|
19
|
+
*/
|
|
20
|
+
export async function acquireLock(name, locks = defaultLocks()) {
|
|
21
|
+
await releasing.get(name);
|
|
22
|
+
let release = () => { };
|
|
23
|
+
const held = new Promise((resolve) => { release = resolve; });
|
|
24
|
+
let finished = Promise.resolve();
|
|
25
|
+
const granted = await new Promise((resolve, reject) => {
|
|
26
|
+
// The request settles only after the callback returns, that is, once the lock is free again.
|
|
27
|
+
finished = locks.request(name, { ifAvailable: true }, async (lock) => {
|
|
28
|
+
resolve(lock !== null);
|
|
29
|
+
if (lock !== null)
|
|
30
|
+
await held;
|
|
31
|
+
});
|
|
32
|
+
finished.catch(reject);
|
|
33
|
+
});
|
|
34
|
+
if (!granted)
|
|
35
|
+
throw new CheckpointLockedError(`Checkpoint store is in use elsewhere: ${name}`);
|
|
36
|
+
return (after = Promise.resolve()) => {
|
|
37
|
+
const released = after.catch(() => { }).then(() => { release(); return finished; }).then(() => { });
|
|
38
|
+
const ready = released.catch(() => { }).finally(() => { if (releasing.get(name) === ready)
|
|
39
|
+
releasing.delete(name); });
|
|
40
|
+
releasing.set(name, ready);
|
|
41
|
+
return released;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Shared state for stores that hold a lock until `close()`. Operations started before `close()`
|
|
46
|
+
* finish first; then `onClose` runs, and the lock is released once it settles.
|
|
47
|
+
* @internal
|
|
48
|
+
*/
|
|
49
|
+
export function closable(release, onClose = () => { }) {
|
|
50
|
+
let closing;
|
|
51
|
+
const running = new Set();
|
|
52
|
+
return {
|
|
53
|
+
run(operation) {
|
|
54
|
+
if (closing !== undefined)
|
|
55
|
+
return Promise.reject(new Error("Checkpoint store is closed"));
|
|
56
|
+
const promise = operation();
|
|
57
|
+
running.add(promise);
|
|
58
|
+
const settled = () => { running.delete(promise); };
|
|
59
|
+
promise.then(settled, settled);
|
|
60
|
+
return promise;
|
|
61
|
+
},
|
|
62
|
+
close() {
|
|
63
|
+
if (closing !== undefined)
|
|
64
|
+
return closing;
|
|
65
|
+
const cleanup = Promise.allSettled([...running]).then(onClose);
|
|
66
|
+
closing = Promise.allSettled([cleanup, release(cleanup)]).then(([cleaned, unlocked]) => {
|
|
67
|
+
if (cleaned.status === "rejected")
|
|
68
|
+
throw cleaned.reason;
|
|
69
|
+
if (unlocked.status === "rejected")
|
|
70
|
+
throw unlocked.reason;
|
|
71
|
+
});
|
|
72
|
+
return closing;
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
const OBJECT_STORE = "checkpoints";
|
|
77
|
+
function settle(request) {
|
|
78
|
+
return new Promise((resolve, reject) => {
|
|
79
|
+
request.onsuccess = () => resolve(request.result);
|
|
80
|
+
request.onerror = () => reject(request.error);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
function completion(transaction) {
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
transaction.oncomplete = () => resolve();
|
|
86
|
+
transaction.onerror = () => reject(transaction.error);
|
|
87
|
+
transaction.onabort = () => reject(transaction.error ?? new Error("IndexedDB transaction aborted"));
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
const MAX_SLOTS = 64;
|
|
91
|
+
/** How much a free slot is worth taking: 2 with pending edits, 1 with a checkpoint, 0 empty or unreadable. */
|
|
92
|
+
function slotRank(stored) {
|
|
93
|
+
if (typeof stored !== "string")
|
|
94
|
+
return 0;
|
|
95
|
+
try {
|
|
96
|
+
const parsed = JSON.parse(stored);
|
|
97
|
+
if (typeof parsed !== "object" || parsed === null)
|
|
98
|
+
return 0;
|
|
99
|
+
const pending = parsed.pendingBatches;
|
|
100
|
+
return Array.isArray(pending) && pending.length > 0 ? 2 : 1;
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Opens a browser checkpoint store. It takes the Web Lock `articollab:<database>:<key>` first and
|
|
108
|
+
* throws `CheckpointLockedError` if another tab, or another client in this tab, holds it. With
|
|
109
|
+
* `slots`, each tab takes a free slot instead and the error means every slot is held.
|
|
110
|
+
* Checkpoints are stored as JSON strings in the `checkpoints` object store.
|
|
111
|
+
*/
|
|
112
|
+
export async function openIndexedDbStore(options) {
|
|
113
|
+
const { database } = options;
|
|
114
|
+
if (typeof database !== "string" || database.length === 0)
|
|
115
|
+
throw new TypeError("database must be a nonempty string");
|
|
116
|
+
if (typeof options.key !== "string")
|
|
117
|
+
throw new TypeError("key must be a string");
|
|
118
|
+
const slots = integerOption(options.slots ?? 1, "slots", 1, MAX_SLOTS);
|
|
119
|
+
const factory = options.indexedDB ?? globalThis.indexedDB;
|
|
120
|
+
if (factory === undefined)
|
|
121
|
+
throw new Error("indexedDB is unavailable; pass `indexedDB`");
|
|
122
|
+
const keys = Array.from({ length: slots }, (_, slot) => slot === 0 ? options.key : `${options.key}#${slot}`);
|
|
123
|
+
// With one slot, a held lock fails before the database is opened.
|
|
124
|
+
let release = slots === 1 ? await acquireLock(`articollab:${database}:${keys[0]}`, options.locks) : undefined;
|
|
125
|
+
let slot = 0;
|
|
126
|
+
let db;
|
|
127
|
+
try {
|
|
128
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- The IndexedDB open request shape.
|
|
129
|
+
const request = factory.open(database, 1);
|
|
130
|
+
request.onupgradeneeded = () => {
|
|
131
|
+
if (!request.result.objectStoreNames.contains(OBJECT_STORE))
|
|
132
|
+
request.result.createObjectStore(OBJECT_STORE);
|
|
133
|
+
};
|
|
134
|
+
db = await settle(request);
|
|
135
|
+
}
|
|
136
|
+
catch (cause) {
|
|
137
|
+
release?.().catch(() => { });
|
|
138
|
+
throw cause;
|
|
139
|
+
}
|
|
140
|
+
if (release === undefined) {
|
|
141
|
+
try {
|
|
142
|
+
// A hint only: the lock decides. Take over a closed tab's pending edits first, then an existing session.
|
|
143
|
+
const objects = db.transaction(OBJECT_STORE, "readonly").objectStore(OBJECT_STORE);
|
|
144
|
+
const ranks = await Promise.all(keys.map(async (key) => slotRank(await settle(objects.get(key)))));
|
|
145
|
+
const order = keys.map((_, index) => index).sort((a, b) => ranks[b] - ranks[a] || a - b);
|
|
146
|
+
for (const candidate of order) {
|
|
147
|
+
try {
|
|
148
|
+
release = await acquireLock(`articollab:${database}:${keys[candidate]}`, options.locks);
|
|
149
|
+
slot = candidate;
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
if (!(error instanceof CheckpointLockedError))
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
catch (cause) {
|
|
159
|
+
db.close();
|
|
160
|
+
throw cause;
|
|
161
|
+
}
|
|
162
|
+
if (release === undefined) {
|
|
163
|
+
db.close();
|
|
164
|
+
throw new CheckpointLockedError(`All ${slots} checkpoint slots are in use elsewhere: ${options.key}`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const key = keys[slot];
|
|
168
|
+
const state = closable(release, () => db.close());
|
|
169
|
+
function write(change) {
|
|
170
|
+
return state.run(async () => {
|
|
171
|
+
const transaction = db.transaction(OBJECT_STORE, "readwrite");
|
|
172
|
+
const done = completion(transaction);
|
|
173
|
+
change(transaction.objectStore(OBJECT_STORE));
|
|
174
|
+
await done;
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
slot,
|
|
179
|
+
key,
|
|
180
|
+
load: () => state.run(async () => {
|
|
181
|
+
const stored = await settle(db.transaction(OBJECT_STORE, "readonly").objectStore(OBJECT_STORE).get(key));
|
|
182
|
+
if (stored === undefined)
|
|
183
|
+
return undefined;
|
|
184
|
+
if (typeof stored !== "string")
|
|
185
|
+
throw new Error(`Stored checkpoint is not a JSON string: ${key}`);
|
|
186
|
+
return JSON.parse(stored);
|
|
187
|
+
}),
|
|
188
|
+
save: (checkpoint) => write((store) => { store.put(JSON.stringify(checkpoint), key); }),
|
|
189
|
+
clear: () => write((store) => { store.delete(key); }),
|
|
190
|
+
close() { state.close().catch(() => { }); },
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
//# sourceMappingURL=store.js.map
|