@ekrooh/bare 0.6.2 → 0.8.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.
@@ -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). The route
102
- * body is read with `collectRequestBody`. */
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
- const count = tail === void 0 ? filtered.length : Math.min(tail, filtered.length);
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;
@@ -0,0 +1,40 @@
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, current room and
4
+ * last published value. Pass `runtime.config.storage`. Without it (or if it
5
+ * is missing/unwritable) identity and room live in memory and a restart
6
+ * starts a new room. */
7
+ storage?: string;
8
+ /** Validates a peer's value. Return the typed value, or undefined to drop
9
+ * it. Required. */
10
+ parse: (raw: unknown) => T | undefined;
11
+ };
12
+ type SyncValue<T> = {
13
+ peer: string;
14
+ self: boolean;
15
+ value: T;
16
+ };
17
+ interface Sync<T> {
18
+ /** This device's current room code: 32 lowercase hex chars. */
19
+ invite(): string;
20
+ /** Leave the current room and join the one named by `code`. */
21
+ join(code: string): Either<CoreError, true>;
22
+ /** Replace this device's value, save it when `storage` is set, and send it
23
+ * to every connected device. Returns `sync/save-failed` and changes nothing
24
+ * when the save fails. */
25
+ publish(value: T): Either<CoreError, true>;
26
+ /** Latest value of every device seen in this room: self first, then by peer
27
+ * id. This device's own value is kept across restarts when `storage` is set. */
28
+ values(): SyncValue<T>[];
29
+ /** Devices connected right now (not counting this one). */
30
+ connected(): number;
31
+ /** Called after a peer value changes, a device connects or disconnects, or
32
+ * join() succeeds. Returns unsubscribe. */
33
+ onChange(listener: () => void): () => void;
34
+ close(): Promise<void>;
35
+ }
36
+ /** Peer-to-peer sync of one JSON value per device. Each device publishes its
37
+ * own value; `values()` returns the latest value of every device in the room.
38
+ * Worklet only. */
39
+ export declare function createSync<T>(options: SyncOptions<T>): Either<CoreError, Sync<T>>;
40
+ export type { Sync, SyncOptions, SyncValue };
package/dist/sync.mjs ADDED
@@ -0,0 +1,372 @@
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$1 = "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$1);
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$1);
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
+ // core/sync/sync-values-file.ts
92
+ const FILE_NAME = "ekrooh-sync-values.json";
93
+ /** Reads this device's last published value. Missing, unreadable or rejected
94
+ * values give undefined (one warning when a file existed but is unusable). */
95
+ function loadSelfValue(storage, parse) {
96
+ if (storage === void 0 || storage === "") return void 0;
97
+ const file = path.join(storage, FILE_NAME);
98
+ let text;
99
+ try {
100
+ text = fs.readFileSync(file, "utf8");
101
+ } catch (error) {
102
+ if (error.code !== "ENOENT") console.warn(`[sync] could not read ${file}; starting without it`);
103
+ return;
104
+ }
105
+ let value;
106
+ try {
107
+ const record = JSON.parse(text);
108
+ if (record.version === 1) value = parse(record.self);
109
+ } catch {
110
+ value = void 0;
111
+ }
112
+ if (value === void 0) console.warn(`[sync] ${file} is unreadable; starting without it`);
113
+ return value;
114
+ }
115
+ /** Writes this device's value through a tmp file + rename. Without a storage
116
+ * directory nothing is written (in memory by design). */
117
+ function saveSelfValue(storage, value) {
118
+ if (storage === void 0 || storage === "") return ok(true);
119
+ const file = path.join(storage, FILE_NAME);
120
+ const tmp = `${file}.tmp`;
121
+ try {
122
+ fs.writeFileSync(tmp, JSON.stringify({
123
+ version: 1,
124
+ self: value
125
+ }));
126
+ fs.renameSync(tmp, file);
127
+ return ok(true);
128
+ } catch (error) {
129
+ const reason = error instanceof Error ? error.message : String(error);
130
+ return err("sync/save-failed", `Could not save ${file}: ${reason}`);
131
+ }
132
+ }
133
+ /** Largest line a peer may send before the connection is dropped. */
134
+ const MAX_LINE_BYTES = 32768;
135
+ /** One wire line: `{"v":1,"value":<json>}\n`. */
136
+ function encodeSyncLine(value) {
137
+ let json;
138
+ try {
139
+ json = JSON.stringify({
140
+ v: 1,
141
+ value
142
+ });
143
+ } catch {
144
+ json = void 0;
145
+ }
146
+ if (json === void 0 || JSON.stringify(value) === void 0) return err("sync/not-json", "Sync values must be JSON.");
147
+ const line = `${json}\n`;
148
+ if (Buffer.byteLength(line) > 16384) return err("sync/value-too-large", "Sync values must be under 16 KiB of JSON.");
149
+ return ok(line);
150
+ }
151
+ /** Splits a byte stream into lines. A line longer than `maxBytes` without a
152
+ * newline calls `onOverflow` once and the reader goes quiet. */
153
+ function createLineReader(options) {
154
+ let pending = Buffer.alloc(0);
155
+ let dead = false;
156
+ return { push(chunk) {
157
+ if (dead) return;
158
+ pending = Buffer.concat([pending, Buffer.from(chunk)]);
159
+ for (;;) {
160
+ const end = pending.indexOf(10);
161
+ if (end === -1) break;
162
+ const line = pending.subarray(0, end).toString("utf8");
163
+ pending = pending.subarray(end + 1);
164
+ if (line.length > 0) options.onLine(line);
165
+ }
166
+ if (pending.length > options.maxBytes) {
167
+ dead = true;
168
+ pending = Buffer.alloc(0);
169
+ options.onOverflow();
170
+ }
171
+ } };
172
+ }
173
+ // core/sync/sync-engine.ts
174
+ /** Most devices a room remembers; matches the swarm's maxPeers. */
175
+ const MAX_PEERS = 16;
176
+ const hex = (bytes) => Buffer.from(bytes).toString("hex");
177
+ function createSyncWith(options, deps) {
178
+ const [stateError, state] = loadSyncState(options.storage);
179
+ if (stateError !== null) return [stateError, null];
180
+ const swarm = deps.createSwarm(Buffer.from(state.seed, "hex"));
181
+ const selfId = hex(swarm.keyPair.publicKey);
182
+ const peers = /* @__PURE__ */ new Map();
183
+ const listeners = /* @__PURE__ */ new Set();
184
+ let room = state.room;
185
+ let topic = topicForInvite(room);
186
+ let selfLine;
187
+ let selfValue = loadSelfValue(options.storage, options.parse);
188
+ if (selfValue !== void 0) {
189
+ const [encodeError, line] = encodeSyncLine(selfValue);
190
+ if (encodeError === null) selfLine = line;
191
+ else selfValue = void 0;
192
+ }
193
+ let closed = false;
194
+ const fire = () => {
195
+ for (const listener of [...listeners]) try {
196
+ listener();
197
+ } catch (error) {
198
+ const message = error instanceof Error ? error.message : String(error);
199
+ console.warn(`[sync] onChange listener failed: ${message}`);
200
+ }
201
+ };
202
+ const connected = () => {
203
+ let count = 0;
204
+ for (const peer of peers.values()) if (peer.conns.size > 0) count++;
205
+ return count;
206
+ };
207
+ const peerFor = (id) => {
208
+ const existing = peers.get(id);
209
+ if (existing !== void 0) return existing;
210
+ const created = {
211
+ conns: /* @__PURE__ */ new Set(),
212
+ raw: void 0,
213
+ value: void 0,
214
+ warned: /* @__PURE__ */ new Set()
215
+ };
216
+ peers.set(id, created);
217
+ return created;
218
+ };
219
+ const prune = () => {
220
+ for (const [id, peer] of peers) {
221
+ if (peers.size <= MAX_PEERS) return;
222
+ if (peer.conns.size === 0) peers.delete(id);
223
+ }
224
+ };
225
+ const warnOnce = (peer, key, message) => {
226
+ if (peer.warned.has(key)) return;
227
+ peer.warned.add(key);
228
+ console.warn(message);
229
+ };
230
+ const joinTopic = () => {
231
+ swarm.join(topic, {
232
+ server: true,
233
+ client: true
234
+ });
235
+ console.log(`[sync] in room ${room.slice(0, 4)}…`);
236
+ };
237
+ swarm.on("error", () => {});
238
+ swarm.on("connection", (conn) => {
239
+ conn.on("error", () => {});
240
+ const id = hex(conn.remotePublicKey);
241
+ if (closed || id === selfId) {
242
+ conn.destroy();
243
+ return;
244
+ }
245
+ const short = id.slice(0, 8);
246
+ const peer = peerFor(id);
247
+ peer.conns.add(conn);
248
+ console.log(`[sync] peer ${short} connected (${connected()} connected)`);
249
+ if (selfLine !== void 0) conn.write(selfLine);
250
+ const reader = createLineReader({
251
+ maxBytes: MAX_LINE_BYTES,
252
+ onOverflow: () => {
253
+ console.warn(`[sync] peer ${short} sent an oversized message; disconnected`);
254
+ conn.destroy();
255
+ },
256
+ onLine: (line) => {
257
+ if (!peer.conns.has(conn)) return;
258
+ let message;
259
+ try {
260
+ message = JSON.parse(line);
261
+ } catch {
262
+ warnOnce(peer, "json", `[sync] peer ${short} sent a bad message`);
263
+ return;
264
+ }
265
+ const record = typeof message === "object" && message !== null ? message : {};
266
+ if (record.v !== 1) {
267
+ warnOnce(peer, "version", `[sync] peer ${short} uses sync v${String(record.v)}; update @ekrooh/bare on both devices`);
268
+ return;
269
+ }
270
+ let parsed;
271
+ try {
272
+ parsed = options.parse(record.value);
273
+ } catch {
274
+ parsed = void 0;
275
+ }
276
+ if (parsed === void 0) {
277
+ warnOnce(peer, "parse", `[sync] peer ${short} sent a value this app does not accept`);
278
+ return;
279
+ }
280
+ if (peer.raw === line) return;
281
+ peer.raw = line;
282
+ peer.value = parsed;
283
+ fire();
284
+ }
285
+ });
286
+ conn.on("data", (chunk) => reader.push(chunk));
287
+ conn.on("close", () => {
288
+ if (!peer.conns.delete(conn)) return;
289
+ console.log(`[sync] peer ${short} disconnected (${connected()} connected)`);
290
+ prune();
291
+ fire();
292
+ });
293
+ fire();
294
+ });
295
+ joinTopic();
296
+ return ok({
297
+ invite: () => room,
298
+ join(code) {
299
+ if (closed) return err("sync/closed", "This sync was closed.");
300
+ const [error, next] = parseInviteCode(code);
301
+ if (error !== null) return [error, null];
302
+ if (next === room) return ok(true);
303
+ Promise.resolve(swarm.leave(topic)).catch(() => {});
304
+ const old = [...peers.values()].flatMap((p) => [...p.conns]);
305
+ for (const peer of peers.values()) peer.conns.clear();
306
+ peers.clear();
307
+ for (const conn of old) conn.destroy();
308
+ room = next;
309
+ topic = topicForInvite(room);
310
+ saveSyncState(options.storage, {
311
+ ...state,
312
+ room
313
+ });
314
+ joinTopic();
315
+ fire();
316
+ return ok(true);
317
+ },
318
+ publish(value) {
319
+ if (closed) return err("sync/closed", "This sync was closed.");
320
+ const [error, line] = encodeSyncLine(value);
321
+ if (error !== null) return [error, null];
322
+ const [saveError] = saveSelfValue(options.storage, value);
323
+ if (saveError !== null) return [saveError, null];
324
+ selfLine = line;
325
+ selfValue = value;
326
+ for (const peer of peers.values()) for (const conn of peer.conns) conn.write(line);
327
+ return ok(true);
328
+ },
329
+ values() {
330
+ const out = [];
331
+ if (selfValue !== void 0) out.push({
332
+ peer: selfId,
333
+ self: true,
334
+ value: selfValue
335
+ });
336
+ const ids = [...peers.keys()].sort();
337
+ for (const id of ids) {
338
+ const value = peers.get(id)?.value;
339
+ if (value !== void 0) out.push({
340
+ peer: id,
341
+ self: false,
342
+ value
343
+ });
344
+ }
345
+ return out;
346
+ },
347
+ connected,
348
+ onChange(listener) {
349
+ listeners.add(listener);
350
+ return () => {
351
+ listeners.delete(listener);
352
+ };
353
+ },
354
+ async close() {
355
+ if (closed) return;
356
+ closed = true;
357
+ listeners.clear();
358
+ await Promise.resolve(swarm.destroy()).catch(() => {});
359
+ }
360
+ });
361
+ }
362
+ // core/sync/create-sync.ts
363
+ /** Peer-to-peer sync of one JSON value per device. Each device publishes its
364
+ * own value; `values()` returns the latest value of every device in the room.
365
+ * Worklet only. */
366
+ function createSync(options) {
367
+ return createSyncWith(options, { createSwarm: (seed) => new Hyperswarm({
368
+ seed,
369
+ maxPeers: 16
370
+ }) });
371
+ }
372
+ export { createSync };
@@ -1,4 +1,4 @@
1
- import { nt as WireMessage, q as MessageHeader, st as MessageTypeValue } from "./index-Do-kTNXw.mjs";
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,44 @@ 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;
55
+ /** Resolves once the transport is open, or has stopped trying (gave up,
56
+ * closed, replaced). A request's timeout starts when the caller invokes, so
57
+ * a request queued behind a slow connect can time out before it was ever
58
+ * sent; awaiting this first starts that clock at the socket. Optional so
59
+ * existing custom transports still satisfy the interface. */
60
+ ready?(): Promise<void>;
36
61
  }
37
62
  export declare function createWebSocketTransport(urlOrOptions?: string | CreateWebSocketTransportOptions): MessageTransport;
63
+ /**
64
+ * Deterministic in-process transport for tests and browser dev. Requests are
65
+ * routed through the real plugin kernel and the real `core.health`,
66
+ * `core.discovery`, `core.logs` and `core.permissions` manifests, so argument
67
+ * checks, unsupported-event errors and discovery match the worklet. Only the
68
+ * host (permission handlers) and `vendor.media` (no native picker, no
69
+ * loopback server: a `data:` URL) are stand-ins.
70
+ */
38
71
  export declare function createMockTransport(): MessageTransport;
39
72
  export type { MessageTransport };