@isoloop/bus 0.0.0-next.56111e3

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.
@@ -0,0 +1,16 @@
1
+ // src/standard-schema.ts
2
+ const segmentKey = (s) => typeof s === "object" ? s.key : s;
3
+ /**
4
+ * Maps schema issues to the cloneable `{ message, path }[]` sent with `invalid`
5
+ * (ADR 0003, decision 10). Symbol keys become their description.
6
+ */
7
+ function toIssues(issues) {
8
+ return issues.map((i) => ({
9
+ message: i.message,
10
+ path: (i.path ?? []).map((s) => {
11
+ const k = segmentKey(s);
12
+ return typeof k === "symbol" ? String(k) : k;
13
+ })
14
+ }));
15
+ }
16
+ export { toIssues as t };
@@ -0,0 +1,28 @@
1
+ import { n as Contracts } from "./topic-Cxr8oyfH.js";
2
+ import { Issue } from "@isoloop/protocol";
3
+ /** Sample values for one topic. An array is shorthand for `{ values }`. */
4
+ export type TopicSamples = readonly unknown[] | {
5
+ values: readonly unknown[];
6
+ replies?: readonly unknown[];
7
+ };
8
+ export type ContractProblem = {
9
+ topic: string;
10
+ /** `value` for the topic schema, `reply` for its reply schema. */
11
+ schema: "value" | "reply";
12
+ /** Index of the sample, or -1 for `no_samples`. */
13
+ sample: number;
14
+ /**
15
+ * `invalid`: the schema rejected the sample. `not_plain`: its output isn't
16
+ * plain, structured-cloneable data. `no_samples`: the topic has none.
17
+ */
18
+ kind: "invalid" | "not_plain" | "no_samples";
19
+ message: string;
20
+ issues?: Issue[];
21
+ };
22
+ /**
23
+ * Runs sample values through every schema in a contracts list and reports
24
+ * samples the schema rejects and outputs that aren't plain, cloneable data
25
+ * (ADR 0003, decision 11). The broker only checks cloneability in dev builds,
26
+ * so run this in the contracts package's tests. An empty result means all good.
27
+ */
28
+ export declare function testContracts(list: Contracts, samples: Readonly<Record<string, TopicSamples>>): Promise<ContractProblem[]>;
@@ -0,0 +1,98 @@
1
+ import { t as toIssues } from "./standard-schema-DnJtEmJw.js";
2
+ // src/testing.ts
3
+ const PLAIN_TAGS = /* @__PURE__ */ new Set([
4
+ "[object Date]",
5
+ "[object RegExp]",
6
+ "[object ArrayBuffer]",
7
+ "[object Boolean]",
8
+ "[object Number]",
9
+ "[object String]"
10
+ ]);
11
+ /**
12
+ * Finds the first part of `v` that isn't plain data: functions, symbols, and
13
+ * objects other than plain objects, arrays, Map, Set, Date, RegExp, ArrayBuffer
14
+ * and its views. Class instances clone without their prototype, so they count.
15
+ */
16
+ function notPlain(v, path, seen) {
17
+ if (typeof v === "function") return `${path} is a function`;
18
+ if (typeof v === "symbol") return `${path} is a symbol`;
19
+ if (typeof v !== "object" || v === null) return void 0;
20
+ if (seen.has(v)) return void 0;
21
+ seen.add(v);
22
+ if (Array.isArray(v)) {
23
+ for (const [i, x] of v.entries()) {
24
+ const p = notPlain(x, `${path}[${i}]`, seen);
25
+ if (p) return p;
26
+ }
27
+ return;
28
+ }
29
+ if (v instanceof Map) {
30
+ for (const [k, x] of v) {
31
+ const p = notPlain(k, `${path} key`, seen) ?? notPlain(x, `${path}.get(${String(k)})`, seen);
32
+ if (p) return p;
33
+ }
34
+ return;
35
+ }
36
+ if (v instanceof Set) {
37
+ for (const x of v) {
38
+ const p = notPlain(x, `${path} entry`, seen);
39
+ if (p) return p;
40
+ }
41
+ return;
42
+ }
43
+ if (ArrayBuffer.isView(v) || PLAIN_TAGS.has(Object.prototype.toString.call(v))) return void 0;
44
+ const proto = Object.getPrototypeOf(v);
45
+ if (proto !== Object.prototype && proto !== null) return `${path} is an instance of ${v.constructor?.name ?? "unknown"}`;
46
+ for (const [k, x] of Object.entries(v)) {
47
+ const p = notPlain(x, `${path}.${k}`, seen);
48
+ if (p) return p;
49
+ }
50
+ }
51
+ async function check(topic, which, schema, samples) {
52
+ return (await Promise.all(samples.map(async (v) => schema["~standard"].validate(v)))).flatMap((result, sample) => {
53
+ if (result.issues) return [{
54
+ topic,
55
+ schema: which,
56
+ sample,
57
+ kind: "invalid",
58
+ message: `sample ${sample} was rejected`,
59
+ issues: toIssues(result.issues)
60
+ }];
61
+ const problem = notPlain(result.value, "output", /* @__PURE__ */ new Set());
62
+ return problem ? [{
63
+ topic,
64
+ schema: which,
65
+ sample,
66
+ kind: "not_plain",
67
+ message: problem
68
+ }] : [];
69
+ });
70
+ }
71
+ const isList = (s) => Array.isArray(s);
72
+ /**
73
+ * Runs sample values through every schema in a contracts list and reports
74
+ * samples the schema rejects and outputs that aren't plain, cloneable data
75
+ * (ADR 0003, decision 11). The broker only checks cloneability in dev builds,
76
+ * so run this in the contracts package's tests. An empty result means all good.
77
+ */
78
+ async function testContracts(list, samples) {
79
+ return (await Promise.all(list.topics.map(async (t) => {
80
+ const s = samples[t.name] ?? [];
81
+ const values = isList(s) ? s : s.values;
82
+ const replies = isList(s) ? [] : s.replies ?? [];
83
+ const none = values.length === 0 ? [{
84
+ topic: t.name,
85
+ schema: "value",
86
+ sample: -1,
87
+ kind: "no_samples",
88
+ message: "no samples"
89
+ }] : [];
90
+ const [v, r] = await Promise.all([check(t.name, "value", t.schema, values), t.reply ? check(t.name, "reply", t.reply, replies) : []]);
91
+ return [
92
+ ...none,
93
+ ...v,
94
+ ...r
95
+ ];
96
+ }))).flat();
97
+ }
98
+ export { testContracts };
@@ -0,0 +1,127 @@
1
+ import { BusRecord, ErrorCode, Issue as Issue$1, Retention, Retention as Retention$1, TopicConfig } from "@isoloop/protocol";
2
+ /**
3
+ * The Standard Schema V1 interface (https://standardschema.dev), vendored so
4
+ * the bus depends on no schema library (ADR 0003, decision 1). Zod 4, Valibot
5
+ * and ArkType implement it. Copied from the spec; keep it in step with it.
6
+ */
7
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
8
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
9
+ }
10
+ declare namespace StandardSchemaV1 {
11
+ export interface Props<Input = unknown, Output = Input> {
12
+ readonly version: 1;
13
+ readonly vendor: string;
14
+ readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
15
+ readonly types?: Types<Input, Output> | undefined;
16
+ }
17
+ export type Result<Output> = SuccessResult<Output> | FailureResult;
18
+ export interface SuccessResult<Output> {
19
+ readonly value: Output;
20
+ readonly issues?: undefined;
21
+ }
22
+ export interface FailureResult {
23
+ readonly issues: ReadonlyArray<Issue>;
24
+ }
25
+ export interface Issue {
26
+ readonly message: string;
27
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
28
+ }
29
+ export interface PathSegment {
30
+ readonly key: PropertyKey;
31
+ }
32
+ export interface Types<Input = unknown, Output = Input> {
33
+ readonly input: Input;
34
+ readonly output: Output;
35
+ }
36
+ export type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
37
+ export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
38
+ }
39
+ /**
40
+ * Maps schema issues to the cloneable `{ message, path }[]` sent with `invalid`
41
+ * (ADR 0003, decision 10). Symbol keys become their description.
42
+ */
43
+ declare function toIssues(issues: ReadonlyArray<StandardSchemaV1.Issue>): Issue$1[];
44
+ /** Default `maxRecordBytes`: 256 KiB (design §6.1). */
45
+ declare const DEFAULT_MAX_RECORD_BYTES: number;
46
+ /**
47
+ * A topic: its name, schema and log policy (design §6.1). Publishers are typed
48
+ * with `In`, subscribers with `Out`, because the log stores the schema's
49
+ * validated output (ADR 0003, decision 11). `RIn`/`ROut` type `bus.request`
50
+ * replies; a topic without `reply` can't be requested.
51
+ */
52
+ type TopicDef<In, Out = In, RIn = never, ROut = RIn> = {
53
+ /** Carries the major version, e.g. `cart.items.v1` (ADR 0003, decision 17). */
54
+ readonly name: string;
55
+ /** Required. `unchecked<T>()` is the explicit opt-out. */
56
+ readonly schema: StandardSchemaV1<In, Out>;
57
+ /** Required for `bus.request`. */
58
+ readonly reply?: StandardSchemaV1<RIn, ROut>;
59
+ readonly retention: Retention;
60
+ /** Rough structured size limit per record. Default 256 KiB. */
61
+ readonly maxRecordBytes?: number;
62
+ /**
63
+ * Default `memory`. `persistent` keeps the topic in OPFS (ADR 0007): it
64
+ * survives a bus crash and a reload. Where OPFS isn't available, or another
65
+ * tab holds it, it behaves as `memory` and the kernel emits
66
+ * `bus:durability-degraded`.
67
+ */
68
+ readonly durability?: "memory" | "persistent";
69
+ /**
70
+ * Starts this topic from an older one (ADR 0003, decision 18). On the first
71
+ * boot where this topic is empty and `from` has records, the bus copies
72
+ * them through `map` and this topic's schema before it opens: its publishes
73
+ * wait and its subscribers get nothing until then. `map` must be pure and
74
+ * synchronous. `follow` keeps mapping new `from` records afterwards.
75
+ */
76
+ readonly seed?: {
77
+ readonly from: AnyTopicDef;
78
+ readonly map: (value: any, record: BusRecord) => In;
79
+ readonly follow?: boolean;
80
+ };
81
+ };
82
+ type AnyTopicDef = TopicDef<any, any, any, any>;
83
+ /** What a publisher passes. */
84
+ type InputOf<D> = D extends TopicDef<infer In, any, any, any> ? In : never;
85
+ /** What a subscriber receives. */
86
+ type OutputOf<D> = D extends TopicDef<any, infer Out, any, any> ? Out : never;
87
+ /** What a responder passes to `reply`. */
88
+ type ReplyInputOf<D> = D extends TopicDef<any, any, infer RIn, any> ? RIn : never;
89
+ /** What a requester receives. */
90
+ type ReplyOutputOf<D> = D extends TopicDef<any, any, any, infer ROut> ? ROut : never;
91
+ /** Defines a topic. Types come from the schemas. */
92
+ declare function topic<In, Out = In, RIn = never, ROut = RIn>(name: string, def: Omit<TopicDef<In, Out, RIn, ROut>, "name">): TopicDef<In, Out, RIn, ROut>;
93
+ /**
94
+ * A Standard Schema that accepts any value unchanged and only carries the type
95
+ * (ADR 0003, decision 2). Tools list topics that use it.
96
+ */
97
+ declare function unchecked<T>(): StandardSchemaV1<T, T>;
98
+ /** True if the schema came from `unchecked()`. */
99
+ declare function isUnchecked(schema: StandardSchemaV1): boolean;
100
+ /**
101
+ * The default export of a contracts module (ADR 0003, decision 4). Built only
102
+ * by `contracts()`, so the bus worker can tell it from any other export.
103
+ */
104
+ type Contracts = {
105
+ /** Brand, so the bus worker can tell a contracts list from any other export. */
106
+ readonly "~isoloop": "contracts";
107
+ readonly topics: readonly AnyTopicDef[];
108
+ /** Looks a topic up by name. */
109
+ get(name: string): AnyTopicDef | undefined;
110
+ };
111
+ /** A contracts list that can't be built: duplicate or reserved names, or a bad definition. */
112
+ declare class ContractsError extends Error {
113
+ readonly code: ErrorCode;
114
+ /** The topics at fault. */
115
+ readonly topics: readonly string[];
116
+ constructor(code: ErrorCode, message: string, topics: readonly string[]);
117
+ }
118
+ /**
119
+ * Builds the contracts list. Rejects duplicate names and `isoloop.*` topics,
120
+ * which belong to the kernel (ADR 0003, decisions 4 and 6).
121
+ */
122
+ declare function contracts(...topics: AnyTopicDef[]): Contracts;
123
+ /** True for a value built by `contracts()`, from any copy of this package. */
124
+ declare function isContracts(x: unknown): x is Contracts;
125
+ /** The structured-cloneable part of a topic, sent at `boot` for the contracts check (ADR 0003, decision 5). */
126
+ declare function topicConfig(t: AnyTopicDef): TopicConfig;
127
+ export { StandardSchemaV1 as _, InputOf as a, ReplyOutputOf as c, contracts as d, isContracts as f, unchecked as g, topicConfig as h, DEFAULT_MAX_RECORD_BYTES as i, Retention$1 as l, topic as m, Contracts as n, OutputOf as o, isUnchecked as p, ContractsError as r, ReplyInputOf as s, AnyTopicDef as t, TopicDef as u, toIssues as v };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@isoloop/bus",
3
+ "version": "0.0.0-next.56111e3",
4
+ "description": "Log bus that runs in its own worker: topics, schemas, offsets, replay.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/isoloop/isoloop.git",
11
+ "directory": "packages/bus"
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ },
21
+ "./testing": {
22
+ "types": "./dist/testing.d.ts",
23
+ "import": "./dist/testing.js"
24
+ },
25
+ "./worker": {
26
+ "import": "./dist/bus-worker.js"
27
+ }
28
+ },
29
+ "dependencies": {
30
+ "@isoloop/codec": "0.0.0-next.56111e3",
31
+ "@isoloop/protocol": "0.0.0-next.56111e3"
32
+ },
33
+ "devDependencies": {
34
+ "fast-check": "4.10.2",
35
+ "typescript": "7.0.2",
36
+ "valibot": "1.5.0",
37
+ "zod": "4.6.7"
38
+ },
39
+ "scripts": {
40
+ "build": "tsdown",
41
+ "typecheck": "tsc --noEmit"
42
+ }
43
+ }