@ekrooh/bare 0.6.2 → 0.7.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/README.md +3 -2
- package/dist/errors-Bl5w-m62.mjs +56 -0
- package/dist/events-DUGMT3B9.mjs +40 -0
- package/dist/{index-Do-kTNXw.d.mts → index-B3AmX7mC.d.mts} +35 -146
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +3 -1
- package/dist/{messages-CMNIFMFY.mjs → messages-BxviiFuh.mjs} +182 -73
- package/dist/plugin-BnDh08L_.mjs +111 -0
- package/dist/plugins-discovery-events.d.mts +1 -1
- package/dist/plugins-discovery-events.mjs +1 -1
- package/dist/plugins-health-events.d.mts +1 -1
- package/dist/plugins-health-events.mjs +1 -1
- package/dist/plugins-logs-events.d.mts +2 -1
- package/dist/plugins-logs-events.mjs +1 -1
- package/dist/plugins-media-events.d.mts +1 -1
- package/dist/plugins-media-events.mjs +1 -26
- package/dist/plugins-permissions-events.d.mts +2 -1
- package/dist/plugins-permissions-events.mjs +11 -3
- package/dist/plugins-q6Wno9wN.mjs +77 -0
- package/dist/plugins.d.mts +7 -4
- package/dist/plugins.mjs +1 -1
- package/dist/runtime.d.mts +31 -7
- package/dist/runtime.mjs +657 -124
- package/dist/{static-file-server-COxd-PFR.d.mts → static-file-server-drT1AHqV.d.mts} +26 -4
- package/dist/{store-DTg1jN5E.mjs → store-Bd2wL58k.mjs} +11 -2
- package/dist/sync.d.mts +36 -0
- package/dist/sync.mjs +323 -0
- package/dist/transports.d.mts +28 -1
- package/dist/transports.mjs +332 -168
- package/dist/types-BC39OoZB.d.mts +152 -0
- package/package.json +10 -5
- package/dist/plugins-BnpdCi3A.mjs +0 -156
|
@@ -24,7 +24,10 @@ type LoopbackConnectionHandler = (socket: WebSocketLike, request: LoopbackReques
|
|
|
24
24
|
* strings — `String(uint8array)` would join bytes with commas, so decode
|
|
25
25
|
* explicitly (the `/login` token body must match byte-for-byte). */
|
|
26
26
|
declare function collectRequestBody(req: HTTPIncomingMessage, maxBytes?: number): Promise<string>;
|
|
27
|
-
/** Handler for a registered HTTP route on the loopback server.
|
|
27
|
+
/** Handler for a registered HTTP route on the loopback server. An async
|
|
28
|
+
* handler that rejects is answered with a bare 500, like a throwing one. The
|
|
29
|
+
* return type stays `void`: an async function already fits it, while
|
|
30
|
+
* `void | Promise<void>` would reject the common `(req, res) => res.end()`. */
|
|
28
31
|
type LoopbackRouteHandler = (req: HTTPIncomingMessage, res: HTTPServerResponse) => void;
|
|
29
32
|
interface LoopbackServerOptions {
|
|
30
33
|
/** Bind address. Defaults to `127.0.0.1`. A non-loopback address throws
|
|
@@ -60,6 +63,13 @@ interface LoopbackServerOptions {
|
|
|
60
63
|
* this (to 8x) and then the socket is closed rather than lose one. Defaults to
|
|
61
64
|
* 2 MiB. */
|
|
62
65
|
wsMaxQueuedBytes?: number;
|
|
66
|
+
/** Compare mount roots ignoring case and Unicode normalization, as a
|
|
67
|
+
* case-insensitive filesystem does. Defaults to on for darwin, ios and
|
|
68
|
+
* win32, off for android and linux. */
|
|
69
|
+
foldPathCase?: boolean;
|
|
70
|
+
/** How long the bootstrap nonce stays redeemable after binding, in ms.
|
|
71
|
+
* Defaults to the gate's `BOOTSTRAP_TTL_MS`. */
|
|
72
|
+
bootstrapTtlMs?: number;
|
|
63
73
|
}
|
|
64
74
|
interface LoopbackServer {
|
|
65
75
|
/** Resolves to the server origin (`http://127.0.0.1:<port>`), binding on
|
|
@@ -71,6 +81,12 @@ interface LoopbackServer {
|
|
|
71
81
|
/** The per-session token. The host reads it from `credentials()` for its own
|
|
72
82
|
* `X-Bare-Token` calls and never injects it into the page. */
|
|
73
83
|
token(): string;
|
|
84
|
+
/** Pause/resume the bootstrap nonce's lifetime clock across a worklet
|
|
85
|
+
* suspend. Both are idempotent. Optional in the type so a consumer's own
|
|
86
|
+
* `LoopbackServer` fake keeps compiling; `createLoopbackServer` always
|
|
87
|
+
* provides them. */
|
|
88
|
+
pauseBootstrapClock?(): void;
|
|
89
|
+
resumeBootstrapClock?(): void;
|
|
74
90
|
/** Resolves to the bound origin, port, token and the one-time bootstrap
|
|
75
91
|
* nonce (empty once spent). The host injects `bootstrap` into the page (not
|
|
76
92
|
* the token); the page exchanges it once via `POST /login` for the HttpOnly
|
|
@@ -90,7 +106,8 @@ interface LoopbackServer {
|
|
|
90
106
|
* `{ public: true }` to mark a mount as world-readable bootstrap content
|
|
91
107
|
* served before auth; a non-public directory mount gates every request
|
|
92
108
|
* behind the session. A request never resolves outside `dirPath`, symlinks
|
|
93
|
-
* included.
|
|
109
|
+
* included. Throws when a public and a gated mount's directories contain
|
|
110
|
+
* one another. */
|
|
94
111
|
mountDir(prefix: string, dirPath: string, opts?: {
|
|
95
112
|
public?: boolean;
|
|
96
113
|
}): void;
|
|
@@ -98,8 +115,13 @@ interface LoopbackServer {
|
|
|
98
115
|
* (the protocol socket). */
|
|
99
116
|
onConnection(handler: LoopbackConnectionHandler): void;
|
|
100
117
|
/** Registers an HTTP route. `handler` runs before mount resolution, after
|
|
101
|
-
* the auth gate (device mode requires the session cookie/token).
|
|
102
|
-
*
|
|
118
|
+
* the auth gate (device mode requires the session cookie/token). `path` is
|
|
119
|
+
* normalized like a mount path (decoded, trailing slash dropped). The
|
|
120
|
+
* response starts with `Referrer-Policy`, `X-Content-Type-Options` (and
|
|
121
|
+
* `Cross-Origin-Resource-Policy` unless extra `allowedOrigins` are configured)
|
|
122
|
+
* already set; a handler that
|
|
123
|
+
* throws or rejects is answered with a bare 500. Read the body with
|
|
124
|
+
* `collectRequestBody`, passing a byte cap. */
|
|
103
125
|
registerRoute(method: string, path: string, handler: LoopbackRouteHandler): void;
|
|
104
126
|
/** Writes a raw frame to the connected protocol socket (if any) — the
|
|
105
127
|
* server-initiated push seam (e.g. a `photos.changed` dispatch). */
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
// core/logs/store.ts
|
|
2
|
+
/** How many of `available` entries a `tail` asks for. Omitted means all and
|
|
3
|
+
* `Infinity` all there is; a fraction rounds down. Anything else that is not a
|
|
4
|
+
* non-negative number (`NaN`, a negative, a string from an unchecked caller)
|
|
5
|
+
* asks for none: `Math.min(NaN, n)` is `NaN`, and `slice(NaN)` would return
|
|
6
|
+
* the whole ring, so an invalid tail must never mean "everything". */
|
|
7
|
+
function tailCount(tail, available) {
|
|
8
|
+
if (tail === void 0) return available;
|
|
9
|
+
if (typeof tail !== "number" || Number.isNaN(tail) || tail <= 0) return 0;
|
|
10
|
+
return Math.min(Math.floor(tail), available);
|
|
11
|
+
}
|
|
2
12
|
/** Bounded FIFO log buffer. Newest entries are retained; the oldest are
|
|
3
13
|
* dropped once `capacity` is exceeded. `seq` is a monotonic counter assigned
|
|
4
14
|
* on append and shared across every source, so read-back stays ordered. */
|
|
@@ -34,8 +44,7 @@ function createLogRingBuffer(capacity) {
|
|
|
34
44
|
view(options = {}) {
|
|
35
45
|
const { tail, level, source } = options;
|
|
36
46
|
const filtered = ordered().filter((e) => (level === void 0 || e.level === level) && (source === void 0 || e.source === source));
|
|
37
|
-
|
|
38
|
-
return filtered.slice(filtered.length - count);
|
|
47
|
+
return filtered.slice(filtered.length - tailCount(tail, filtered.length));
|
|
39
48
|
},
|
|
40
49
|
clear() {
|
|
41
50
|
const cleared = size;
|
package/dist/sync.d.mts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { a as Either, n as CoreError } from "./types-BC39OoZB.mjs";
|
|
2
|
+
type SyncOptions<T> = {
|
|
3
|
+
/** Existing directory for this device's sync identity and current room.
|
|
4
|
+
* Pass `runtime.config.storage`. Without it (or if it is missing/unwritable)
|
|
5
|
+
* identity and room live in memory and a restart starts a new room. */
|
|
6
|
+
storage?: string;
|
|
7
|
+
/** Validates a peer's value. Return the typed value, or undefined to drop
|
|
8
|
+
* it. Required. */
|
|
9
|
+
parse: (raw: unknown) => T | undefined;
|
|
10
|
+
};
|
|
11
|
+
type SyncValue<T> = {
|
|
12
|
+
peer: string;
|
|
13
|
+
self: boolean;
|
|
14
|
+
value: T;
|
|
15
|
+
};
|
|
16
|
+
interface Sync<T> {
|
|
17
|
+
/** This device's current room code: 32 lowercase hex chars. */
|
|
18
|
+
invite(): string;
|
|
19
|
+
/** Leave the current room and join the one named by `code`. */
|
|
20
|
+
join(code: string): Either<CoreError, true>;
|
|
21
|
+
/** Replace this device's value and send it to every connected device. */
|
|
22
|
+
publish(value: T): Either<CoreError, true>;
|
|
23
|
+
/** Latest value of every device seen in this room: self first, then by peer id. */
|
|
24
|
+
values(): SyncValue<T>[];
|
|
25
|
+
/** Devices connected right now (not counting this one). */
|
|
26
|
+
connected(): number;
|
|
27
|
+
/** Called after a peer value changes, a device connects or disconnects, or
|
|
28
|
+
* join() succeeds. Returns unsubscribe. */
|
|
29
|
+
onChange(listener: () => void): () => void;
|
|
30
|
+
close(): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
/** Peer-to-peer sync of one JSON value per device. Each device publishes its
|
|
33
|
+
* own value; `values()` returns the latest value of every device in the room.
|
|
34
|
+
* Worklet only. */
|
|
35
|
+
export declare function createSync<T>(options: SyncOptions<T>): Either<CoreError, Sync<T>>;
|
|
36
|
+
export type { Sync, SyncOptions, SyncValue };
|
package/dist/sync.mjs
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { n as err, r as ok } from "./errors-Bl5w-m62.mjs";
|
|
2
|
+
import fs from "bare-fs";
|
|
3
|
+
import path from "bare-path";
|
|
4
|
+
import crypto from "bare-crypto";
|
|
5
|
+
import Hyperswarm from "hyperswarm";
|
|
6
|
+
// core/sync/invite.ts
|
|
7
|
+
const INVITE_PATTERN = /^[0-9a-f]{32}$/;
|
|
8
|
+
/** A fresh room code: 16 random bytes as 32 lowercase hex characters. */
|
|
9
|
+
function createInviteCode() {
|
|
10
|
+
return Buffer.from(crypto.randomBytes(16)).toString("hex");
|
|
11
|
+
}
|
|
12
|
+
/** Normalises pasted text (trim, lowercase) and checks its shape. */
|
|
13
|
+
function parseInviteCode(text) {
|
|
14
|
+
const code = typeof text === "string" ? text.trim().toLowerCase() : "";
|
|
15
|
+
if (!INVITE_PATTERN.test(code)) return err("sync/bad-invite", "Invite codes are 32 letters and digits (0-9, a-f). Copy the whole code from the other device.");
|
|
16
|
+
return ok(code);
|
|
17
|
+
}
|
|
18
|
+
/** DHT topic for a room: the code itself never reaches the network. */
|
|
19
|
+
function topicForInvite(code) {
|
|
20
|
+
return Buffer.from(crypto.createHash("sha-256").update(`ekrooh/sync/v1\n${code}`).digest());
|
|
21
|
+
}
|
|
22
|
+
// core/sync/sync-state-file.ts
|
|
23
|
+
const FILE_NAME = "ekrooh-sync.json";
|
|
24
|
+
const SEED_PATTERN = /^[0-9a-f]{64}$/;
|
|
25
|
+
const ROOM_PATTERN = /^[0-9a-f]{32}$/;
|
|
26
|
+
function freshState() {
|
|
27
|
+
return {
|
|
28
|
+
version: 1,
|
|
29
|
+
seed: Buffer.from(crypto.randomBytes(32)).toString("hex"),
|
|
30
|
+
room: createInviteCode()
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function readRaw(file) {
|
|
34
|
+
try {
|
|
35
|
+
return {
|
|
36
|
+
found: true,
|
|
37
|
+
text: fs.readFileSync(file, "utf8")
|
|
38
|
+
};
|
|
39
|
+
} catch {
|
|
40
|
+
return {
|
|
41
|
+
found: false,
|
|
42
|
+
text: ""
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** Reads (or creates) the device's sync identity and room. Without a storage
|
|
47
|
+
* directory, or when it is unwritable, the state lives in memory. */
|
|
48
|
+
function loadSyncState(storage) {
|
|
49
|
+
if (storage === void 0 || storage === "") return ok(freshState());
|
|
50
|
+
const file = path.join(storage, FILE_NAME);
|
|
51
|
+
const raw = readRaw(file);
|
|
52
|
+
if (raw.found) {
|
|
53
|
+
let parsed;
|
|
54
|
+
try {
|
|
55
|
+
parsed = JSON.parse(raw.text);
|
|
56
|
+
} catch {
|
|
57
|
+
parsed = void 0;
|
|
58
|
+
}
|
|
59
|
+
const record = typeof parsed === "object" && parsed !== null ? parsed : void 0;
|
|
60
|
+
if (record !== void 0 && typeof record.version === "number" && record.version > 1) return err("sync/state-version", `${file} was written by a newer @ekrooh/bare. Update @ekrooh/bare.`);
|
|
61
|
+
if (record !== void 0 && record.version === 1 && typeof record.seed === "string" && SEED_PATTERN.test(record.seed) && typeof record.room === "string" && ROOM_PATTERN.test(record.room)) return ok({
|
|
62
|
+
version: 1,
|
|
63
|
+
seed: record.seed,
|
|
64
|
+
room: record.room
|
|
65
|
+
});
|
|
66
|
+
console.warn(`[sync] ${file} is unreadable; starting a new identity and room`);
|
|
67
|
+
}
|
|
68
|
+
const state = freshState();
|
|
69
|
+
saveSyncState(storage, state);
|
|
70
|
+
return ok(state);
|
|
71
|
+
}
|
|
72
|
+
let warnedWrite = false;
|
|
73
|
+
/** Writes the state through a tmp file + rename. Returns false (after one
|
|
74
|
+
* warning) when the write fails; callers carry on in memory. */
|
|
75
|
+
function saveSyncState(storage, state) {
|
|
76
|
+
if (storage === void 0 || storage === "") return false;
|
|
77
|
+
const file = path.join(storage, FILE_NAME);
|
|
78
|
+
const tmp = `${file}.tmp`;
|
|
79
|
+
try {
|
|
80
|
+
fs.writeFileSync(tmp, JSON.stringify(state));
|
|
81
|
+
fs.renameSync(tmp, file);
|
|
82
|
+
return true;
|
|
83
|
+
} catch {
|
|
84
|
+
if (!warnedWrite) {
|
|
85
|
+
warnedWrite = true;
|
|
86
|
+
console.warn(`[sync] could not write ${file}; continuing in memory`);
|
|
87
|
+
}
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** Largest line a peer may send before the connection is dropped. */
|
|
92
|
+
const MAX_LINE_BYTES = 32768;
|
|
93
|
+
/** One wire line: `{"v":1,"value":<json>}\n`. */
|
|
94
|
+
function encodeSyncLine(value) {
|
|
95
|
+
let json;
|
|
96
|
+
try {
|
|
97
|
+
json = JSON.stringify({
|
|
98
|
+
v: 1,
|
|
99
|
+
value
|
|
100
|
+
});
|
|
101
|
+
} catch {
|
|
102
|
+
json = void 0;
|
|
103
|
+
}
|
|
104
|
+
if (json === void 0 || JSON.stringify(value) === void 0) return err("sync/not-json", "Sync values must be JSON.");
|
|
105
|
+
const line = `${json}\n`;
|
|
106
|
+
if (Buffer.byteLength(line) > 16384) return err("sync/value-too-large", "Sync values must be under 16 KiB of JSON.");
|
|
107
|
+
return ok(line);
|
|
108
|
+
}
|
|
109
|
+
/** Splits a byte stream into lines. A line longer than `maxBytes` without a
|
|
110
|
+
* newline calls `onOverflow` once and the reader goes quiet. */
|
|
111
|
+
function createLineReader(options) {
|
|
112
|
+
let pending = Buffer.alloc(0);
|
|
113
|
+
let dead = false;
|
|
114
|
+
return { push(chunk) {
|
|
115
|
+
if (dead) return;
|
|
116
|
+
pending = Buffer.concat([pending, Buffer.from(chunk)]);
|
|
117
|
+
for (;;) {
|
|
118
|
+
const end = pending.indexOf(10);
|
|
119
|
+
if (end === -1) break;
|
|
120
|
+
const line = pending.subarray(0, end).toString("utf8");
|
|
121
|
+
pending = pending.subarray(end + 1);
|
|
122
|
+
if (line.length > 0) options.onLine(line);
|
|
123
|
+
}
|
|
124
|
+
if (pending.length > options.maxBytes) {
|
|
125
|
+
dead = true;
|
|
126
|
+
pending = Buffer.alloc(0);
|
|
127
|
+
options.onOverflow();
|
|
128
|
+
}
|
|
129
|
+
} };
|
|
130
|
+
}
|
|
131
|
+
// core/sync/sync-engine.ts
|
|
132
|
+
/** Most devices a room remembers; matches the swarm's maxPeers. */
|
|
133
|
+
const MAX_PEERS = 16;
|
|
134
|
+
const hex = (bytes) => Buffer.from(bytes).toString("hex");
|
|
135
|
+
function createSyncWith(options, deps) {
|
|
136
|
+
const [stateError, state] = loadSyncState(options.storage);
|
|
137
|
+
if (stateError !== null) return [stateError, null];
|
|
138
|
+
const swarm = deps.createSwarm(Buffer.from(state.seed, "hex"));
|
|
139
|
+
const selfId = hex(swarm.keyPair.publicKey);
|
|
140
|
+
const peers = /* @__PURE__ */ new Map();
|
|
141
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
142
|
+
let room = state.room;
|
|
143
|
+
let topic = topicForInvite(room);
|
|
144
|
+
let selfLine;
|
|
145
|
+
let selfValue;
|
|
146
|
+
let closed = false;
|
|
147
|
+
const fire = () => {
|
|
148
|
+
for (const listener of [...listeners]) try {
|
|
149
|
+
listener();
|
|
150
|
+
} catch (error) {
|
|
151
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
152
|
+
console.warn(`[sync] onChange listener failed: ${message}`);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const connected = () => {
|
|
156
|
+
let count = 0;
|
|
157
|
+
for (const peer of peers.values()) if (peer.conns.size > 0) count++;
|
|
158
|
+
return count;
|
|
159
|
+
};
|
|
160
|
+
const peerFor = (id) => {
|
|
161
|
+
const existing = peers.get(id);
|
|
162
|
+
if (existing !== void 0) return existing;
|
|
163
|
+
const created = {
|
|
164
|
+
conns: /* @__PURE__ */ new Set(),
|
|
165
|
+
raw: void 0,
|
|
166
|
+
value: void 0,
|
|
167
|
+
warned: /* @__PURE__ */ new Set()
|
|
168
|
+
};
|
|
169
|
+
peers.set(id, created);
|
|
170
|
+
return created;
|
|
171
|
+
};
|
|
172
|
+
const prune = () => {
|
|
173
|
+
for (const [id, peer] of peers) {
|
|
174
|
+
if (peers.size <= MAX_PEERS) return;
|
|
175
|
+
if (peer.conns.size === 0) peers.delete(id);
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
const warnOnce = (peer, key, message) => {
|
|
179
|
+
if (peer.warned.has(key)) return;
|
|
180
|
+
peer.warned.add(key);
|
|
181
|
+
console.warn(message);
|
|
182
|
+
};
|
|
183
|
+
const joinTopic = () => {
|
|
184
|
+
swarm.join(topic, {
|
|
185
|
+
server: true,
|
|
186
|
+
client: true
|
|
187
|
+
});
|
|
188
|
+
console.log(`[sync] in room ${room.slice(0, 4)}…`);
|
|
189
|
+
};
|
|
190
|
+
swarm.on("error", () => {});
|
|
191
|
+
swarm.on("connection", (conn) => {
|
|
192
|
+
conn.on("error", () => {});
|
|
193
|
+
const id = hex(conn.remotePublicKey);
|
|
194
|
+
if (closed || id === selfId) {
|
|
195
|
+
conn.destroy();
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const short = id.slice(0, 8);
|
|
199
|
+
const peer = peerFor(id);
|
|
200
|
+
peer.conns.add(conn);
|
|
201
|
+
console.log(`[sync] peer ${short} connected (${connected()} connected)`);
|
|
202
|
+
if (selfLine !== void 0) conn.write(selfLine);
|
|
203
|
+
const reader = createLineReader({
|
|
204
|
+
maxBytes: MAX_LINE_BYTES,
|
|
205
|
+
onOverflow: () => {
|
|
206
|
+
console.warn(`[sync] peer ${short} sent an oversized message; disconnected`);
|
|
207
|
+
conn.destroy();
|
|
208
|
+
},
|
|
209
|
+
onLine: (line) => {
|
|
210
|
+
if (!peer.conns.has(conn)) return;
|
|
211
|
+
let message;
|
|
212
|
+
try {
|
|
213
|
+
message = JSON.parse(line);
|
|
214
|
+
} catch {
|
|
215
|
+
warnOnce(peer, "json", `[sync] peer ${short} sent a bad message`);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const record = typeof message === "object" && message !== null ? message : {};
|
|
219
|
+
if (record.v !== 1) {
|
|
220
|
+
warnOnce(peer, "version", `[sync] peer ${short} uses sync v${String(record.v)}; update @ekrooh/bare on both devices`);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
let parsed;
|
|
224
|
+
try {
|
|
225
|
+
parsed = options.parse(record.value);
|
|
226
|
+
} catch {
|
|
227
|
+
parsed = void 0;
|
|
228
|
+
}
|
|
229
|
+
if (parsed === void 0) {
|
|
230
|
+
warnOnce(peer, "parse", `[sync] peer ${short} sent a value this app does not accept`);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
if (peer.raw === line) return;
|
|
234
|
+
peer.raw = line;
|
|
235
|
+
peer.value = parsed;
|
|
236
|
+
fire();
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
conn.on("data", (chunk) => reader.push(chunk));
|
|
240
|
+
conn.on("close", () => {
|
|
241
|
+
if (!peer.conns.delete(conn)) return;
|
|
242
|
+
console.log(`[sync] peer ${short} disconnected (${connected()} connected)`);
|
|
243
|
+
prune();
|
|
244
|
+
fire();
|
|
245
|
+
});
|
|
246
|
+
fire();
|
|
247
|
+
});
|
|
248
|
+
joinTopic();
|
|
249
|
+
return ok({
|
|
250
|
+
invite: () => room,
|
|
251
|
+
join(code) {
|
|
252
|
+
if (closed) return err("sync/closed", "This sync was closed.");
|
|
253
|
+
const [error, next] = parseInviteCode(code);
|
|
254
|
+
if (error !== null) return [error, null];
|
|
255
|
+
if (next === room) return ok(true);
|
|
256
|
+
Promise.resolve(swarm.leave(topic)).catch(() => {});
|
|
257
|
+
const old = [...peers.values()].flatMap((p) => [...p.conns]);
|
|
258
|
+
for (const peer of peers.values()) peer.conns.clear();
|
|
259
|
+
peers.clear();
|
|
260
|
+
for (const conn of old) conn.destroy();
|
|
261
|
+
room = next;
|
|
262
|
+
topic = topicForInvite(room);
|
|
263
|
+
saveSyncState(options.storage, {
|
|
264
|
+
...state,
|
|
265
|
+
room
|
|
266
|
+
});
|
|
267
|
+
joinTopic();
|
|
268
|
+
fire();
|
|
269
|
+
return ok(true);
|
|
270
|
+
},
|
|
271
|
+
publish(value) {
|
|
272
|
+
if (closed) return err("sync/closed", "This sync was closed.");
|
|
273
|
+
const [error, line] = encodeSyncLine(value);
|
|
274
|
+
if (error !== null) return [error, null];
|
|
275
|
+
selfLine = line;
|
|
276
|
+
selfValue = value;
|
|
277
|
+
for (const peer of peers.values()) for (const conn of peer.conns) conn.write(line);
|
|
278
|
+
return ok(true);
|
|
279
|
+
},
|
|
280
|
+
values() {
|
|
281
|
+
const out = [];
|
|
282
|
+
if (selfValue !== void 0) out.push({
|
|
283
|
+
peer: selfId,
|
|
284
|
+
self: true,
|
|
285
|
+
value: selfValue
|
|
286
|
+
});
|
|
287
|
+
const ids = [...peers.keys()].sort();
|
|
288
|
+
for (const id of ids) {
|
|
289
|
+
const value = peers.get(id)?.value;
|
|
290
|
+
if (value !== void 0) out.push({
|
|
291
|
+
peer: id,
|
|
292
|
+
self: false,
|
|
293
|
+
value
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
return out;
|
|
297
|
+
},
|
|
298
|
+
connected,
|
|
299
|
+
onChange(listener) {
|
|
300
|
+
listeners.add(listener);
|
|
301
|
+
return () => {
|
|
302
|
+
listeners.delete(listener);
|
|
303
|
+
};
|
|
304
|
+
},
|
|
305
|
+
async close() {
|
|
306
|
+
if (closed) return;
|
|
307
|
+
closed = true;
|
|
308
|
+
listeners.clear();
|
|
309
|
+
await Promise.resolve(swarm.destroy()).catch(() => {});
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
// core/sync/create-sync.ts
|
|
314
|
+
/** Peer-to-peer sync of one JSON value per device. Each device publishes its
|
|
315
|
+
* own value; `values()` returns the latest value of every device in the room.
|
|
316
|
+
* Worklet only. */
|
|
317
|
+
function createSync(options) {
|
|
318
|
+
return createSyncWith(options, { createSwarm: (seed) => new Hyperswarm({
|
|
319
|
+
seed,
|
|
320
|
+
maxPeers: 16
|
|
321
|
+
}) });
|
|
322
|
+
}
|
|
323
|
+
export { createSync };
|
package/dist/transports.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { E as MessageTypeValue, f as MessageHeader, x as WireMessage } from "./types-BC39OoZB.mjs";
|
|
2
2
|
declare global {
|
|
3
3
|
interface Window {
|
|
4
4
|
/** Per-session bridge state injected by the embedding shell on-device.
|
|
@@ -29,11 +29,38 @@ interface CreateWebSocketTransportOptions {
|
|
|
29
29
|
/** How long to wait for `/login` before treating it as failed. Default
|
|
30
30
|
* 2000ms. Exposed so tests can exercise the timeout without waiting. */
|
|
31
31
|
loginTimeoutMs?: number;
|
|
32
|
+
/** A client that never connected gives up only after this long (ms), so
|
|
33
|
+
* unlucky jitter cannot exhaust the retries in a few milliseconds. Default
|
|
34
|
+
* 10s. */
|
|
35
|
+
minBootWindowMs?: number;
|
|
36
|
+
/** How long (ms) a socket may stay connecting before it is dropped and
|
|
37
|
+
* retried. Default 10s. */
|
|
38
|
+
openTimeoutMs?: number;
|
|
39
|
+
/** Requests held while connecting; past it, new requests fail fast with
|
|
40
|
+
* `TRANSPORT_ERROR`. Default 256. */
|
|
41
|
+
maxQueued?: number;
|
|
42
|
+
/** Fold the server's recent `[loopback]` upgrade-rejection log lines into
|
|
43
|
+
* the give-up error text. Off by default: log lines are diagnostics, not
|
|
44
|
+
* error messages a UI should show. Turn it on in a diagnostic harness. */
|
|
45
|
+
diagnostics?: boolean;
|
|
32
46
|
}
|
|
33
47
|
interface MessageTransport {
|
|
34
48
|
send(type: MessageTypeValue, header: MessageHeader, payload?: Uint8Array | ArrayBuffer | string | null): void;
|
|
35
49
|
subscribe(handler: (message: WireMessage) => void): () => void;
|
|
50
|
+
/** Closes the transport for good: drops the socket, stops reconnecting,
|
|
51
|
+
* removes its listeners and fails every pending request with
|
|
52
|
+
* `TRANSPORT_ERROR`. Later sends fail the same way. Optional so existing
|
|
53
|
+
* custom transports still satisfy the interface. */
|
|
54
|
+
close?(): void;
|
|
36
55
|
}
|
|
37
56
|
export declare function createWebSocketTransport(urlOrOptions?: string | CreateWebSocketTransportOptions): MessageTransport;
|
|
57
|
+
/**
|
|
58
|
+
* Deterministic in-process transport for tests and browser dev. Requests are
|
|
59
|
+
* routed through the real plugin kernel and the real `core.health`,
|
|
60
|
+
* `core.discovery`, `core.logs` and `core.permissions` manifests, so argument
|
|
61
|
+
* checks, unsupported-event errors and discovery match the worklet. Only the
|
|
62
|
+
* host (permission handlers) and `vendor.media` (no native picker, no
|
|
63
|
+
* loopback server: a `data:` URL) are stand-ins.
|
|
64
|
+
*/
|
|
38
65
|
export declare function createMockTransport(): MessageTransport;
|
|
39
66
|
export type { MessageTransport };
|