@isoloop/protocol 0.0.0 → 0.1.0-next.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sabin Pandelovitch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,608 @@
1
+ /** Protocol version this build speaks (`v`) and the oldest it still accepts (`min`). */
2
+ export declare const PROTOCOL: {
3
+ readonly v: 1;
4
+ readonly min: 1;
5
+ };
6
+ /** Every message on every port is an envelope. */
7
+ export type Envelope<T extends string, P> = {
8
+ /** Protocol version. */
9
+ v: 1;
10
+ /** Message type. */
11
+ t: T;
12
+ /** Set when a reply is expected. */
13
+ id?: string;
14
+ /** Id of the message this replies to. */
15
+ re?: string;
16
+ /**
17
+ * The pool member a message is for (host → worker) or from (worker → host),
18
+ * on a pooled worker's isolate port (M2c, ADR 0001). Absent on an own
19
+ * worker's port, and on messages about the whole worker (`beat`).
20
+ */
21
+ isolate?: string;
22
+ p: P;
23
+ };
24
+ /** Any envelope, before its type is known. */
25
+ export type AnyEnvelope = Envelope<string, unknown>;
26
+ /**
27
+ * True for a well-formed envelope this build can read: `v` is a supported
28
+ * version, `t` is a string, `id`/`re`/`isolate` are absent or strings, and `p`
29
+ * is present.
30
+ * Says nothing about whether `t` is known; see the per-port guards.
31
+ */
32
+ export declare function isEnvelope(x: unknown): x is AnyEnvelope;
33
+ /**
34
+ * The message types of one port, as a map so the compiler checks that every
35
+ * type in the union is listed: a missing key is a type error.
36
+ */
37
+ export type MessageTypes<E extends AnyEnvelope> = Readonly<Record<E["t"], true>>;
38
+ /**
39
+ * Builds a guard for one port's union from its message types. Each side drops
40
+ * (and counts) envelopes with an unknown `v` or `t` (design §3), so a guard
41
+ * only checks the envelope and the type, not the payload.
42
+ */
43
+ export declare function envelopeGuard<E extends AnyEnvelope>(types: MessageTypes<E>): (x: unknown) => x is E;
44
+ /** Exhaustiveness check for switches over message unions. */
45
+ export declare function assertNever(x: never, message?: string): never;
46
+ /** Every error code on the wire (design §3, §4.7, §6.1, §6.3; ADRs 0002, 0003, 0007, 0008). */
47
+ export declare const ERROR_CODES: readonly ["protocol_mismatch", "timeout", "no_surface", "forbidden", "not_found", "unsupported", "cross_origin", "routing_disabled", "navigate_failed", "unknown_topic", "too_large", "invalid", "not_encodable", "quota_exceeded", "bus_unavailable", "not_requestable", "already_replied", "reply_invalid", "contracts_failed", "contracts_invalid", "contracts_mismatch", "reserved_topic", "seed_async", "seed_pending"];
48
+ export type ErrorCode = (typeof ERROR_CODES)[number];
49
+ export declare function isErrorCode(x: unknown): x is ErrorCode;
50
+ /** A schema issue, as reported with `invalid` (design §6.3). */
51
+ export type Issue = {
52
+ message: string;
53
+ path: (string | number)[];
54
+ };
55
+ export type CallError = {
56
+ code: ErrorCode;
57
+ message: string;
58
+ issues?: Issue[];
59
+ };
60
+ /** Reply to a host call or an acknowledged publish. */
61
+ export type CallResult = {
62
+ ok: true;
63
+ value: unknown;
64
+ } | {
65
+ ok: false;
66
+ error: CallError;
67
+ };
68
+ /** Payload of an `error` envelope from an isolate or the bus worker. */
69
+ export type ErrorPayload = {
70
+ message: string;
71
+ stack?: string;
72
+ fatal: boolean;
73
+ code?: ErrorCode;
74
+ };
75
+ /** What an isolate may do on the bus and the host (design §3). */
76
+ export type Grants = {
77
+ /** Topic patterns the isolate may publish to. */
78
+ publish: string[];
79
+ /** Topic patterns the isolate may subscribe to. */
80
+ subscribe: string[];
81
+ /** Programmatic `navigate()` allowed (ADR 0002). Default false. */
82
+ navigate?: boolean;
83
+ };
84
+ /** Topics under this prefix belong to the kernel (ADR 0002). */
85
+ export declare const SYSTEM_TOPIC_PREFIX = "isoloop.";
86
+ export declare function isSystemTopic(topic: string): boolean;
87
+ /**
88
+ * True if `topic` matches the grant pattern. `*` matches one or more
89
+ * characters, dots included, so `catalog.*` covers `catalog.items.v1` and
90
+ * `cart.*.v1` covers `cart.items.v1`. Without `*` the match is exact.
91
+ */
92
+ export declare function matchTopic(grant: string, topic: string): boolean;
93
+ /** True if any pattern in the list matches `topic`. */
94
+ export declare function matchAny(patterns: readonly string[], topic: string): boolean;
95
+ /** Modifier keys held during an event. */
96
+ export type Mods = {
97
+ alt: boolean;
98
+ ctrl: boolean;
99
+ meta: boolean;
100
+ shift: boolean;
101
+ };
102
+ /**
103
+ * Event types the host forwards (design §4.6), plus `resize` for transferred
104
+ * canvases (§4.7). `pointermove` and `scroll` are opt-in per node and come at
105
+ * most once a frame.
106
+ */
107
+ export type EventType = "click" | "dblclick" | "input" | "change" | "keydown" | "keyup" | "submit" | "focusin" | "focusout" | "pointerdown" | "pointerup" | "pointermove" | "scroll" | "resize";
108
+ /** A DOM event as it reaches an isolate (design §4.6). Node ids are the isolate's own. */
109
+ export type SerializedEvent = {
110
+ type: EventType;
111
+ target: string;
112
+ /** The target and its ancestors that have a listener, innermost first. */
113
+ currentTargets: string[];
114
+ value?: string;
115
+ checked?: boolean;
116
+ key?: string;
117
+ code?: string;
118
+ mods: Mods;
119
+ x?: number;
120
+ y?: number;
121
+ button?: number;
122
+ /** For `resize`. */
123
+ width?: number;
124
+ height?: number;
125
+ /** For `scroll`: the scrolled element's offsets (M3b). */
126
+ scrollTop?: number;
127
+ scrollLeft?: number;
128
+ };
129
+ /** Why the host asks an isolate to shut down. `suspend` keeps its offsets (M2, ADR 0001). */
130
+ export type ShutdownReason = "stop" | "restart" | "suspend";
131
+ /** Calls an isolate can make to the host (design §4.7). */
132
+ export type HostMethod = "measure" | "focus" | "navigate" | "scrollIntoView" | "requestCanvas";
133
+ /** What `measure` returns: a node's box relative to its surface, in CSS pixels. */
134
+ export type Rect = {
135
+ x: number;
136
+ y: number;
137
+ width: number;
138
+ height: number;
139
+ };
140
+ /** First message to an isolate. The host's half of the version handshake. */
141
+ export type InitPayload = {
142
+ isolateId: string;
143
+ /** Protocol versions the host accepts. */
144
+ protocol: {
145
+ min: number;
146
+ max: number;
147
+ };
148
+ /** `isoloop-dom@1`, or `none` (headless). */
149
+ renderFmt: string;
150
+ /** `manifest.config`, passed through. */
151
+ config: unknown;
152
+ grants: Grants;
153
+ /** Transferred. */
154
+ busPort: MessagePort;
155
+ heartbeatMs: number;
156
+ /** Isolate module URL, imported by the bootstrap. */
157
+ src: string;
158
+ /**
159
+ * Set when the isolate wakes from suspension (ADR 0001): its `latest`
160
+ * subscriptions start from `committed` instead, so it replays what it missed.
161
+ */
162
+ wake?: boolean;
163
+ /** `KernelConfig.bus.commitIntervalMs` (ADR 0016, decision 1). Default 100. */
164
+ commitIntervalMs?: number;
165
+ };
166
+ /** What a beat says about whether the isolate could be suspended (ADR 0001). */
167
+ export type IdleReport = {
168
+ /** Time since the bus last delivered a record to this isolate. */
169
+ sinceDeliveryMs: number;
170
+ /** Host calls, publishes and requests waiting for an answer. */
171
+ inFlight: number;
172
+ /** Open `ctx.keepAwake()` holds: age and where they were taken. */
173
+ holds: {
174
+ ageMs: number;
175
+ stack?: string;
176
+ }[];
177
+ /**
178
+ * Milliseconds the worker spent running this isolate's code since the last
179
+ * beat (ADR 0017): what the runtime dispatched to it and the callbacks it
180
+ * registered. A pool's shared framework render is split equally among the
181
+ * members whose roots it touched. Promise continuations, other schedulers
182
+ * and the worker's shared work (garbage collection) aren't counted; they
183
+ * show only in `lagMs`. Absent from runtimes before it.
184
+ */
185
+ busyMs?: number;
186
+ };
187
+ /** Isolate port: host → isolate. */
188
+ export type HostToIsolate = Envelope<"init", InitPayload> | Envelope<"event", SerializedEvent> | Envelope<"result", CallResult> | Envelope<"shutdown", {
189
+ reason: ShutdownReason;
190
+ graceMs: number;
191
+ }> | Envelope<"reattach", {
192
+ busPort: MessagePort;
193
+ }>;
194
+ /** Isolate port: isolate → host. */
195
+ export type IsolateToHost = Envelope<"ready", {
196
+ runtime: string;
197
+ adapter: string;
198
+ renderFmt: string;
199
+ /** The Isoloop `major.minor` the isolate was built against, from `defineIsolate` (ADR 0012). */
200
+ requires?: string;
201
+ }> | Envelope<"patch", {
202
+ fmt: string;
203
+ batch: unknown;
204
+ styles?: string[];
205
+ head?: string[];
206
+ }> | Envelope<"call", {
207
+ method: HostMethod;
208
+ args: unknown[];
209
+ }> | Envelope<"beat", {
210
+ lagMs: number;
211
+ heapBytes?: number;
212
+ idle?: IdleReport;
213
+ members?: Record<string, IdleReport>;
214
+ }> | Envelope<"error", ErrorPayload> | Envelope<"bye", Record<string, never>>;
215
+ export declare const HOST_TO_ISOLATE: MessageTypes<HostToIsolate>;
216
+ export declare const ISOLATE_TO_HOST: MessageTypes<IsolateToHost>;
217
+ export declare const isHostToIsolate: (x: unknown) => x is HostToIsolate;
218
+ export declare const isIsolateToHost: (x: unknown) => x is IsolateToHost;
219
+ /** One record in a topic's log (design §6.1). */
220
+ export type BusRecord = {
221
+ offset: number;
222
+ key?: string;
223
+ value: unknown;
224
+ /** `Date.now()` at append. */
225
+ ts: number;
226
+ /** Isolate id of the publisher. */
227
+ producer: string;
228
+ /**
229
+ * Set on a `bus.request` record: the caller's isolate id and its request id.
230
+ * A recipient answers with `reply { topic, offset }` (design §6.3).
231
+ */
232
+ req?: {
233
+ from: string;
234
+ id: string;
235
+ };
236
+ };
237
+ /**
238
+ * Identifies a publish so a re-send after a bus crash isn't appended twice to
239
+ * a persistent topic (ADR 0007, step 5): `epoch` names the publisher's
240
+ * instance (new after an isolate restart or a page load), `seq` counts its
241
+ * publishes and requests. The bus answers a re-send it already holds with the
242
+ * original offset. Memory topics ignore it.
243
+ */
244
+ export type PublishId = {
245
+ epoch?: number;
246
+ seq?: number;
247
+ };
248
+ /** Where a new subscription starts reading. */
249
+ export type StartPosition = "latest" | "earliest" | "committed";
250
+ /** Bus port: isolate → bus worker. */
251
+ export type IsolateToBus = Envelope<"publish", {
252
+ topic: string;
253
+ key?: string;
254
+ value: unknown;
255
+ } & PublishId> | Envelope<"subscribe", {
256
+ topic: string;
257
+ from: StartPosition;
258
+ group?: string;
259
+ }> | Envelope<"unsubscribe", {
260
+ topic: string;
261
+ }> | Envelope<"commits", {
262
+ offsets: {
263
+ topic: string;
264
+ offset: number;
265
+ seq: number;
266
+ }[];
267
+ }> | Envelope<"request", {
268
+ topic: string;
269
+ key?: string;
270
+ value: unknown;
271
+ timeoutMs: number;
272
+ } & PublishId> | Envelope<"reply", {
273
+ topic: string;
274
+ offset: number;
275
+ value: unknown;
276
+ }>;
277
+ /** Bus port: bus worker → isolate. */
278
+ export type BusToIsolate = Envelope<"deliver", {
279
+ topic: string;
280
+ records: BusRecord[];
281
+ gap?: {
282
+ from: number;
283
+ to: number;
284
+ };
285
+ seq: number;
286
+ }> | Envelope<"reset", {
287
+ topic: string;
288
+ reason: "bus_restart";
289
+ }> | Envelope<"result", CallResult>;
290
+ export declare const ISOLATE_TO_BUS: MessageTypes<IsolateToBus>;
291
+ export declare const BUS_TO_ISOLATE: MessageTypes<BusToIsolate>;
292
+ export declare const isIsolateToBus: (x: unknown) => x is IsolateToBus;
293
+ export declare const isBusToIsolate: (x: unknown) => x is BusToIsolate;
294
+ /** `KernelConfig.bus.commitIntervalMs` when unset (ADR 0016, decision 1, point 7). */
295
+ export declare const DEFAULT_COMMIT_INTERVAL_MS = 100;
296
+ /** The highest allowed interval: keeps the redelivery window after a crash under a second. */
297
+ export declare const MAX_COMMIT_INTERVAL_MS = 1e3;
298
+ /** A subscription's credit at the broker: records delivered and not yet committed. */
299
+ export declare const DEFAULT_CREDIT = 1e3;
300
+ /** Why an interval is invalid, or `undefined` when it's an integer from 0 to 1,000. */
301
+ export declare function commitIntervalProblem(ms: unknown): string | undefined;
302
+ /** Where one subscription has settled to: the highest settled offset, and the delivery `seq` (ADR 0016, point 11). */
303
+ export type CommitPoint = {
304
+ offset: number;
305
+ seq: number;
306
+ };
307
+ export type CommitOffsets = ({
308
+ topic: string;
309
+ } & CommitPoint)[];
310
+ /**
311
+ * The commit point each record of one `deliver` settles to, in order. A
312
+ * record settles its delivery `seq` only as the delivery's last record, and
313
+ * `seq − 1` before that: a delivery counts once all its records are settled,
314
+ * and records settle in the order they arrived. Its offset is the highest
315
+ * delivered on the subscription up to it, `highest` being the highest before
316
+ * this delivery (`-1` for none), so a commit that counts a delivery settled
317
+ * also reaches every offset in it.
318
+ */
319
+ export declare function deliveryPoints(seq: number, offsets: readonly number[], highest: number): CommitPoint[];
320
+ export type CommitterOptions = {
321
+ /** Sends one `commits` message. Called with at least one entry. */
322
+ send: (offsets: CommitOffsets) => void;
323
+ /** 0: at the end of each task that settled a record. Default 100. */
324
+ intervalMs?: number;
325
+ /** The broker's credit per subscription; a subscription sends early at half of it. Default 1,000. */
326
+ credit?: number;
327
+ };
328
+ export type Committer = {
329
+ /**
330
+ * `records` records of `topic` are settled (default one): everything up to
331
+ * `at.offset`, and every delivery up to `at.seq` whole. Each is kept as the
332
+ * highest seen, separately: a record redelivered to a group member can
333
+ * have a lower offset than records it settled before (ADR 0016, point 11).
334
+ */
335
+ settle(topic: string, at: CommitPoint, records?: number): void;
336
+ /** Sends what's pending now: an unsubscribe, and a new port after a bus restart. */
337
+ flush(): void;
338
+ /**
339
+ * Returns what's pending and clears it, without sending: for a sender that
340
+ * must wait for the broker's answer (a shutdown, before `bye`).
341
+ */
342
+ take(): CommitOffsets | undefined;
343
+ /** Forgets a topic's pending offset (an unsubscribe or a lost memory topic). */
344
+ drop(topic: string): void;
345
+ /** Settled points not yet sent, by topic. For tests and reports. */
346
+ pending(): ReadonlyMap<string, CommitPoint>;
347
+ /** Stops the timer without sending. */
348
+ dispose(): void;
349
+ };
350
+ export declare function createCommitter(o: CommitterOptions): Committer;
351
+ /**
352
+ * A rejected bus call (`kernel.publish`, `ctx.bus.publish`, `request`,
353
+ * `reply`): the broker's error code, and the schema issues for `invalid`.
354
+ */
355
+ export declare class BusError extends Error {
356
+ readonly code: ErrorCode;
357
+ readonly issues: readonly Issue[] | undefined;
358
+ constructor(error: CallError);
359
+ }
360
+ export type Retention = {
361
+ kind: "last-n";
362
+ n: number;
363
+ } | {
364
+ kind: "time";
365
+ ms: number;
366
+ } | {
367
+ kind: "compacted";
368
+ };
369
+ /**
370
+ * The structured-cloneable part of a topic definition: what the host sends at
371
+ * `boot` so the bus worker can check it against the contracts module (ADR 0003).
372
+ */
373
+ export type TopicConfig = {
374
+ name: string;
375
+ retention: Retention;
376
+ /** Default 256 KiB. */
377
+ maxRecordBytes?: number;
378
+ /** Default `memory`. `persistent` is OPFS (ADR 0007, M2b). */
379
+ durability?: "memory" | "persistent";
380
+ /** The topic has a `reply` schema, so `bus.request` works on it. */
381
+ requestable: boolean;
382
+ /** Name of the `seed.from` topic and its `follow` flag (M2b). */
383
+ seed?: {
384
+ from: string;
385
+ follow: boolean;
386
+ };
387
+ };
388
+ /** Why persistent topics run in memory (`bus:durability-degraded`). */
389
+ export type DurabilityDegraded = "another-tab" | "no-sync-access" | "open-failed";
390
+ /**
391
+ * Seeding news (ADR 0003, decision 18). `rejected`: a source record `map`
392
+ * threw on, returned a promise for (`seed_async`), or the topic's schema
393
+ * rejected; it was skipped and stays in `from`. `seeded`: the seed ended and
394
+ * the topic opened.
395
+ */
396
+ export type SeedEvent = {
397
+ kind: "rejected";
398
+ topic: string;
399
+ from: string;
400
+ offset: number;
401
+ code: ErrorCode;
402
+ issues: Issue[];
403
+ } | {
404
+ kind: "seeded";
405
+ topic: string;
406
+ copied: number;
407
+ rejected: number;
408
+ };
409
+ /** Sampled every second on the control port (design §6.3). */
410
+ export type BusMetrics = {
411
+ topics: {
412
+ topic: string;
413
+ recordsPerSec: number;
414
+ bytesPerSec: number;
415
+ }[];
416
+ /** `lag` is `head − cursor`. */
417
+ subscriptions: {
418
+ consumer: string;
419
+ topic: string;
420
+ lag: number;
421
+ credit: number;
422
+ }[];
423
+ rejected: Partial<Record<ErrorCode, number>>;
424
+ /** The origin's storage use, from `navigator.storage.estimate()`, while the bus keeps files. */
425
+ storage?: {
426
+ usage: number;
427
+ quota: number;
428
+ };
429
+ };
430
+ /** Control port: host → bus worker. */
431
+ export type HostToBus = Envelope<"boot", {
432
+ contractsUrl: string;
433
+ topics: TopicConfig[];
434
+ heartbeatMs?: number;
435
+ dev?: boolean;
436
+ /**
437
+ * Safe mode (ADR 0007, decision 5): the bus crashed twice while
438
+ * loading, so it sets each persistent topic's newest segment aside.
439
+ */
440
+ safeMode?: boolean;
441
+ /** A bus restart: the worker it replaces may still hold the files' lock a moment. */
442
+ restart?: boolean;
443
+ }> | Envelope<"attach", {
444
+ isolateId: string;
445
+ grants: Grants;
446
+ port: MessagePort;
447
+ reattach?: boolean;
448
+ }> | Envelope<"detach", {
449
+ isolateId: string;
450
+ keepOffsets: boolean;
451
+ wake?: boolean;
452
+ }> | Envelope<"publish", {
453
+ topic: string;
454
+ key?: string;
455
+ value: unknown;
456
+ } & PublishId> | Envelope<"flush", Record<string, never>> | Envelope<"drop", {
457
+ topic: string;
458
+ force: boolean;
459
+ }>;
460
+ /** Control port: bus worker → host. */
461
+ export type BusToHost = Envelope<"ready", {
462
+ engine: string;
463
+ storage: "memory" | "opfs";
464
+ restored: {
465
+ topic: string;
466
+ head: number;
467
+ }[];
468
+ /** Safe mode only: the segments set aside, as `<topic>/<file>`. */
469
+ quarantined?: string[];
470
+ /**
471
+ * Persistent topics run in memory, and why (ADR 0007, decision 6):
472
+ * another tab holds the files, sync access handles are missing, or
473
+ * the files failed to open.
474
+ */
475
+ degraded?: DurabilityDegraded;
476
+ /**
477
+ * Persistent topics on disk that the contracts no longer list: kept,
478
+ * not opened (ADR 0003, decision 19). `bytes` is their total size.
479
+ */
480
+ orphaned?: {
481
+ names: string[];
482
+ bytes: number;
483
+ };
484
+ }> | Envelope<"beat", {
485
+ lagMs: number;
486
+ }> | Envelope<"wake", {
487
+ isolateId: string;
488
+ topic: string;
489
+ }> | Envelope<"metrics", BusMetrics> | Envelope<"result", CallResult> | Envelope<"seed", SeedEvent> | Envelope<"error", ErrorPayload>;
490
+ export declare const HOST_TO_BUS: MessageTypes<HostToBus>;
491
+ export declare const BUS_TO_HOST: MessageTypes<BusToHost>;
492
+ export declare const isHostToBus: (x: unknown) => x is HostToBus;
493
+ export declare const isBusToHost: (x: unknown) => x is BusToHost;
494
+ /**
495
+ * A Standard Schema V1 built by hand (ADR 0003, decision 6). Protocol depends
496
+ * on nothing, so this is the structural subset of the interface that system
497
+ * topics need; it is assignable to the bus's vendored `StandardSchemaV1`.
498
+ */
499
+ export type SystemSchema<T> = {
500
+ readonly "~standard": {
501
+ readonly version: 1;
502
+ readonly vendor: "isoloop";
503
+ readonly validate: (value: unknown) => {
504
+ readonly value: T;
505
+ readonly issues?: undefined;
506
+ } | {
507
+ readonly issues: readonly Issue[];
508
+ };
509
+ readonly types?: {
510
+ readonly input: T;
511
+ readonly output: T;
512
+ } | undefined;
513
+ };
514
+ };
515
+ /** A kernel-owned `isoloop.*` topic: same shape as a bus `TopicDef`. */
516
+ export type SystemTopicDef<T> = {
517
+ readonly name: string;
518
+ readonly schema: SystemSchema<T>;
519
+ readonly retention: Retention;
520
+ readonly maxRecordBytes?: number;
521
+ };
522
+ /**
523
+ * A check that returns the issues found in `value`, or none. `path` is where
524
+ * `value` sits, so nested checks can report full paths.
525
+ */
526
+ export type Check = (value: unknown, path: (string | number)[]) => Issue[];
527
+ /** Wraps a hand-written check as a Standard Schema that passes valid values through unchanged. */
528
+ export declare function systemSchema<T>(check: Check): SystemSchema<T>;
529
+ /** Defines a system topic. The name must start with `isoloop.`. */
530
+ export declare function systemTopic<T>(name: string, def: Omit<SystemTopicDef<T>, "name">): SystemTopicDef<T>;
531
+ /** Small building blocks for hand-written checks. */
532
+ export declare const checks: {
533
+ string: Check;
534
+ optionalString: Check;
535
+ /** A plain object whose listed fields pass their checks. Other fields are allowed. */
536
+ object: (fields: Readonly<Record<string, Check>>) => Check;
537
+ /** Any value. */
538
+ any: Check;
539
+ };
540
+ /** The current location, as the kernel publishes it (ADR 0002). */
541
+ export type RouteValue = {
542
+ /** Absolute URL. */
543
+ href: string;
544
+ pathname: string;
545
+ /** `pathname` relative to `basePath`, starting with `/`; `null` outside it. */
546
+ path: string | null;
547
+ search: string;
548
+ hash: string;
549
+ /** `history.state` as is; `null` when it was too large for the bus (`route:state_dropped`). */
550
+ state: unknown;
551
+ };
552
+ /**
553
+ * `isoloop.route.v1`: compacted, key `"current"`, memory only (the URL is the
554
+ * source of truth). Only the kernel publishes it; every isolate may
555
+ * subscribe without a grant, with `from: 'earliest'` to get the current
556
+ * route at once.
557
+ */
558
+ export declare const routeTopic: SystemTopicDef<RouteValue>;
559
+ /** The key of the one record that matters on `isoloop.route.v1`. */
560
+ export declare const ROUTE_KEY = "current";
561
+ /** Every system topic, built into the bus. */
562
+ export declare const SYSTEM_TOPICS: readonly SystemTopicDef<any>[];
563
+ /** A topic as `kernel.publish`, `kernel.subscribe` and `BusClient` take it. */
564
+ export type TopicRef<In = unknown, Out = In, RIn = never, ROut = RIn> = {
565
+ readonly name: string;
566
+ readonly schema: SchemaTypes<In, Out>;
567
+ readonly reply?: SchemaTypes<RIn, ROut>;
568
+ };
569
+ /** The type-only part of a Standard Schema V1. */
570
+ export type SchemaTypes<In, Out> = {
571
+ readonly "~standard": {
572
+ readonly types?: {
573
+ readonly input: In;
574
+ readonly output: Out;
575
+ } | undefined;
576
+ };
577
+ };
578
+ /** A record whose value has the topic's output type. */
579
+ export type TypedRecord<T> = Omit<BusRecord, "value"> & {
580
+ value: T;
581
+ };
582
+ /** The parts of a topic definition that make up its `TopicConfig`. */
583
+ export type TopicShape = {
584
+ readonly name: string;
585
+ readonly retention: Retention;
586
+ readonly maxRecordBytes?: number;
587
+ readonly durability?: "memory" | "persistent";
588
+ readonly reply?: unknown;
589
+ readonly seed?: {
590
+ readonly from: {
591
+ readonly name: string;
592
+ };
593
+ readonly follow?: boolean;
594
+ };
595
+ };
596
+ /** What `KernelConfig.contracts.list` holds: a `contracts()` list, seen structurally. */
597
+ export type ContractsList = {
598
+ readonly topics: readonly TopicShape[];
599
+ };
600
+ /**
601
+ * The structured-cloneable part of a topic, sent at `boot` and compared with
602
+ * the contracts module's (ADR 0003, decision 5). Host and bus both use this
603
+ * one function, so equal definitions always give equal configs.
604
+ */
605
+ export declare function topicConfigOf(t: TopicShape): TopicConfig;
606
+ /** `"0.4.2"` → `"0.4"`. Anything that isn't `major.minor[.patch…]` gives `undefined`. */
607
+ export declare function majorMinor(version: string): string | undefined;
608
+ export declare function compareVersions(a: string, b: string): number;
package/dist/index.js ADDED
@@ -0,0 +1,357 @@
1
+ // src/envelope.ts
2
+ /** Protocol version this build speaks (`v`) and the oldest it still accepts (`min`). */
3
+ const PROTOCOL = {
4
+ v: 1,
5
+ min: 1
6
+ };
7
+ const isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
8
+ const isOptionalString = (x) => x === void 0 || typeof x === "string";
9
+ /**
10
+ * True for a well-formed envelope this build can read: `v` is a supported
11
+ * version, `t` is a string, `id`/`re`/`isolate` are absent or strings, and `p`
12
+ * is present.
13
+ * Says nothing about whether `t` is known; see the per-port guards.
14
+ */
15
+ function isEnvelope(x) {
16
+ return isRecord(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
17
+ }
18
+ /**
19
+ * Builds a guard for one port's union from its message types. Each side drops
20
+ * (and counts) envelopes with an unknown `v` or `t` (design §3), so a guard
21
+ * only checks the envelope and the type, not the payload.
22
+ */
23
+ function envelopeGuard(types) {
24
+ return (x) => isEnvelope(x) && Object.hasOwn(types, x.t);
25
+ }
26
+ /** Exhaustiveness check for switches over message unions. */
27
+ function assertNever(x, message = "Unexpected value") {
28
+ throw new Error(`${message}: ${JSON.stringify(x)}`);
29
+ }
30
+ // src/errors.ts
31
+ /** Every error code on the wire (design §3, §4.7, §6.1, §6.3; ADRs 0002, 0003, 0007, 0008). */
32
+ const ERROR_CODES = [
33
+ "protocol_mismatch",
34
+ "timeout",
35
+ "no_surface",
36
+ "forbidden",
37
+ "not_found",
38
+ "unsupported",
39
+ "cross_origin",
40
+ "routing_disabled",
41
+ "navigate_failed",
42
+ "unknown_topic",
43
+ "too_large",
44
+ "invalid",
45
+ "not_encodable",
46
+ "quota_exceeded",
47
+ "bus_unavailable",
48
+ "not_requestable",
49
+ "already_replied",
50
+ "reply_invalid",
51
+ "contracts_failed",
52
+ "contracts_invalid",
53
+ "contracts_mismatch",
54
+ "reserved_topic",
55
+ "seed_async",
56
+ "seed_pending"
57
+ ];
58
+ const codes = new Set(ERROR_CODES);
59
+ function isErrorCode(x) {
60
+ return typeof x === "string" && codes.has(x);
61
+ }
62
+ // src/grants.ts
63
+ /** Topics under this prefix belong to the kernel (ADR 0002). */
64
+ const SYSTEM_TOPIC_PREFIX = "isoloop.";
65
+ function isSystemTopic(topic) {
66
+ return topic.startsWith(SYSTEM_TOPIC_PREFIX);
67
+ }
68
+ const escape = (s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
69
+ const compiled = /* @__PURE__ */ new Map();
70
+ /**
71
+ * True if `topic` matches the grant pattern. `*` matches one or more
72
+ * characters, dots included, so `catalog.*` covers `catalog.items.v1` and
73
+ * `cart.*.v1` covers `cart.items.v1`. Without `*` the match is exact.
74
+ */
75
+ function matchTopic(grant, topic) {
76
+ if (!grant.includes("*")) return grant === topic;
77
+ let re = compiled.get(grant);
78
+ if (!re) {
79
+ re = new RegExp(`^${grant.split("*").map(escape).join(".+")}$`);
80
+ compiled.set(grant, re);
81
+ }
82
+ return re.test(topic);
83
+ }
84
+ /** True if any pattern in the list matches `topic`. */
85
+ function matchAny(patterns, topic) {
86
+ return patterns.some((p) => matchTopic(p, topic));
87
+ }
88
+ // src/isolate.ts
89
+ const HOST_TO_ISOLATE = {
90
+ init: true,
91
+ event: true,
92
+ result: true,
93
+ shutdown: true,
94
+ reattach: true
95
+ };
96
+ const ISOLATE_TO_HOST = {
97
+ ready: true,
98
+ patch: true,
99
+ call: true,
100
+ beat: true,
101
+ error: true,
102
+ bye: true
103
+ };
104
+ const isHostToIsolate = envelopeGuard(HOST_TO_ISOLATE);
105
+ const isIsolateToHost = envelopeGuard(ISOLATE_TO_HOST);
106
+ // src/bus.ts
107
+ const ISOLATE_TO_BUS = {
108
+ publish: true,
109
+ subscribe: true,
110
+ unsubscribe: true,
111
+ commits: true,
112
+ request: true,
113
+ reply: true
114
+ };
115
+ const BUS_TO_ISOLATE = {
116
+ deliver: true,
117
+ reset: true,
118
+ result: true
119
+ };
120
+ const isIsolateToBus = envelopeGuard(ISOLATE_TO_BUS);
121
+ const isBusToIsolate = envelopeGuard(BUS_TO_ISOLATE);
122
+ // src/commits.ts
123
+ /** `KernelConfig.bus.commitIntervalMs` when unset (ADR 0016, decision 1, point 7). */
124
+ const DEFAULT_COMMIT_INTERVAL_MS = 100;
125
+ /** The highest allowed interval: keeps the redelivery window after a crash under a second. */
126
+ const MAX_COMMIT_INTERVAL_MS = 1e3;
127
+ /** A subscription's credit at the broker: records delivered and not yet committed. */
128
+ const DEFAULT_CREDIT = 1e3;
129
+ /** Why an interval is invalid, or `undefined` when it's an integer from 0 to 1,000. */
130
+ function commitIntervalProblem(ms) {
131
+ if (typeof ms === "number" && Number.isInteger(ms) && ms >= 0 && ms <= 1e3) return void 0;
132
+ return `bus.commitIntervalMs must be an integer from 0 to ${MAX_COMMIT_INTERVAL_MS}, got ${String(ms)}`;
133
+ }
134
+ /**
135
+ * The commit point each record of one `deliver` settles to, in order. A
136
+ * record settles its delivery `seq` only as the delivery's last record, and
137
+ * `seq − 1` before that: a delivery counts once all its records are settled,
138
+ * and records settle in the order they arrived. Its offset is the highest
139
+ * delivered on the subscription up to it, `highest` being the highest before
140
+ * this delivery (`-1` for none), so a commit that counts a delivery settled
141
+ * also reaches every offset in it.
142
+ */
143
+ function deliveryPoints(seq, offsets, highest) {
144
+ let top = highest;
145
+ return offsets.map((offset, i) => {
146
+ top = Math.max(top, offset);
147
+ return {
148
+ offset: top,
149
+ seq: i === offsets.length - 1 ? seq : seq - 1
150
+ };
151
+ });
152
+ }
153
+ function createCommitter(o) {
154
+ const intervalMs = o.intervalMs ?? 100;
155
+ const half = Math.max(1, Math.floor((o.credit ?? 1e3) / 2));
156
+ /** Highest settled offset and delivery per topic, not yet sent. */
157
+ const offsets = /* @__PURE__ */ new Map();
158
+ /** Records settled per topic since its last send: the early send at half the credit. */
159
+ const counts = /* @__PURE__ */ new Map();
160
+ let timer;
161
+ let queued = false;
162
+ const take = () => {
163
+ if (timer !== void 0) {
164
+ clearTimeout(timer);
165
+ timer = void 0;
166
+ }
167
+ queued = false;
168
+ if (offsets.size === 0) return void 0;
169
+ const out = [];
170
+ for (const [topic, { offset, seq }] of offsets) out.push({
171
+ topic,
172
+ offset,
173
+ seq
174
+ });
175
+ offsets.clear();
176
+ counts.clear();
177
+ return out;
178
+ };
179
+ const flush = () => {
180
+ const out = take();
181
+ if (out) o.send(out);
182
+ };
183
+ const schedule = () => {
184
+ if (intervalMs === 0) {
185
+ if (queued) return;
186
+ queued = true;
187
+ queueMicrotask(() => {
188
+ if (queued) flush();
189
+ });
190
+ return;
191
+ }
192
+ timer ??= setTimeout(flush, intervalMs);
193
+ };
194
+ return {
195
+ settle(topic, at, records = 1) {
196
+ const prev = offsets.get(topic);
197
+ offsets.set(topic, prev === void 0 ? {
198
+ offset: at.offset,
199
+ seq: at.seq
200
+ } : {
201
+ offset: Math.max(prev.offset, at.offset),
202
+ seq: Math.max(prev.seq, at.seq)
203
+ });
204
+ const n = (counts.get(topic) ?? 0) + records;
205
+ counts.set(topic, n);
206
+ if (n >= half) flush();
207
+ else schedule();
208
+ },
209
+ flush,
210
+ take,
211
+ drop(topic) {
212
+ offsets.delete(topic);
213
+ counts.delete(topic);
214
+ },
215
+ pending: () => offsets,
216
+ dispose() {
217
+ if (timer !== void 0) clearTimeout(timer);
218
+ timer = void 0;
219
+ queued = false;
220
+ }
221
+ };
222
+ }
223
+ // src/bus-error.ts
224
+ /**
225
+ * A rejected bus call (`kernel.publish`, `ctx.bus.publish`, `request`,
226
+ * `reply`): the broker's error code, and the schema issues for `invalid`.
227
+ */
228
+ var BusError = class extends Error {
229
+ code;
230
+ issues;
231
+ constructor(error) {
232
+ super(error.message);
233
+ this.name = "BusError";
234
+ this.code = error.code;
235
+ this.issues = error.issues;
236
+ }
237
+ };
238
+ // src/control.ts
239
+ const HOST_TO_BUS = {
240
+ boot: true,
241
+ attach: true,
242
+ detach: true,
243
+ publish: true,
244
+ flush: true,
245
+ drop: true
246
+ };
247
+ const BUS_TO_HOST = {
248
+ ready: true,
249
+ beat: true,
250
+ wake: true,
251
+ metrics: true,
252
+ result: true,
253
+ seed: true,
254
+ error: true
255
+ };
256
+ const isHostToBus = envelopeGuard(HOST_TO_BUS);
257
+ const isBusToHost = envelopeGuard(BUS_TO_HOST);
258
+ // src/system-topics.ts
259
+ /** Wraps a hand-written check as a Standard Schema that passes valid values through unchanged. */
260
+ function systemSchema(check) {
261
+ return { "~standard": {
262
+ version: 1,
263
+ vendor: "isoloop",
264
+ validate: (value) => {
265
+ const issues = check(value, []);
266
+ return issues.length === 0 ? { value } : { issues };
267
+ }
268
+ } };
269
+ }
270
+ /** Defines a system topic. The name must start with `isoloop.`. */
271
+ function systemTopic(name, def) {
272
+ if (!isSystemTopic(name)) throw new Error(`system topic names start with isoloop.: ${name}`);
273
+ return Object.freeze({
274
+ ...def,
275
+ name
276
+ });
277
+ }
278
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
279
+ const issue = (path, message) => [{
280
+ message,
281
+ path
282
+ }];
283
+ /** Small building blocks for hand-written checks. */
284
+ const checks = {
285
+ string: (v, path) => typeof v === "string" ? [] : issue(path, "expected a string"),
286
+ optionalString: (v, path) => v === void 0 || typeof v === "string" ? [] : issue(path, "expected a string or nothing"),
287
+ object: (fields) => (v, path) => {
288
+ if (!isObject(v)) return issue(path, "expected an object");
289
+ return Object.entries(fields).flatMap(([k, check]) => check(v[k], [...path, k]));
290
+ },
291
+ any: () => []
292
+ };
293
+ // src/route.ts
294
+ const stringOrNull = (v, path) => v === null || typeof v === "string" ? [] : [{
295
+ message: "expected a string or null",
296
+ path
297
+ }];
298
+ /**
299
+ * `isoloop.route.v1`: compacted, key `"current"`, memory only (the URL is the
300
+ * source of truth). Only the kernel publishes it; every isolate may
301
+ * subscribe without a grant, with `from: 'earliest'` to get the current
302
+ * route at once.
303
+ */
304
+ const routeTopic = systemTopic("isoloop.route.v1", {
305
+ schema: systemSchema(checks.object({
306
+ href: checks.string,
307
+ pathname: checks.string,
308
+ path: stringOrNull,
309
+ search: checks.string,
310
+ hash: checks.string,
311
+ state: checks.any
312
+ })),
313
+ retention: { kind: "compacted" }
314
+ });
315
+ /** The key of the one record that matters on `isoloop.route.v1`. */
316
+ const ROUTE_KEY = "current";
317
+ /** Every system topic, built into the bus. */
318
+ const SYSTEM_TOPICS = [routeTopic];
319
+ // src/topics.ts
320
+ /**
321
+ * The structured-cloneable part of a topic, sent at `boot` and compared with
322
+ * the contracts module's (ADR 0003, decision 5). Host and bus both use this
323
+ * one function, so equal definitions always give equal configs.
324
+ */
325
+ function topicConfigOf(t) {
326
+ const cfg = {
327
+ name: t.name,
328
+ retention: { ...t.retention },
329
+ requestable: t.reply !== void 0
330
+ };
331
+ if (t.maxRecordBytes !== void 0) cfg.maxRecordBytes = t.maxRecordBytes;
332
+ if (t.durability !== void 0) cfg.durability = t.durability;
333
+ if (t.seed !== void 0) cfg.seed = {
334
+ from: t.seed.from.name,
335
+ follow: t.seed.follow ?? false
336
+ };
337
+ return cfg;
338
+ }
339
+ // src/version.ts
340
+ /** `"0.4.2"` → `"0.4"`. Anything that isn't `major.minor[.patch…]` gives `undefined`. */
341
+ function majorMinor(version) {
342
+ const m = /^(\d+)\.(\d+)(?:[.+-].*)?$/.exec(version);
343
+ return m ? `${Number(m[1])}.${Number(m[2])}` : void 0;
344
+ }
345
+ /** Orders two `major.minor` stamps: negative, zero or positive. Unparseable ones throw. */
346
+ const parse = (v) => {
347
+ const mm = majorMinor(v);
348
+ if (mm === void 0) throw new TypeError(`not a version: ${JSON.stringify(v)}`);
349
+ const [major = 0, minor = 0] = mm.split(".").map(Number);
350
+ return [major, minor];
351
+ };
352
+ function compareVersions(a, b) {
353
+ const [am, an] = parse(a);
354
+ const [bm, bn] = parse(b);
355
+ return am - bm || an - bn;
356
+ }
357
+ export { BUS_TO_HOST, BUS_TO_ISOLATE, BusError, DEFAULT_COMMIT_INTERVAL_MS, DEFAULT_CREDIT, ERROR_CODES, HOST_TO_BUS, HOST_TO_ISOLATE, ISOLATE_TO_BUS, ISOLATE_TO_HOST, MAX_COMMIT_INTERVAL_MS, PROTOCOL, ROUTE_KEY, SYSTEM_TOPICS, SYSTEM_TOPIC_PREFIX, assertNever, checks, commitIntervalProblem, compareVersions, createCommitter, deliveryPoints, envelopeGuard, isBusToHost, isBusToIsolate, isEnvelope, isErrorCode, isHostToBus, isHostToIsolate, isIsolateToBus, isIsolateToHost, isSystemTopic, majorMinor, matchAny, matchTopic, routeTopic, systemSchema, systemTopic, topicConfigOf };
package/package.json CHANGED
@@ -1,9 +1,29 @@
1
1
  {
2
2
  "name": "@isoloop/protocol",
3
- "version": "0.0.0",
4
- "description": "Placeholder for @isoloop/protocol. Real releases come from https://github.com/isoloop/isoloop.",
3
+ "version": "0.1.0-next.0",
4
+ "description": "Wire protocol types and guards shared by every Isoloop package.",
5
5
  "license": "MIT",
6
- "repository": { "type": "git", "url": "git+https://github.com/isoloop/isoloop.git", "directory": "packages/protocol" },
7
- "homepage": "https://github.com/isoloop/isoloop",
8
- "publishConfig": { "access": "public" }
9
- }
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/isoloop/isoloop.git",
11
+ "directory": "packages/protocol"
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ }
21
+ },
22
+ "devDependencies": {
23
+ "typescript": "7.0.2"
24
+ },
25
+ "scripts": {
26
+ "build": "tsdown --platform neutral --dts",
27
+ "typecheck": "tsc --noEmit"
28
+ }
29
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # @isoloop/protocol
2
-
3
- Placeholder. Real releases are published from [isoloop/isoloop](https://github.com/isoloop/isoloop).