@patodo/localapp 0.1.0 → 0.2.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/.localapp-artifact.json +133 -103
- package/README.md +3 -2
- package/bin/localapp.mjs +54 -8
- package/package.json +1 -1
- package/runtime/native/adapter-manifest.json +1 -1
- package/runtime/native/win32-x64/localapp-native.exe +0 -0
- package/runtime/server/.localapp-server-runtime.json +61 -61
- package/runtime/server/bin/server-cli.cjs +14 -2
- package/runtime/server/bin/worker.cjs +12978 -3242
- package/runtime/server/web/404.html +1 -1
- package/runtime/server/web/_next/static/chunks/{416-53d48ad9442eb7b2.js → 416-c15a156fd32eefc3.js} +1 -1
- package/runtime/server/web/_next/static/chunks/app/{layout-5557bc90d966fded.js → layout-2231382739460b63.js} +1 -1
- package/runtime/server/web/_next/static/css/7618766dbe836b27.css +3 -0
- package/runtime/server/web/inbox.html +1 -1
- package/runtime/server/web/inbox.txt +7 -7
- package/runtime/server/web/index.html +1 -1
- package/runtime/server/web/index.txt +7 -7
- package/runtime/server/web/my/analytics.html +1 -1
- package/runtime/server/web/my/analytics.txt +7 -7
- package/runtime/server/web/my/apps/placeholder/settings.html +1 -1
- package/runtime/server/web/my/apps/placeholder/settings.txt +7 -7
- package/runtime/server/web/my/apps.html +1 -1
- package/runtime/server/web/my/apps.txt +7 -7
- package/runtime/server/web/my/dashboard.html +1 -1
- package/runtime/server/web/my/dashboard.txt +7 -7
- package/runtime/server/web/my/device-actions.html +1 -1
- package/runtime/server/web/my/device-actions.txt +7 -7
- package/runtime/server/web/my/device-notifications.html +1 -1
- package/runtime/server/web/my/device-notifications.txt +7 -7
- package/runtime/server/web/my/favorites.html +1 -1
- package/runtime/server/web/my/favorites.txt +7 -7
- package/runtime/server/web/my/groups.html +1 -1
- package/runtime/server/web/my/groups.txt +7 -7
- package/runtime/server/web/my/info.html +1 -1
- package/runtime/server/web/my/info.txt +7 -7
- package/runtime/server/web/my/keys.html +1 -1
- package/runtime/server/web/my/keys.txt +7 -7
- package/runtime/server/web/my/orgs.html +1 -1
- package/runtime/server/web/my/orgs.txt +7 -7
- package/runtime/server/web/my/pages.html +1 -1
- package/runtime/server/web/my/pages.txt +7 -7
- package/runtime/server/web/my/peers.html +1 -1
- package/runtime/server/web/my/peers.txt +7 -7
- package/runtime/server/web/my/recent.html +1 -1
- package/runtime/server/web/my/recent.txt +7 -7
- package/runtime/server/web/my/settings.html +1 -1
- package/runtime/server/web/my/settings.txt +7 -7
- package/runtime/server/web/my/studio.html +1 -1
- package/runtime/server/web/my/studio.txt +7 -7
- package/runtime/server/web/my/subscriptions.html +1 -1
- package/runtime/server/web/my/subscriptions.txt +7 -7
- package/runtime/server/web/my/system.html +1 -1
- package/runtime/server/web/my/system.txt +7 -7
- package/runtime/server/web/my/tasks.html +1 -1
- package/runtime/server/web/my/tasks.txt +7 -7
- package/runtime/server/web/my/users.html +1 -1
- package/runtime/server/web/my/users.txt +7 -7
- package/runtime/server/web/my.html +1 -1
- package/runtime/server/web/my.txt +7 -7
- package/runtime/server/web/platform-shell/placeholder/placeholder.html +1 -1
- package/runtime/server/web/platform-shell/placeholder/placeholder.txt +8 -8
- package/runtime/server/web/platform-shell-preview.html +1 -1
- package/runtime/server/web/platform-shell-preview.txt +8 -8
- package/runtime/server/web/setup.html +1 -1
- package/runtime/server/web/setup.txt +7 -7
- package/template/.claude/skills/localapp-collaboration/SKILL.md +92 -0
- package/template/AGENTS.md +6 -0
- package/template/CLAUDE.md +6 -0
- package/template/package.json +2 -1
- package/template/runtime/platform-capabilities.json +13 -1
- package/template/runtime/sdk/crdt/package.json +39 -0
- package/template/runtime/sdk/crdt/src/index.ts +440 -0
- package/template/runtime/sdk/crdt/src/react.ts +67 -0
- package/template/runtime/sdk/crdt/tests/provider.test.ts +169 -0
- package/template/runtime/sdk/crdt/tsconfig.json +18 -0
- package/template/runtime/server-core/dist/generated/platform-capabilities.d.ts +14 -2
- package/template/runtime/server-core/dist/generated/platform-capabilities.d.ts.map +1 -1
- package/template/runtime/server-core/dist/generated/platform-capabilities.js +14 -2
- package/template/runtime/server-core/dist/generated/platform-capabilities.js.map +1 -1
- package/template/runtime/server-core/dist/lib/__tests__/platform-capabilities.test.js +13 -2
- package/template/runtime/server-core/dist/lib/__tests__/platform-capabilities.test.js.map +1 -1
- package/template/runtime/version.json +1 -1
- package/template/tests/agent-guidance-template.test.ts +14 -0
- package/runtime/server/web/_next/static/css/afdc0938fca59693.css +0 -3
- /package/runtime/server/web/_next/static/{CqtRUQyhpQ2FmEc3vaVz3 → GyUKT-hZbRN2iexOBXTTr}/_buildManifest.js +0 -0
- /package/runtime/server/web/_next/static/{CqtRUQyhpQ2FmEc3vaVz3 → GyUKT-hZbRN2iexOBXTTr}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import * as Y from "yjs";
|
|
2
|
+
import { detectBasePath } from "@localapp/sdk";
|
|
3
|
+
|
|
4
|
+
export const LOCALAPP_EDITING_AWARENESS_EVENT = "localapp:crdt-editing-awareness";
|
|
5
|
+
|
|
6
|
+
const REMOTE_ORIGIN = Symbol("localapp-crdt-remote");
|
|
7
|
+
const MAX_PENDING_UPDATE_BYTES = 8 * 1024 * 1024;
|
|
8
|
+
const MAX_BATCH_UPDATE_BYTES = 768 * 1024;
|
|
9
|
+
|
|
10
|
+
export type LocalAppCrdtStatus = "connecting" | "connected" | "offline" | "error" | "destroyed";
|
|
11
|
+
|
|
12
|
+
export interface EditingTarget {
|
|
13
|
+
surfaceId: string;
|
|
14
|
+
fieldId?: string;
|
|
15
|
+
label?: string;
|
|
16
|
+
kind?: "field" | "selection" | "canvas";
|
|
17
|
+
selection?: { anchor: string; head: string };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface AwarenessUser {
|
|
21
|
+
id: string;
|
|
22
|
+
name: string;
|
|
23
|
+
displayName: string | null;
|
|
24
|
+
avatarUrl: string | null;
|
|
25
|
+
color: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface EditingPeer {
|
|
29
|
+
clientId: string;
|
|
30
|
+
clock: number;
|
|
31
|
+
user: AwarenessUser;
|
|
32
|
+
editing: EditingTarget;
|
|
33
|
+
overlay?: boolean;
|
|
34
|
+
updatedAt: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface LocalAppCrdtOptions {
|
|
38
|
+
resource: string;
|
|
39
|
+
documentId: string;
|
|
40
|
+
doc?: Y.Doc;
|
|
41
|
+
basePath?: string;
|
|
42
|
+
clientId?: string;
|
|
43
|
+
autoConnect?: boolean;
|
|
44
|
+
awareness?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface LocalAppCrdtError {
|
|
48
|
+
operation: "connect" | "sync" | "update" | "awareness";
|
|
49
|
+
error: Error;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type StatusListener = (status: LocalAppCrdtStatus) => void;
|
|
53
|
+
type AwarenessListener = (peers: EditingPeer[]) => void;
|
|
54
|
+
type ErrorListener = (error: LocalAppCrdtError) => void;
|
|
55
|
+
|
|
56
|
+
export class LocalAppCrdtProvider {
|
|
57
|
+
readonly doc: Y.Doc;
|
|
58
|
+
readonly resource: string;
|
|
59
|
+
readonly documentId: string;
|
|
60
|
+
readonly clientId: string;
|
|
61
|
+
|
|
62
|
+
private readonly basePath: string;
|
|
63
|
+
private readonly awarenessEnabled: boolean;
|
|
64
|
+
private readonly sourceId: string;
|
|
65
|
+
private eventSource: EventSource | null = null;
|
|
66
|
+
private heartbeatTimer: number | null = null;
|
|
67
|
+
private retryTimer: number | null = null;
|
|
68
|
+
private pendingUpdates: Uint8Array[] = [];
|
|
69
|
+
private sending = false;
|
|
70
|
+
private destroyed = false;
|
|
71
|
+
private listeningForDocumentUpdates = false;
|
|
72
|
+
private initialDocumentStateQueued = false;
|
|
73
|
+
private awarenessClock = 0;
|
|
74
|
+
private awarenessLeaseActive = false;
|
|
75
|
+
private editingTarget: EditingTarget | null = null;
|
|
76
|
+
private peers: EditingPeer[] = [];
|
|
77
|
+
private currentStatus: LocalAppCrdtStatus = "offline";
|
|
78
|
+
private readonly statusListeners = new Set<StatusListener>();
|
|
79
|
+
private readonly awarenessListeners = new Set<AwarenessListener>();
|
|
80
|
+
private readonly errorListeners = new Set<ErrorListener>();
|
|
81
|
+
|
|
82
|
+
constructor(options: LocalAppCrdtOptions) {
|
|
83
|
+
this.resource = requireIdentifier(options.resource, "resource");
|
|
84
|
+
this.documentId = requireDocumentId(options.documentId);
|
|
85
|
+
this.doc = options.doc ?? new Y.Doc();
|
|
86
|
+
this.basePath = (options.basePath ?? detectBasePath()).replace(/\/+$/, "");
|
|
87
|
+
this.clientId = options.clientId ?? createClientId();
|
|
88
|
+
this.sourceId = `${this.resource}:${this.documentId}:${this.clientId}`;
|
|
89
|
+
this.awarenessEnabled = options.awareness !== false;
|
|
90
|
+
if (options.autoConnect !== false) void this.connect();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
get status(): LocalAppCrdtStatus {
|
|
94
|
+
return this.currentStatus;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
get awareness(): readonly EditingPeer[] {
|
|
98
|
+
return this.peers;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
onStatus(listener: StatusListener): () => void {
|
|
102
|
+
this.statusListeners.add(listener);
|
|
103
|
+
listener(this.currentStatus);
|
|
104
|
+
return () => this.statusListeners.delete(listener);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
onAwareness(listener: AwarenessListener): () => void {
|
|
108
|
+
this.awarenessListeners.add(listener);
|
|
109
|
+
listener(this.peers);
|
|
110
|
+
return () => this.awarenessListeners.delete(listener);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
onError(listener: ErrorListener): () => void {
|
|
114
|
+
this.errorListeners.add(listener);
|
|
115
|
+
return () => this.errorListeners.delete(listener);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async connect(): Promise<void> {
|
|
119
|
+
if (this.destroyed || this.eventSource) return;
|
|
120
|
+
this.startDocumentUpdates();
|
|
121
|
+
this.queueInitialDocumentState();
|
|
122
|
+
this.setStatus("connecting");
|
|
123
|
+
if (typeof EventSource !== "undefined") {
|
|
124
|
+
const query = new URLSearchParams({
|
|
125
|
+
resource: this.resource,
|
|
126
|
+
documentId: this.documentId,
|
|
127
|
+
clientId: this.clientId,
|
|
128
|
+
});
|
|
129
|
+
this.eventSource = new EventSource(`${this.basePath}/crdt/events?${query}`);
|
|
130
|
+
this.eventSource.addEventListener("crdt:update", this.handleRemoteUpdate as EventListener);
|
|
131
|
+
this.eventSource.addEventListener("crdt:awareness", this.handleAwarenessSnapshot as EventListener);
|
|
132
|
+
this.eventSource.addEventListener("open", this.handleEventSourceOpen as EventListener);
|
|
133
|
+
this.eventSource.addEventListener("error", this.handleEventSourceError as EventListener);
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
await this.synchronize();
|
|
137
|
+
this.setStatus("connected");
|
|
138
|
+
this.startHeartbeat();
|
|
139
|
+
await this.flushUpdates();
|
|
140
|
+
if (this.editingTarget) await this.sendAwareness();
|
|
141
|
+
} catch (error) {
|
|
142
|
+
this.report("connect", error);
|
|
143
|
+
this.setStatus(typeof navigator !== "undefined" && navigator.onLine === false ? "offline" : "error");
|
|
144
|
+
this.scheduleRetry();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
setEditingTarget(target: EditingTarget | null): void {
|
|
149
|
+
this.editingTarget = target ? normalizeEditingTarget(target) : null;
|
|
150
|
+
this.awarenessClock += 1;
|
|
151
|
+
if (!this.destroyed && this.awarenessEnabled && this.currentStatus === "connected") void this.sendAwareness();
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async synchronize(): Promise<void> {
|
|
155
|
+
const response = await fetch(`${this.basePath}/crdt/sync`, {
|
|
156
|
+
method: "POST",
|
|
157
|
+
credentials: "include",
|
|
158
|
+
headers: { "Content-Type": "application/json" },
|
|
159
|
+
body: JSON.stringify({
|
|
160
|
+
resource: this.resource,
|
|
161
|
+
documentId: this.documentId,
|
|
162
|
+
stateVector: encodeBase64Url(Y.encodeStateVector(this.doc)),
|
|
163
|
+
}),
|
|
164
|
+
});
|
|
165
|
+
const body = await readJson(response);
|
|
166
|
+
if (!response.ok || body.success !== true || typeof body.data?.update !== "string") {
|
|
167
|
+
throw new Error(body.error ?? `CRDT sync failed with HTTP ${response.status}`);
|
|
168
|
+
}
|
|
169
|
+
const update = decodeBase64Url(body.data.update);
|
|
170
|
+
if (update.byteLength > 0) Y.applyUpdate(this.doc, update, REMOTE_ORIGIN);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async destroy(): Promise<void> {
|
|
174
|
+
if (this.destroyed) return;
|
|
175
|
+
this.destroyed = true;
|
|
176
|
+
if (this.listeningForDocumentUpdates) this.doc.off("update", this.handleDocumentUpdate);
|
|
177
|
+
this.listeningForDocumentUpdates = false;
|
|
178
|
+
this.eventSource?.close();
|
|
179
|
+
this.eventSource = null;
|
|
180
|
+
if (this.heartbeatTimer !== null) window.clearInterval(this.heartbeatTimer);
|
|
181
|
+
if (this.retryTimer !== null) window.clearTimeout(this.retryTimer);
|
|
182
|
+
this.heartbeatTimer = null;
|
|
183
|
+
this.retryTimer = null;
|
|
184
|
+
if (this.awarenessEnabled && this.awarenessLeaseActive) {
|
|
185
|
+
this.awarenessClock += 1;
|
|
186
|
+
await this.sendAwareness(true).catch(() => {});
|
|
187
|
+
}
|
|
188
|
+
this.peers = [];
|
|
189
|
+
this.publishAwareness();
|
|
190
|
+
this.setStatus("destroyed");
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
private readonly handleDocumentUpdate = (update: Uint8Array, origin: unknown) => {
|
|
194
|
+
if (origin === REMOTE_ORIGIN || this.destroyed) return;
|
|
195
|
+
this.pendingUpdates.push(update);
|
|
196
|
+
const pendingBytes = this.pendingUpdates.reduce((total, item) => total + item.byteLength, 0);
|
|
197
|
+
if (pendingBytes > MAX_PENDING_UPDATE_BYTES) {
|
|
198
|
+
this.pendingUpdates = [Y.mergeUpdates(this.pendingUpdates)];
|
|
199
|
+
}
|
|
200
|
+
if (this.currentStatus === "connected") void this.flushUpdates();
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
private startDocumentUpdates(): void {
|
|
204
|
+
if (this.listeningForDocumentUpdates) return;
|
|
205
|
+
this.doc.on("update", this.handleDocumentUpdate);
|
|
206
|
+
this.listeningForDocumentUpdates = true;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private queueInitialDocumentState(): void {
|
|
210
|
+
if (this.initialDocumentStateQueued) return;
|
|
211
|
+
this.initialDocumentStateQueued = true;
|
|
212
|
+
const update = Y.encodeStateAsUpdate(this.doc);
|
|
213
|
+
// An empty Y.Doc encodes as a two-byte no-op update.
|
|
214
|
+
if (update.byteLength > 2) this.pendingUpdates.push(update);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
private readonly handleRemoteUpdate = (event: MessageEvent) => {
|
|
218
|
+
try {
|
|
219
|
+
const body = JSON.parse(event.data) as { data?: { update?: unknown } };
|
|
220
|
+
if (typeof body.data?.update !== "string") return;
|
|
221
|
+
Y.applyUpdate(this.doc, decodeBase64Url(body.data.update), REMOTE_ORIGIN);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
this.report("update", error);
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
private readonly handleAwarenessSnapshot = (event: MessageEvent) => {
|
|
228
|
+
try {
|
|
229
|
+
const body = JSON.parse(event.data) as { data?: { peers?: unknown } };
|
|
230
|
+
const peers = Array.isArray(body.data?.peers)
|
|
231
|
+
? body.data.peers.filter(isEditingPeer).filter((peer) => peer.clientId !== this.clientId)
|
|
232
|
+
: [];
|
|
233
|
+
this.peers = peers;
|
|
234
|
+
this.publishAwareness();
|
|
235
|
+
} catch (error) {
|
|
236
|
+
this.report("awareness", error);
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
private readonly handleEventSourceOpen = () => {
|
|
241
|
+
if (this.destroyed) return;
|
|
242
|
+
void this.synchronize()
|
|
243
|
+
.then(async () => {
|
|
244
|
+
this.setStatus("connected");
|
|
245
|
+
this.startHeartbeat();
|
|
246
|
+
await this.flushUpdates();
|
|
247
|
+
if (this.editingTarget) await this.sendAwareness();
|
|
248
|
+
})
|
|
249
|
+
.catch((error) => this.report("sync", error));
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
private readonly handleEventSourceError = () => {
|
|
253
|
+
if (!this.destroyed) this.setStatus(typeof navigator !== "undefined" && navigator.onLine === false ? "offline" : "connecting");
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
private async flushUpdates(): Promise<void> {
|
|
257
|
+
if (this.sending || this.destroyed || this.pendingUpdates.length === 0) return;
|
|
258
|
+
this.sending = true;
|
|
259
|
+
try {
|
|
260
|
+
while (!this.destroyed && this.pendingUpdates.length > 0) {
|
|
261
|
+
const count = pendingBatchCount(this.pendingUpdates);
|
|
262
|
+
const update = count === 1 ? this.pendingUpdates[0] : Y.mergeUpdates(this.pendingUpdates.slice(0, count));
|
|
263
|
+
const response = await fetch(`${this.basePath}/crdt/update`, {
|
|
264
|
+
method: "POST",
|
|
265
|
+
credentials: "include",
|
|
266
|
+
headers: { "Content-Type": "application/json" },
|
|
267
|
+
body: JSON.stringify({
|
|
268
|
+
resource: this.resource,
|
|
269
|
+
documentId: this.documentId,
|
|
270
|
+
clientId: this.clientId,
|
|
271
|
+
update: encodeBase64Url(update),
|
|
272
|
+
}),
|
|
273
|
+
});
|
|
274
|
+
const body = await readJson(response);
|
|
275
|
+
if (!response.ok || body.success !== true) throw new Error(body.error ?? `CRDT update failed with HTTP ${response.status}`);
|
|
276
|
+
this.pendingUpdates.splice(0, count);
|
|
277
|
+
}
|
|
278
|
+
} catch (error) {
|
|
279
|
+
this.report("update", error);
|
|
280
|
+
this.setStatus("offline");
|
|
281
|
+
this.scheduleRetry();
|
|
282
|
+
} finally {
|
|
283
|
+
this.sending = false;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
private async sendAwareness(clear = false): Promise<void> {
|
|
288
|
+
if (!this.awarenessEnabled) return;
|
|
289
|
+
const response = await fetch(`${this.basePath}/crdt/awareness`, {
|
|
290
|
+
method: "POST",
|
|
291
|
+
credentials: "include",
|
|
292
|
+
headers: { "Content-Type": "application/json" },
|
|
293
|
+
keepalive: clear,
|
|
294
|
+
body: JSON.stringify({
|
|
295
|
+
resource: this.resource,
|
|
296
|
+
documentId: this.documentId,
|
|
297
|
+
clientId: this.clientId,
|
|
298
|
+
clock: this.awarenessClock,
|
|
299
|
+
state: clear || !this.editingTarget ? null : { editing: this.editingTarget },
|
|
300
|
+
}),
|
|
301
|
+
});
|
|
302
|
+
if (!response.ok) {
|
|
303
|
+
const body = await readJson(response);
|
|
304
|
+
const error = new Error(body.error ?? `CRDT awareness failed with HTTP ${response.status}`);
|
|
305
|
+
this.report("awareness", error);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
this.awarenessLeaseActive = !clear && this.editingTarget !== null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
private startHeartbeat(): void {
|
|
312
|
+
if (!this.awarenessEnabled || this.heartbeatTimer !== null || typeof window === "undefined") return;
|
|
313
|
+
this.heartbeatTimer = window.setInterval(() => {
|
|
314
|
+
if (!this.editingTarget || this.destroyed) return;
|
|
315
|
+
this.awarenessClock += 1;
|
|
316
|
+
void this.sendAwareness();
|
|
317
|
+
}, 15_000);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
private scheduleRetry(): void {
|
|
321
|
+
if (this.destroyed || this.retryTimer !== null || typeof window === "undefined") return;
|
|
322
|
+
this.retryTimer = window.setTimeout(() => {
|
|
323
|
+
this.retryTimer = null;
|
|
324
|
+
this.eventSource?.close();
|
|
325
|
+
this.eventSource = null;
|
|
326
|
+
void this.connect();
|
|
327
|
+
}, 2_000);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private publishAwareness(): void {
|
|
331
|
+
for (const listener of this.awarenessListeners) listener(this.peers);
|
|
332
|
+
if (typeof window !== "undefined" && typeof CustomEvent !== "undefined") {
|
|
333
|
+
window.dispatchEvent(new CustomEvent(LOCALAPP_EDITING_AWARENESS_EVENT, {
|
|
334
|
+
detail: { sourceId: this.sourceId, peers: this.peers },
|
|
335
|
+
}));
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private setStatus(status: LocalAppCrdtStatus): void {
|
|
340
|
+
if (this.currentStatus === status) return;
|
|
341
|
+
this.currentStatus = status;
|
|
342
|
+
for (const listener of this.statusListeners) listener(status);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
private report(operation: LocalAppCrdtError["operation"], value: unknown): void {
|
|
346
|
+
const error = value instanceof Error ? value : new Error(String(value));
|
|
347
|
+
for (const listener of this.errorListeners) listener({ operation, error });
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
export function createLocalAppCrdt(options: LocalAppCrdtOptions): LocalAppCrdtProvider {
|
|
352
|
+
return new LocalAppCrdtProvider(options);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export function encodeRelativePosition(position: Y.RelativePosition): string {
|
|
356
|
+
return encodeBase64Url(Y.encodeRelativePosition(position));
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export function decodeRelativePosition(value: string): Y.RelativePosition {
|
|
360
|
+
return Y.decodeRelativePosition(decodeBase64Url(value));
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export { Y };
|
|
364
|
+
|
|
365
|
+
function requireIdentifier(value: string, label: string): string {
|
|
366
|
+
const normalized = value.trim();
|
|
367
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,99}$/.test(normalized)) throw new Error(`Invalid CRDT ${label}`);
|
|
368
|
+
return normalized;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function requireDocumentId(value: string): string {
|
|
372
|
+
const normalized = value.trim();
|
|
373
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.:@/-]{0,199}$/.test(normalized) || normalized.includes("..")) {
|
|
374
|
+
throw new Error("Invalid CRDT documentId");
|
|
375
|
+
}
|
|
376
|
+
return normalized;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function normalizeEditingTarget(target: EditingTarget): EditingTarget {
|
|
380
|
+
const surfaceId = requireIdentifier(target.surfaceId, "surfaceId");
|
|
381
|
+
const fieldId = target.fieldId === undefined ? undefined : requireIdentifier(target.fieldId, "fieldId");
|
|
382
|
+
const label = target.label?.trim().slice(0, 80) || undefined;
|
|
383
|
+
const kind = target.kind ?? "field";
|
|
384
|
+
if (!["field", "selection", "canvas"].includes(kind)) throw new Error("Invalid CRDT editing target kind");
|
|
385
|
+
const selection = target.selection;
|
|
386
|
+
if (selection && (selection.anchor.length > 2048 || selection.head.length > 2048)) {
|
|
387
|
+
throw new Error("Invalid CRDT editing target selection");
|
|
388
|
+
}
|
|
389
|
+
return {
|
|
390
|
+
surfaceId,
|
|
391
|
+
...(fieldId ? { fieldId } : {}),
|
|
392
|
+
...(label ? { label } : {}),
|
|
393
|
+
kind,
|
|
394
|
+
...(selection ? { selection } : {}),
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function createClientId(): string {
|
|
399
|
+
return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function encodeBase64Url(bytes: Uint8Array): string {
|
|
403
|
+
let binary = "";
|
|
404
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
405
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function decodeBase64Url(value: string): Uint8Array {
|
|
409
|
+
if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new Error("Invalid base64url payload");
|
|
410
|
+
const padded = value.replaceAll("-", "+").replaceAll("_", "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
|
|
411
|
+
const binary = atob(padded);
|
|
412
|
+
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async function readJson(response: Response): Promise<any> {
|
|
416
|
+
try { return await response.json(); }
|
|
417
|
+
catch { return { success: false, error: `HTTP ${response.status}` }; }
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function isEditingPeer(value: unknown): value is EditingPeer {
|
|
421
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
422
|
+
const peer = value as Record<string, any>;
|
|
423
|
+
return typeof peer.clientId === "string"
|
|
424
|
+
&& typeof peer.clock === "number"
|
|
425
|
+
&& typeof peer.updatedAt === "string"
|
|
426
|
+
&& peer.user && typeof peer.user.id === "string" && typeof peer.user.color === "string"
|
|
427
|
+
&& peer.editing && typeof peer.editing.surfaceId === "string";
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function pendingBatchCount(updates: Uint8Array[]): number {
|
|
431
|
+
let bytes = 0;
|
|
432
|
+
let count = 0;
|
|
433
|
+
for (const update of updates) {
|
|
434
|
+
if (count > 0 && bytes + update.byteLength > MAX_BATCH_UPDATE_BYTES) break;
|
|
435
|
+
bytes += update.byteLength;
|
|
436
|
+
count += 1;
|
|
437
|
+
if (bytes >= MAX_BATCH_UPDATE_BYTES) break;
|
|
438
|
+
}
|
|
439
|
+
return Math.max(1, count);
|
|
440
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { useEffect, useMemo, useState } from "react";
|
|
2
|
+
import {
|
|
3
|
+
createLocalAppCrdt,
|
|
4
|
+
type EditingPeer,
|
|
5
|
+
type EditingTarget,
|
|
6
|
+
type LocalAppCrdtOptions,
|
|
7
|
+
type LocalAppCrdtProvider,
|
|
8
|
+
type LocalAppCrdtStatus,
|
|
9
|
+
} from "./index.js";
|
|
10
|
+
|
|
11
|
+
export interface UseLocalAppCrdtResult {
|
|
12
|
+
provider: LocalAppCrdtProvider;
|
|
13
|
+
doc: LocalAppCrdtProvider["doc"];
|
|
14
|
+
status: LocalAppCrdtStatus;
|
|
15
|
+
peers: readonly EditingPeer[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function useLocalAppCrdt(options: LocalAppCrdtOptions): UseLocalAppCrdtResult {
|
|
19
|
+
const provider = useMemo(() => createLocalAppCrdt({ ...options, autoConnect: false }), [
|
|
20
|
+
options.resource,
|
|
21
|
+
options.documentId,
|
|
22
|
+
options.doc,
|
|
23
|
+
options.basePath,
|
|
24
|
+
options.clientId,
|
|
25
|
+
options.awareness,
|
|
26
|
+
]);
|
|
27
|
+
const [status, setStatus] = useState(provider.status);
|
|
28
|
+
const [peers, setPeers] = useState<readonly EditingPeer[]>(provider.awareness);
|
|
29
|
+
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
const offStatus = provider.onStatus(setStatus);
|
|
32
|
+
const offAwareness = provider.onAwareness(setPeers);
|
|
33
|
+
if (options.autoConnect !== false) void provider.connect();
|
|
34
|
+
return () => {
|
|
35
|
+
offStatus();
|
|
36
|
+
offAwareness();
|
|
37
|
+
void provider.destroy();
|
|
38
|
+
};
|
|
39
|
+
}, [options.autoConnect, provider]);
|
|
40
|
+
|
|
41
|
+
return { provider, doc: provider.doc, status, peers };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function useEditingTarget(
|
|
45
|
+
provider: LocalAppCrdtProvider | null | undefined,
|
|
46
|
+
target: EditingTarget | null | undefined,
|
|
47
|
+
active = true,
|
|
48
|
+
): void {
|
|
49
|
+
const surfaceId = target?.surfaceId;
|
|
50
|
+
const fieldId = target?.fieldId;
|
|
51
|
+
const label = target?.label;
|
|
52
|
+
const kind = target?.kind;
|
|
53
|
+
const anchor = target?.selection?.anchor;
|
|
54
|
+
const head = target?.selection?.head;
|
|
55
|
+
|
|
56
|
+
useEffect(() => {
|
|
57
|
+
if (!provider || !active || !surfaceId) return;
|
|
58
|
+
provider.setEditingTarget({
|
|
59
|
+
surfaceId,
|
|
60
|
+
...(fieldId ? { fieldId } : {}),
|
|
61
|
+
...(label ? { label } : {}),
|
|
62
|
+
...(kind ? { kind } : {}),
|
|
63
|
+
...(anchor && head ? { selection: { anchor, head } } : {}),
|
|
64
|
+
});
|
|
65
|
+
return () => provider.setEditingTarget(null);
|
|
66
|
+
}, [provider, active, surfaceId, fieldId, label, kind, anchor, head]);
|
|
67
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
|
|
3
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
4
|
+
import * as Y from "yjs";
|
|
5
|
+
import {
|
|
6
|
+
createLocalAppCrdt,
|
|
7
|
+
decodeRelativePosition,
|
|
8
|
+
encodeRelativePosition,
|
|
9
|
+
type EditingPeer,
|
|
10
|
+
} from "../src/index.js";
|
|
11
|
+
|
|
12
|
+
class MockEventSource {
|
|
13
|
+
static instances: MockEventSource[] = [];
|
|
14
|
+
readonly url: string;
|
|
15
|
+
readonly listeners = new Map<string, Set<(event: MessageEvent) => void>>();
|
|
16
|
+
readonly close = vi.fn();
|
|
17
|
+
|
|
18
|
+
constructor(url: string) {
|
|
19
|
+
this.url = url;
|
|
20
|
+
MockEventSource.instances.push(this);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
addEventListener(type: string, listener: (event: MessageEvent) => void): void {
|
|
24
|
+
const listeners = this.listeners.get(type) ?? new Set();
|
|
25
|
+
listeners.add(listener);
|
|
26
|
+
this.listeners.set(type, listeners);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
emit(type: string, body: unknown): void {
|
|
30
|
+
const event = new MessageEvent(type, { data: JSON.stringify(body) });
|
|
31
|
+
for (const listener of this.listeners.get(type) ?? []) listener(event);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe("LocalAppCrdtProvider", () => {
|
|
36
|
+
afterEach(() => {
|
|
37
|
+
MockEventSource.instances = [];
|
|
38
|
+
vi.unstubAllGlobals();
|
|
39
|
+
vi.restoreAllMocks();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("uploads document edits made before connect and applies remote updates", async () => {
|
|
43
|
+
vi.stubGlobal("EventSource", MockEventSource as unknown as typeof EventSource);
|
|
44
|
+
const serverDoc = new Y.Doc();
|
|
45
|
+
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
46
|
+
const url = String(input);
|
|
47
|
+
if (url.endsWith("/crdt/sync")) return jsonResponse({ success: true, data: { update: "" } });
|
|
48
|
+
if (url.endsWith("/crdt/update")) {
|
|
49
|
+
const body = JSON.parse(String(init?.body));
|
|
50
|
+
Y.applyUpdate(serverDoc, decode(body.update));
|
|
51
|
+
return jsonResponse({ success: true, data: { snapshotBytes: body.update.length, updatedAt: new Date().toISOString() } });
|
|
52
|
+
}
|
|
53
|
+
throw new Error(`Unexpected request: ${url}`);
|
|
54
|
+
});
|
|
55
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
56
|
+
|
|
57
|
+
const localDoc = new Y.Doc();
|
|
58
|
+
localDoc.getText("body").insert(0, "local draft");
|
|
59
|
+
const provider = createLocalAppCrdt({
|
|
60
|
+
resource: "documents",
|
|
61
|
+
documentId: "proposal-1",
|
|
62
|
+
clientId: "window-1",
|
|
63
|
+
basePath: "/serve/alice/editor/api",
|
|
64
|
+
doc: localDoc,
|
|
65
|
+
autoConnect: false,
|
|
66
|
+
awareness: false,
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
70
|
+
await provider.connect();
|
|
71
|
+
expect(provider.status).toBe("connected");
|
|
72
|
+
expect(serverDoc.getText("body").toString()).toBe("local draft");
|
|
73
|
+
expect(MockEventSource.instances[0].url).toContain("/crdt/events?resource=documents&documentId=proposal-1&clientId=window-1");
|
|
74
|
+
|
|
75
|
+
const remoteDoc = new Y.Doc();
|
|
76
|
+
remoteDoc.getText("body").insert(0, "remote ");
|
|
77
|
+
MockEventSource.instances[0].emit("crdt:update", {
|
|
78
|
+
type: "crdt:update",
|
|
79
|
+
data: { clientId: "window-2", update: encode(Y.encodeStateAsUpdate(remoteDoc)) },
|
|
80
|
+
});
|
|
81
|
+
expect(localDoc.getText("body").toString()).toContain("remote ");
|
|
82
|
+
|
|
83
|
+
await provider.destroy();
|
|
84
|
+
expect(MockEventSource.instances[0].close).toHaveBeenCalledOnce();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it("publishes canonical remote editing awareness and clears its lease on destroy", async () => {
|
|
88
|
+
vi.stubGlobal("EventSource", MockEventSource as unknown as typeof EventSource);
|
|
89
|
+
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
|
90
|
+
const url = String(input);
|
|
91
|
+
if (url.endsWith("/crdt/sync")) return jsonResponse({ success: true, data: { update: "" } });
|
|
92
|
+
if (url.endsWith("/crdt/awareness")) return jsonResponse({ success: true, data: { status: "editing" } });
|
|
93
|
+
throw new Error(`Unexpected request: ${url}`);
|
|
94
|
+
});
|
|
95
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
96
|
+
const provider = createLocalAppCrdt({
|
|
97
|
+
resource: "documents",
|
|
98
|
+
documentId: "proposal-2",
|
|
99
|
+
clientId: "window-1",
|
|
100
|
+
basePath: "/serve/alice/editor/api",
|
|
101
|
+
autoConnect: false,
|
|
102
|
+
});
|
|
103
|
+
const received: readonly EditingPeer[][] = [];
|
|
104
|
+
provider.onAwareness((peers) => received.push(peers));
|
|
105
|
+
await provider.connect();
|
|
106
|
+
provider.setEditingTarget({ surfaceId: "proposal:2", fieldId: "title", label: "标题" });
|
|
107
|
+
await vi.waitFor(() => expect(fetchMock.mock.calls.some(([url]) => String(url).endsWith("/crdt/awareness"))).toBe(true));
|
|
108
|
+
|
|
109
|
+
MockEventSource.instances[0].emit("crdt:awareness", {
|
|
110
|
+
type: "crdt:awareness",
|
|
111
|
+
data: {
|
|
112
|
+
peers: [{
|
|
113
|
+
clientId: "window-2",
|
|
114
|
+
clock: 3,
|
|
115
|
+
user: { id: "bob", name: "bob", displayName: "Bob", avatarUrl: null, color: "#2563eb" },
|
|
116
|
+
editing: { surfaceId: "proposal:2", fieldId: "title", label: "标题", kind: "field" },
|
|
117
|
+
overlay: true,
|
|
118
|
+
updatedAt: "2026-08-20T00:00:00.000Z",
|
|
119
|
+
}],
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
expect(received.at(-1)?.[0]).toMatchObject({ clientId: "window-2", user: { id: "bob" }, editing: { fieldId: "title" } });
|
|
123
|
+
|
|
124
|
+
await provider.destroy();
|
|
125
|
+
const awarenessBodies = fetchMock.mock.calls
|
|
126
|
+
.filter(([url]) => String(url).endsWith("/crdt/awareness"))
|
|
127
|
+
.map(([, init]) => JSON.parse(String(init?.body)));
|
|
128
|
+
expect(awarenessBodies.at(-1)?.state).toBeNull();
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it("encodes stable Yjs relative positions and rejects unsafe identifiers", () => {
|
|
132
|
+
const doc = new Y.Doc();
|
|
133
|
+
const text = doc.getText("body");
|
|
134
|
+
text.insert(0, "hello");
|
|
135
|
+
const encoded = encodeRelativePosition(Y.createRelativePositionFromTypeIndex(text, 3));
|
|
136
|
+
const absolute = Y.createAbsolutePositionFromRelativePosition(decodeRelativePosition(encoded), doc);
|
|
137
|
+
expect(absolute?.index).toBe(3);
|
|
138
|
+
|
|
139
|
+
expect(() => createLocalAppCrdt({ resource: "../files", documentId: "doc", autoConnect: false })).toThrow("Invalid CRDT resource");
|
|
140
|
+
expect(() => createLocalAppCrdt({ resource: "documents", documentId: "../doc", autoConnect: false })).toThrow("Invalid CRDT documentId");
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("does not perform network cleanup when an autoConnect=false provider never connected", async () => {
|
|
144
|
+
const fetchMock = vi.fn();
|
|
145
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
146
|
+
const provider = createLocalAppCrdt({
|
|
147
|
+
resource: "documents",
|
|
148
|
+
documentId: "draft-1",
|
|
149
|
+
autoConnect: false,
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
await provider.destroy();
|
|
153
|
+
|
|
154
|
+
expect(provider.status).toBe("destroyed");
|
|
155
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
function jsonResponse(value: unknown): Response {
|
|
160
|
+
return new Response(JSON.stringify(value), { status: 200, headers: { "Content-Type": "application/json" } });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function encode(value: Uint8Array): string {
|
|
164
|
+
return Buffer.from(value).toString("base64url");
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function decode(value: string): Uint8Array {
|
|
168
|
+
return Buffer.from(value, "base64url");
|
|
169
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"module": "ESNext",
|
|
5
|
+
"moduleResolution": "bundler",
|
|
6
|
+
"strict": true,
|
|
7
|
+
"esModuleInterop": true,
|
|
8
|
+
"skipLibCheck": true,
|
|
9
|
+
"declaration": true,
|
|
10
|
+
"declarationMap": true,
|
|
11
|
+
"sourceMap": true,
|
|
12
|
+
"outDir": "dist",
|
|
13
|
+
"rootDir": "src",
|
|
14
|
+
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
|
15
|
+
"jsx": "react-jsx"
|
|
16
|
+
},
|
|
17
|
+
"include": ["src"]
|
|
18
|
+
}
|