@pritzlaff/nano-core 0.0.0-stage → 0.2.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 Aaron Pritzlaff
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.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @pritzlaff/nano-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lift ordinary code into named coordinates that can be called, published from, subscribed to and observed.
4
+
5
+ | File | Purpose |
6
+ |---|---|
7
+ | `src/data.ts` | Names and plain data: `Op`, `Coord`, `Result`, `Event`, `Subscription`, `Delta`. |
8
+ | `src/component.ts` | Wraps plain code: how to make a value, and the actions over it. |
9
+ | `src/env.ts` | An instance's view of the registries it is in: one handle each, and its own ops. |
10
+ | `src/registry.ts` | One place holding instances and subscriptions; reports every change as a `Delta`. |
11
+ | `src/runtime.ts` | Calls and publishes by name over one registry; wrap it with a `Policy` to change the rules. |
12
+
13
+ ## A counter
14
+
15
+ ```ts
16
+ let counter = 0
17
+ const increment = () => { counter = counter + 1 }
18
+
19
+ const Updated = Ops.source('com.acme', 'counter-updated', Type.Number())
20
+ const Inc = Ops.sink('com.acme', 'inc', Type.Null())
21
+
22
+ const Counter = Components.create({ ns: 'com.acme', name: 'counter' }, () => ({ get: () => counter, increment }))
23
+ Counter.action(Updated, c => c.get()) // a source's action reads the current value
24
+ Counter.action(Inc, c => { c.increment() }, { emits: [Updated] }) // after inc, publish what Updated reads
25
+
26
+ const rt = Runtimes.create(Registries.create('r'))
27
+ rt.registry.add('counter', Components.instantiate(Counter))
28
+ await rt.call({ registry: 'r', instance: 'me' }, 'counter', Ops.key(Inc), null)
29
+ ```
30
+
31
+ The registry is in itself as the instance `registry`. Its changes (`instance-added`, `op-added`,
32
+ `subscription-opened`, …) are events from it, so watching a registry is subscribing to it, and changing one
33
+ is calling it. `test/examples.test.ts` walks through watching, subscribing at runtime, one instance in two
34
+ registries, a "subscribe only yourself" policy, and adding ops at runtime.
package/component.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ import type { Static, TSchema } from 'typebox';
2
+ import { type Op, type Result } from './data.js';
3
+ import { type Environment } from './env.js';
4
+ type StaticOf<T> = T extends TSchema ? Static<T> : void;
5
+ /** What an action does: given the instance, the argument and the environment, produce the output. */
6
+ export type Run<A, I = any, O = any> = (instance: A, arg: I, env: Environment) => O | Promise<O>;
7
+ /** An op bound to a run. With no run, it is a source that is only published by `notify`. */
8
+ export type Action<A> = {
9
+ op: Op;
10
+ run?: Run<A>;
11
+ emits?: Op[];
12
+ };
13
+ /** A definition: how to make an A, and the actions over it. */
14
+ export type Component<A = any> = {
15
+ id: {
16
+ ns: string;
17
+ name: string;
18
+ };
19
+ make(env: Environment): A;
20
+ actions: Map<string, Action<A>>;
21
+ action<I extends TSchema | undefined, O extends TSchema | undefined>(op: Op<I, O>, run?: Run<A, StaticOf<I>, StaticOf<O>>, opts?: {
22
+ emits?: Op[];
23
+ }): 'added' | 'replaced';
24
+ };
25
+ /** One made value, with its own copy of the actions and its environment. */
26
+ export type Instance<A = any> = {
27
+ component: Component<A>;
28
+ value: A;
29
+ actions: Map<string, Action<A>>;
30
+ env: Environment;
31
+ };
32
+ /** Makes components, instances of them, and invokes their actions. */
33
+ export declare const Components: {
34
+ create<A>(id: {
35
+ ns: string;
36
+ name: string;
37
+ }, make: (env: Environment) => A): Component<A>;
38
+ instantiate<A>(component: Component<A>): Instance<A>;
39
+ /** Runs the action, then publishes each op it emits with that op's own reading. The action stands if an emit fails. */
40
+ invoke(inst: Instance, key: string, arg: unknown): Promise<Result>;
41
+ };
42
+ export {};
package/data.d.ts ADDED
@@ -0,0 +1,72 @@
1
+ import type { TSchema } from 'typebox';
2
+ type S = TSchema | undefined;
3
+ /** A named operation a component offers. With input and output it is an action, output only a source, input only a sink. */
4
+ export type Op<I extends S = S, O extends S = S> = {
5
+ ns: string;
6
+ name: string;
7
+ input?: I;
8
+ output?: O;
9
+ };
10
+ /** A value as JSON with sorted keys: equal data gives equal strings (schemas included). */
11
+ export declare const canonical: (value: unknown) => string;
12
+ /** Makes ops and names them. */
13
+ export declare const Ops: {
14
+ action: <I extends TSchema, O extends TSchema>(ns: string, name: string, input: I, output: O) => Op<I, O>;
15
+ source: <O extends TSchema>(ns: string, name: string, output: O) => Op<undefined, O>;
16
+ sink: <I extends TSchema>(ns: string, name: string, input: I) => Op<I, undefined>;
17
+ /** The op's coordinate, used wherever an op is referred to by name. */
18
+ key: (op: Pick<Op, 'ns' | 'name'>) => string;
19
+ /** Can what `from` outputs be given to `to`? Its input takes anything, or is the same type, name included. */
20
+ fits: (from: Op, to: Op) => boolean;
21
+ };
22
+ /** Where an instance lives: a registry and an instance id within it. */
23
+ export type Coord = {
24
+ registry: string;
25
+ instance: string;
26
+ };
27
+ /** The outcome of anything that can fail: a value, or an error message. */
28
+ export type Result<A = unknown> = {
29
+ value: A;
30
+ detail?: unknown;
31
+ } | {
32
+ error: string;
33
+ detail?: unknown;
34
+ };
35
+ /** A success. */
36
+ export declare const ok: <A>(value: A, detail?: unknown) => Result<A>;
37
+ /** A failure, with a message. */
38
+ export declare const err: (error: string, detail?: unknown) => Result<never>;
39
+ /** Whether a Result is a success. */
40
+ export declare const isOk: <A>(r: Result<A>) => r is {
41
+ value: A;
42
+ detail?: unknown;
43
+ };
44
+ /** Something an instance published: who, which op (by key), and the data. */
45
+ export type Event = {
46
+ from: Coord;
47
+ op: string;
48
+ data: unknown;
49
+ correlation?: string;
50
+ };
51
+ /** A named connection: when `source` (or any, '*') publishes `op`, call `listener`'s `target` action with the data. */
52
+ export type Subscription = {
53
+ id: string;
54
+ source: string;
55
+ op: string;
56
+ listener: string;
57
+ target: string;
58
+ };
59
+ /** A change to a registry, published from the registry itself. */
60
+ export type Delta = {
61
+ type: 'instance-added' | 'instance-removed';
62
+ instance: string;
63
+ ops: string[];
64
+ } | {
65
+ type: 'op-added' | 'op-removed';
66
+ instance: string;
67
+ op: string;
68
+ } | {
69
+ type: 'subscription-opened' | 'subscription-closed';
70
+ subscription: Subscription;
71
+ };
72
+ export {};
package/env.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { Action } from './component.js';
2
+ import { type Coord, type Op, type Result } from './data.js';
3
+ /** One registry as seen by an instance in it: its coordinate there, and how to publish and call. */
4
+ export type Handle = {
5
+ coord: Coord;
6
+ notify(op: Op, data: unknown, correlation?: string): Promise<Result<Result[]>>;
7
+ call(target: string, op: Op, arg: unknown): Promise<Result>;
8
+ };
9
+ /** Tells a registry that the instance's ops changed. */
10
+ export type Announce = (type: 'op-added' | 'op-removed', op: Op) => void;
11
+ /** All the registries an instance is in. It publishes to each, and lets the instance add or drop its own ops. */
12
+ export type Environment = {
13
+ handles(): Handle[];
14
+ added(h: Handle, announce: Announce): void;
15
+ removed(coord: Coord): void;
16
+ notify(op: Op, data: unknown, correlation?: string): Promise<Result<Result[]>[]>;
17
+ register(op: Op, run?: Action<any>['run'], opts?: {
18
+ emits?: Op[];
19
+ }): 'added' | 'replaced';
20
+ unregister(op: Op): boolean;
21
+ };
22
+ /** Makes the environment over an instance's action map. */
23
+ export declare const Environments: {
24
+ create(actions: Map<string, Action<any>>): Environment;
25
+ };
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './data.js';
2
+ export * from './component.js';
3
+ export * from './env.js';
4
+ export * from './registry.js';
5
+ export * from './runtime.js';
package/index.js ADDED
@@ -0,0 +1,289 @@
1
+ // packages/core/src/data.ts
2
+ var sorted = (v) => Array.isArray(v) ? v.map(sorted) : v && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sorted(v[k])])) : v;
3
+ var canonical = (value) => JSON.stringify(sorted(value));
4
+ var anything = (s) => Object.keys(s).every((k) => k === "title");
5
+ var Ops = {
6
+ action: (ns, name, input, output) => ({ ns, name, input, output }),
7
+ source: (ns, name, output) => ({ ns, name, output }),
8
+ sink: (ns, name, input) => ({ ns, name, input }),
9
+ key: (op) => `${op.ns}/${op.name}`,
10
+ fits: (from, to) => !!from.output && !!to.input && (anything(to.input) || canonical(from.output) === canonical(to.input))
11
+ };
12
+ var ok = (value, detail) => detail === undefined ? { value } : { value, detail };
13
+ var err = (error, detail) => detail === undefined ? { error } : { error, detail };
14
+ var isOk = (r) => ("value" in r);
15
+ // packages/core/src/env.ts
16
+ var same = (a, b) => a.registry === b.registry && a.instance === b.instance;
17
+ var Environments = {
18
+ create(actions) {
19
+ let members = [];
20
+ const tell = (type, op) => members.forEach((m) => m.announce(type, op));
21
+ return {
22
+ handles: () => members.map((m) => m.h),
23
+ added: (h, announce) => {
24
+ if (!members.some((m) => same(m.h.coord, h.coord)))
25
+ members.push({ h, announce });
26
+ },
27
+ removed: (coord) => {
28
+ members = members.filter((m) => !same(m.h.coord, coord));
29
+ },
30
+ notify: (op, data, correlation) => Promise.all(members.map((m) => m.h.notify(op, data, correlation))),
31
+ register(op, run, opts) {
32
+ const had = actions.has(Ops.key(op));
33
+ actions.set(Ops.key(op), { op, run, emits: opts?.emits });
34
+ tell("op-added", op);
35
+ return had ? "replaced" : "added";
36
+ },
37
+ unregister(op) {
38
+ const had = actions.delete(Ops.key(op));
39
+ if (had)
40
+ tell("op-removed", op);
41
+ return had;
42
+ }
43
+ };
44
+ }
45
+ };
46
+
47
+ // packages/core/src/component.ts
48
+ var message = (e) => e instanceof Error ? e.message : String(e);
49
+ async function run(inst, key, arg) {
50
+ const a = inst.actions.get(key);
51
+ if (!a?.run)
52
+ return err(`unknown op ${key}`);
53
+ try {
54
+ return ok(await a.run(inst.value, arg, inst.env));
55
+ } catch (e) {
56
+ return err(message(e));
57
+ }
58
+ }
59
+ var Components = {
60
+ create(id, make) {
61
+ const actions = new Map;
62
+ return {
63
+ id,
64
+ make,
65
+ actions,
66
+ action(op, run2, opts) {
67
+ const had = actions.has(Ops.key(op));
68
+ actions.set(Ops.key(op), { op, run: run2, emits: opts?.emits });
69
+ return had ? "replaced" : "added";
70
+ }
71
+ };
72
+ },
73
+ instantiate(component) {
74
+ const actions = new Map(component.actions), env = Environments.create(actions);
75
+ return { component, value: component.make(env), actions, env };
76
+ },
77
+ async invoke(inst, key, arg) {
78
+ const emits = inst.actions.get(key)?.emits ?? [];
79
+ const r = await run(inst, key, arg);
80
+ if (!isOk(r))
81
+ return r;
82
+ const failed = [];
83
+ for (const op of emits) {
84
+ const read = await run(inst, Ops.key(op), undefined);
85
+ if (!isOk(read)) {
86
+ failed.push(read);
87
+ continue;
88
+ }
89
+ for (const sent of await inst.env.notify(op, read.value))
90
+ if (!isOk(sent))
91
+ failed.push(sent);
92
+ }
93
+ return failed.length ? ok(r.value, { emits: failed }) : r;
94
+ }
95
+ };
96
+ // packages/core/src/registry.ts
97
+ var Registries = {
98
+ create(id) {
99
+ const instances = new Map, subs = new Map;
100
+ const listeners = new Set;
101
+ const index = new Map, seq = new Map;
102
+ let n = 0;
103
+ const bucket = (source, op) => index.get(`${source} ${op}`) ?? index.set(`${source} ${op}`, new Set).get(`${source} ${op}`);
104
+ const emit = (d) => listeners.forEach((fn) => fn(d));
105
+ const keys = (inst) => [...inst.actions.keys()];
106
+ const close = (s) => {
107
+ subs.delete(s.id);
108
+ bucket(s.source, s.op).delete(s);
109
+ seq.delete(s);
110
+ emit({ type: "subscription-closed", subscription: s });
111
+ };
112
+ return {
113
+ id,
114
+ get: (i) => instances.get(i),
115
+ add(i, inst) {
116
+ if (instances.has(i))
117
+ return err(`${i} is already in ${id}`);
118
+ instances.set(i, inst);
119
+ emit({ type: "instance-added", instance: i, ops: keys(inst) });
120
+ return ok(undefined);
121
+ },
122
+ remove(i) {
123
+ const inst = instances.get(i);
124
+ if (!inst)
125
+ return err(`no instance ${i} in ${id}`);
126
+ for (const s of [...subs.values()])
127
+ if (s.listener === i)
128
+ close(s);
129
+ instances.delete(i);
130
+ emit({ type: "instance-removed", instance: i, ops: keys(inst) });
131
+ return ok(undefined);
132
+ },
133
+ subscribe(s) {
134
+ if (!instances.has(s.listener))
135
+ return err(`no listener ${s.listener} in ${id}`);
136
+ const sub = { id: crypto.randomUUID(), ...s };
137
+ subs.set(sub.id, sub);
138
+ bucket(sub.source, sub.op).add(sub);
139
+ seq.set(sub, n++);
140
+ emit({ type: "subscription-opened", subscription: sub });
141
+ return ok(sub);
142
+ },
143
+ unsubscribe(sid) {
144
+ const s = subs.get(sid);
145
+ if (!s)
146
+ return err(`no subscription ${sid} in ${id}`);
147
+ close(s);
148
+ return ok(undefined);
149
+ },
150
+ announce(i, type, op) {
151
+ if (!instances.has(i))
152
+ return err(`no instance ${i} in ${id}`);
153
+ emit({ type, instance: i, op: Ops.key(op) });
154
+ return ok(undefined);
155
+ },
156
+ matching: (source, op) => [...index.get(`* ${op}`) ?? [], ...source === "*" ? [] : index.get(`${source} ${op}`) ?? []].sort((a, b) => seq.get(a) - seq.get(b)),
157
+ snapshot: () => ({
158
+ id,
159
+ instances: [...instances].map(([i, inst]) => ({ id: i, ops: [...inst.actions.values()].map((a) => a.op) })),
160
+ subscriptions: [...subs.values()]
161
+ }),
162
+ listen(fn) {
163
+ listeners.add(fn);
164
+ return () => {
165
+ listeners.delete(fn);
166
+ };
167
+ }
168
+ };
169
+ }
170
+ };
171
+ // packages/core/src/runtime.ts
172
+ import { Type } from "typebox";
173
+ import { Value } from "typebox/value";
174
+ var any = Type.Unknown();
175
+ var deltas = ["instance-added", "instance-removed", "op-added", "op-removed", "subscription-opened", "subscription-closed"];
176
+ var RegistryOps = {
177
+ add: Ops.action("composable", "add", Type.Object({ id: Type.String(), instance: any }), any),
178
+ remove: Ops.action("composable", "remove", Type.String(), any),
179
+ subscribe: Ops.action("composable", "subscribe", Type.Object({ source: Type.String(), op: Type.String(), listener: Type.String(), target: Type.String() }), any),
180
+ unsubscribe: Ops.action("composable", "unsubscribe", Type.String(), any),
181
+ snapshot: Ops.action("composable", "snapshot", Type.Null(), any),
182
+ deltas: Object.fromEntries(deltas.map((d) => [d, Ops.source("composable", d, any)]))
183
+ };
184
+ var must = (r) => {
185
+ if (!isOk(r))
186
+ throw new Error(r.error);
187
+ return r.value;
188
+ };
189
+ function registryComponent(registry) {
190
+ const c = Components.create({ ns: "composable", name: "registry" }, () => registry);
191
+ c.action(RegistryOps.add, (r, a) => must(r.add(a.id, a.instance)));
192
+ c.action(RegistryOps.remove, (r, id) => must(r.remove(id)));
193
+ c.action(RegistryOps.subscribe, (r, s) => must(r.subscribe(s)));
194
+ c.action(RegistryOps.unsubscribe, (r, id) => must(r.unsubscribe(id)));
195
+ c.action(RegistryOps.snapshot, (r) => r.snapshot());
196
+ for (const op of Object.values(RegistryOps.deltas))
197
+ c.action(op);
198
+ return c;
199
+ }
200
+ function create(registry, policy) {
201
+ if (registry.get("registry"))
202
+ throw new Error(`registry ${registry.id} already has a runtime`);
203
+ const at = (instance) => ({ registry: registry.id, instance });
204
+ const listeners = new Set;
205
+ const tell = (t) => listeners.forEach((fn) => {
206
+ try {
207
+ fn(t);
208
+ } catch (e) {
209
+ reportError(e);
210
+ }
211
+ });
212
+ const run2 = async (target, op, arg) => {
213
+ const inst = registry.get(target), a = inst?.actions.get(op);
214
+ if (!inst || !a)
215
+ return err(inst ? `unknown op ${op}` : `no instance ${target} in ${registry.id}`);
216
+ if (a.op.input && !Value.Check(a.op.input, arg))
217
+ return err(`invalid input for ${op}`);
218
+ return Components.invoke(inst, op, arg);
219
+ };
220
+ const base = {
221
+ registry,
222
+ async call(from, target, op, arg) {
223
+ const result = await run2(target, op, arg);
224
+ tell({ kind: "call", time: Date.now(), from, target, op, data: arg, result });
225
+ return result;
226
+ },
227
+ listen(fn) {
228
+ listeners.add(fn);
229
+ return () => {
230
+ listeners.delete(fn);
231
+ };
232
+ },
233
+ async notify(e) {
234
+ const a = registry.get(e.from.instance)?.actions.get(e.op);
235
+ const refuse = (error) => {
236
+ const result2 = err(error);
237
+ tell({ kind: "publish", time: Date.now(), from: e.from, op: e.op, data: e.data, result: result2 });
238
+ return result2;
239
+ };
240
+ if (e.from.registry !== registry.id || !a)
241
+ return refuse(`${e.from.instance} does not publish ${e.op} in ${registry.id}`);
242
+ if (a.op.output && !Value.Check(a.op.output, e.data))
243
+ return refuse(`invalid data for ${e.op}`);
244
+ const results = [];
245
+ for (const s of registry.matching(e.from.instance, e.op)) {
246
+ const result2 = await run2(s.listener, s.target, e.data);
247
+ tell({ kind: "delivery", time: Date.now(), from: e.from, target: s.listener, op: s.target, data: e.data, subscription: s.id, result: result2 });
248
+ results.push(result2);
249
+ }
250
+ const result = { value: results };
251
+ tell({ kind: "publish", time: Date.now(), from: e.from, op: e.op, data: e.data, result });
252
+ return result;
253
+ }
254
+ };
255
+ const outer = policy ? policy(base) : base;
256
+ const envs = new Map;
257
+ registry.listen((d) => {
258
+ if (d.type === "instance-added") {
259
+ const env = registry.get(d.instance).env, coord = at(d.instance);
260
+ envs.set(d.instance, env);
261
+ env.added({ coord, notify: (op, data, correlation) => outer.notify({ from: coord, op: Ops.key(op), data, correlation }), call: (t, op, arg) => outer.call(coord, t, Ops.key(op), arg) }, (type, op) => {
262
+ registry.announce(d.instance, type, op);
263
+ });
264
+ }
265
+ if (d.type === "instance-removed") {
266
+ envs.get(d.instance)?.removed(at(d.instance));
267
+ envs.delete(d.instance);
268
+ }
269
+ outer.notify({ from: at("registry"), op: `composable/${d.type}`, data: d });
270
+ });
271
+ registry.add("registry", Components.instantiate(registryComponent(registry)));
272
+ return outer;
273
+ }
274
+ var Runtimes = { create };
275
+ export {
276
+ ok,
277
+ isOk,
278
+ err,
279
+ canonical,
280
+ Runtimes,
281
+ RegistryOps,
282
+ Registries,
283
+ Ops,
284
+ Environments,
285
+ Components
286
+ };
287
+
288
+ //# debugId=7DE4B4DB1C70AABE64756E2164756E21
289
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/data.ts", "../src/env.ts", "../src/component.ts", "../src/registry.ts", "../src/runtime.ts"],
4
+ "sourcesContent": [
5
+ "// The plain data of the core: names for operations and places, results, events, subscriptions and changes.\nimport type { TSchema } from 'typebox'\n\ntype S = TSchema | undefined\n\n/** A named operation a component offers. With input and output it is an action, output only a source, input only a sink. */\nexport type Op<I extends S = S, O extends S = S> = { ns: string; name: string; input?: I; output?: O }\n\nconst sorted = (v: unknown): unknown =>\n Array.isArray(v) ? v.map(sorted)\n : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, sorted((v as Record<string, unknown>)[k])]))\n : v\n\n/** A value as JSON with sorted keys: equal data gives equal strings (schemas included). */\nexport const canonical = (value: unknown): string => JSON.stringify(sorted(value))\n\n/** A schema that accepts any value: no constraints besides, at most, a name. */\nconst anything = (s: TSchema) => Object.keys(s).every(k => k === 'title')\n\n/** Makes ops and names them. */\nexport const Ops = {\n action: <I extends TSchema, O extends TSchema>(ns: string, name: string, input: I, output: O): Op<I, O> => ({ ns, name, input, output }),\n source: <O extends TSchema>(ns: string, name: string, output: O): Op<undefined, O> => ({ ns, name, output }),\n sink: <I extends TSchema>(ns: string, name: string, input: I): Op<I, undefined> => ({ ns, name, input }),\n /** The op's coordinate, used wherever an op is referred to by name. */\n key: (op: Pick<Op, 'ns' | 'name'>): string => `${op.ns}/${op.name}`,\n /** Can what `from` outputs be given to `to`? Its input takes anything, or is the same type, name included. */\n fits: (from: Op, to: Op): boolean =>\n !!from.output && !!to.input && (anything(to.input) || canonical(from.output) === canonical(to.input)),\n}\n\n/** Where an instance lives: a registry and an instance id within it. */\nexport type Coord = { registry: string; instance: string }\n\n/** The outcome of anything that can fail: a value, or an error message. */\nexport type Result<A = unknown> = { value: A; detail?: unknown } | { error: string; detail?: unknown }\n\n/** A success. */\nexport const ok = <A>(value: A, detail?: unknown): Result<A> => (detail === undefined ? { value } : { value, detail })\n/** A failure, with a message. */\nexport const err = (error: string, detail?: unknown): Result<never> => (detail === undefined ? { error } : { error, detail })\n/** Whether a Result is a success. */\nexport const isOk = <A>(r: Result<A>): r is { value: A; detail?: unknown } => 'value' in r\n\n/** Something an instance published: who, which op (by key), and the data. */\nexport type Event = { from: Coord; op: string; data: unknown; correlation?: string }\n\n/** A named connection: when `source` (or any, '*') publishes `op`, call `listener`'s `target` action with the data. */\nexport type Subscription = { id: string; source: string; op: string; listener: string; target: string }\n\n/** A change to a registry, published from the registry itself. */\nexport type Delta =\n | { type: 'instance-added' | 'instance-removed'; instance: string; ops: string[] }\n | { type: 'op-added' | 'op-removed'; instance: string; op: string }\n | { type: 'subscription-opened' | 'subscription-closed'; subscription: Subscription }\n",
6
+ "// An instance's view of the registries it is in: one handle per registry, and its own ops.\nimport type { Action } from './component'\nimport { Ops, type Coord, type Op, type Result } from './data'\n\n/** One registry as seen by an instance in it: its coordinate there, and how to publish and call. */\nexport type Handle = {\n coord: Coord\n notify(op: Op, data: unknown, correlation?: string): Promise<Result<Result[]>>\n call(target: string, op: Op, arg: unknown): Promise<Result>\n}\n\n/** Tells a registry that the instance's ops changed. */\nexport type Announce = (type: 'op-added' | 'op-removed', op: Op) => void\n\n/** All the registries an instance is in. It publishes to each, and lets the instance add or drop its own ops. */\nexport type Environment = {\n handles(): Handle[]\n added(h: Handle, announce: Announce): void\n removed(coord: Coord): void\n notify(op: Op, data: unknown, correlation?: string): Promise<Result<Result[]>[]>\n register(op: Op, run?: Action<any>['run'], opts?: { emits?: Op[] }): 'added' | 'replaced'\n unregister(op: Op): boolean\n}\n\nconst same = (a: Coord, b: Coord) => a.registry === b.registry && a.instance === b.instance\n\n/** Makes the environment over an instance's action map. */\nexport const Environments = {\n create(actions: Map<string, Action<any>>): Environment {\n let members: { h: Handle; announce: Announce }[] = []\n const tell = (type: 'op-added' | 'op-removed', op: Op) => members.forEach(m => m.announce(type, op))\n return {\n handles: () => members.map(m => m.h),\n added: (h, announce) => { if (!members.some(m => same(m.h.coord, h.coord))) members.push({ h, announce }) },\n removed: coord => { members = members.filter(m => !same(m.h.coord, coord)) },\n notify: (op, data, correlation) => Promise.all(members.map(m => m.h.notify(op, data, correlation))),\n register(op, run, opts) {\n const had = actions.has(Ops.key(op))\n actions.set(Ops.key(op), { op, run, emits: opts?.emits })\n tell('op-added', op)\n return had ? 'replaced' : 'added'\n },\n unregister(op) {\n const had = actions.delete(Ops.key(op))\n if (had) tell('op-removed', op)\n return had\n },\n }\n },\n}\n",
7
+ "// Wraps plain code: how to make a value, and the actions over it, each named by an op.\nimport type { Static, TSchema } from 'typebox'\nimport { err, isOk, ok, Ops, type Op, type Result } from './data'\nimport { Environments, type Environment } from './env'\n\ntype StaticOf<T> = T extends TSchema ? Static<T> : void\n\n/** What an action does: given the instance, the argument and the environment, produce the output. */\nexport type Run<A, I = any, O = any> = (instance: A, arg: I, env: Environment) => O | Promise<O>\n\n/** An op bound to a run. With no run, it is a source that is only published by `notify`. */\nexport type Action<A> = { op: Op; run?: Run<A>; emits?: Op[] }\n\n/** A definition: how to make an A, and the actions over it. */\nexport type Component<A = any> = {\n id: { ns: string; name: string }\n make(env: Environment): A\n actions: Map<string, Action<A>>\n action<I extends TSchema | undefined, O extends TSchema | undefined>(op: Op<I, O>, run?: Run<A, StaticOf<I>, StaticOf<O>>, opts?: { emits?: Op[] }): 'added' | 'replaced'\n}\n\n/** One made value, with its own copy of the actions and its environment. */\nexport type Instance<A = any> = { component: Component<A>; value: A; actions: Map<string, Action<A>>; env: Environment }\n\nconst message = (e: unknown) => (e instanceof Error ? e.message : String(e))\n\n/** Runs one op on an instance; a throw becomes an error. */\nasync function run<A>(inst: Instance<A>, key: string, arg: unknown): Promise<Result> {\n const a = inst.actions.get(key)\n if (!a?.run) return err(`unknown op ${key}`)\n try { return ok(await a.run(inst.value, arg, inst.env)) } catch (e) { return err(message(e)) }\n}\n\n/** Makes components, instances of them, and invokes their actions. */\nexport const Components = {\n create<A>(id: { ns: string; name: string }, make: (env: Environment) => A): Component<A> {\n const actions = new Map<string, Action<A>>()\n return {\n id, make, actions,\n action(op, run, opts) {\n const had = actions.has(Ops.key(op))\n actions.set(Ops.key(op), { op, run: run as Run<A>, emits: opts?.emits })\n return had ? 'replaced' : 'added'\n },\n }\n },\n\n instantiate<A>(component: Component<A>): Instance<A> {\n const actions = new Map(component.actions), env = Environments.create(actions)\n return { component, value: component.make(env), actions, env }\n },\n\n /** Runs the action, then publishes each op it emits with that op's own reading. The action stands if an emit fails. */\n async invoke(inst: Instance, key: string, arg: unknown): Promise<Result> {\n const emits = inst.actions.get(key)?.emits ?? [] // read first: the action may unregister itself\n const r = await run(inst, key, arg)\n if (!isOk(r)) return r\n const failed: Result[] = []\n for (const op of emits) {\n const read = await run(inst, Ops.key(op), undefined)\n if (!isOk(read)) { failed.push(read); continue }\n for (const sent of await inst.env.notify(op, read.value)) if (!isOk(sent)) failed.push(sent)\n }\n return failed.length ? ok(r.value, { emits: failed }) : r\n },\n}\n",
8
+ "// One place holding instances by id, and the subscriptions between them. Data only: it never runs an action.\nimport type { Instance } from './component'\nimport { err, ok, Ops, type Delta, type Op, type Result, type Subscription } from './data'\n\n/** What a registry holds, as plain data. */\nexport type Snapshot = { id: string; instances: { id: string; ops: Op[] }[]; subscriptions: Subscription[] }\n\n/** Stores instances and subscriptions, and tells its listeners about every change as a Delta. */\nexport type Registry = {\n id: string\n get(id: string): Instance | undefined\n add(id: string, inst: Instance): Result<void>\n remove(id: string): Result<void>\n subscribe(s: Omit<Subscription, 'id'>): Result<Subscription>\n unsubscribe(id: string): Result<void>\n /** The subscriptions a publish of `op` by `source` reaches. */\n matching(source: string, op: string): Subscription[]\n snapshot(): Snapshot\n /** Records that an instance's ops changed; refused for an unknown instance. */\n announce(instance: string, type: 'op-added' | 'op-removed', op: Op): Result<void>\n listen(fn: (d: Delta) => void): () => void\n}\n\n/** Makes an empty registry. */\nexport const Registries = {\n create(id: string): Registry {\n const instances = new Map<string, Instance>(), subs = new Map<string, Subscription>()\n const listeners = new Set<(d: Delta) => void>()\n // subscriptions by `source op`, so a publish looks at its matches only; seq keeps them in subscription order\n const index = new Map<string, Set<Subscription>>(), seq = new Map<Subscription, number>()\n let n = 0\n const bucket = (source: string, op: string) => index.get(`${source} ${op}`) ?? index.set(`${source} ${op}`, new Set()).get(`${source} ${op}`)!\n const emit = (d: Delta) => listeners.forEach(fn => fn(d))\n const keys = (inst: Instance) => [...inst.actions.keys()]\n const close = (s: Subscription) => { subs.delete(s.id); bucket(s.source, s.op).delete(s); seq.delete(s); emit({ type: 'subscription-closed', subscription: s }) }\n return {\n id,\n get: i => instances.get(i),\n add(i, inst) {\n if (instances.has(i)) return err(`${i} is already in ${id}`)\n instances.set(i, inst)\n emit({ type: 'instance-added', instance: i, ops: keys(inst) })\n return ok(undefined)\n },\n remove(i) {\n const inst = instances.get(i)\n if (!inst) return err(`no instance ${i} in ${id}`)\n for (const s of [...subs.values()]) if (s.listener === i) close(s)\n instances.delete(i)\n emit({ type: 'instance-removed', instance: i, ops: keys(inst) })\n return ok(undefined)\n },\n subscribe(s) {\n if (!instances.has(s.listener)) return err(`no listener ${s.listener} in ${id}`)\n const sub = { id: crypto.randomUUID(), ...s }\n subs.set(sub.id, sub); bucket(sub.source, sub.op).add(sub); seq.set(sub, n++)\n emit({ type: 'subscription-opened', subscription: sub })\n return ok(sub)\n },\n unsubscribe(sid) {\n const s = subs.get(sid)\n if (!s) return err(`no subscription ${sid} in ${id}`)\n close(s)\n return ok(undefined)\n },\n announce(i, type, op) {\n if (!instances.has(i)) return err(`no instance ${i} in ${id}`)\n emit({ type, instance: i, op: Ops.key(op) })\n return ok(undefined)\n },\n matching: (source, op) => [...(index.get(`* ${op}`) ?? []), ...(source === '*' ? [] : index.get(`${source} ${op}`) ?? [])].sort((a, b) => seq.get(a)! - seq.get(b)!),\n snapshot: () => ({\n id,\n instances: [...instances].map(([i, inst]) => ({ id: i, ops: [...inst.actions.values()].map(a => a.op) })),\n subscriptions: [...subs.values()],\n }),\n listen(fn) { listeners.add(fn); return () => { listeners.delete(fn) } },\n }\n },\n}\n",
9
+ "// Invokes actions and publishes events by coordinate, over one registry. Wrap it with a Policy to change the rules.\nimport { Type } from 'typebox'\nimport { Value } from 'typebox/value'\nimport { Components, type Instance } from './component'\nimport { err, isOk, Ops, type Coord, type Delta, type Event, type Result, type Subscription } from './data'\nimport type { Environment } from './env'\nimport type { Registry } from './registry'\n\n/** Calls and publishes by name within one registry. In-process, remote or policy-checked, it is these two functions. */\nexport type Runtime = {\n registry: Registry\n call(from: Coord, target: string, op: string, arg: unknown): Promise<Result>\n /** Outer Result: was the publish allowed. Inner: one Result per delivery. */\n notify(e: Event): Promise<Result<Result[]>>\n /** Tells `fn` about every call, publish and delivery as it ends. Returns a function that stops telling it. */\n listen(fn: (t: Trace) => void): () => void\n}\n\n/** One message through a runtime, as data: what a histogram, a live wire view or a replay is built from. */\nexport type Trace =\n | { kind: 'call'; time: number; from: Coord; target: string; op: string; data: unknown; result: Result }\n | { kind: 'publish'; time: number; from: Coord; op: string; data: unknown; result: Result<Result[]> }\n | { kind: 'delivery'; time: number; from: Coord; target: string; op: string; data: unknown; subscription: string; result: Result }\n\n/** Rules around a runtime: takes the runtime and returns one that enforces them. */\nexport type Policy = (inner: Runtime) => Runtime\n\nconst any = Type.Unknown()\nconst deltas = ['instance-added', 'instance-removed', 'op-added', 'op-removed', 'subscription-opened', 'subscription-closed'] as const\n\n/** The registry's own ops: change it, read it, and the changes it publishes. */\nexport const RegistryOps = {\n add: Ops.action('composable', 'add', Type.Object({ id: Type.String(), instance: any }), any),\n remove: Ops.action('composable', 'remove', Type.String(), any),\n subscribe: Ops.action('composable', 'subscribe', Type.Object({ source: Type.String(), op: Type.String(), listener: Type.String(), target: Type.String() }), any),\n unsubscribe: Ops.action('composable', 'unsubscribe', Type.String(), any),\n snapshot: Ops.action('composable', 'snapshot', Type.Null(), any),\n deltas: Object.fromEntries(deltas.map(d => [d, Ops.source('composable', d, any)])) as Record<Delta['type'], ReturnType<typeof Ops.source<typeof any>>>,\n}\n\nconst must = <A>(r: Result<A>): A => { if (!isOk(r)) throw new Error(r.error); return r.value }\n\n/** The registry, lifted like any other component, so it can be called and watched. */\nfunction registryComponent(registry: Registry) {\n const c = Components.create({ ns: 'composable', name: 'registry' }, () => registry)\n c.action(RegistryOps.add, (r, a) => must(r.add(a.id, a.instance as Instance)))\n c.action(RegistryOps.remove, (r, id) => must(r.remove(id)))\n c.action(RegistryOps.subscribe, (r, s) => must(r.subscribe(s)) as Subscription)\n c.action(RegistryOps.unsubscribe, (r, id) => must(r.unsubscribe(id)))\n c.action(RegistryOps.snapshot, r => r.snapshot())\n for (const op of Object.values(RegistryOps.deltas)) c.action(op)\n return c\n}\n\n/** Makes the runtime for a registry, adds the registry to itself as 'registry', and publishes its changes. */\nfunction create(registry: Registry, policy?: Policy): Runtime {\n if (registry.get('registry')) throw new Error(`registry ${registry.id} already has a runtime`)\n const at = (instance: string): Coord => ({ registry: registry.id, instance })\n const listeners = new Set<(t: Trace) => void>()\n // an observer can't change what happens: its error is reported, never thrown into the call or the delivery loop\n const tell = (t: Trace) => listeners.forEach(fn => { try { fn(t) } catch (e) { reportError(e) } })\n /** Runs `op` on `target`: the lookup and input check every call and delivery share. */\n const run = async (target: string, op: string, arg: unknown): Promise<Result> => {\n const inst = registry.get(target), a = inst?.actions.get(op)\n if (!inst || !a) return err(inst ? `unknown op ${op}` : `no instance ${target} in ${registry.id}`)\n if (a.op.input && !Value.Check(a.op.input, arg)) return err(`invalid input for ${op}`)\n return Components.invoke(inst, op, arg)\n }\n const base: Runtime = {\n registry,\n async call(from, target, op, arg) {\n const result = await run(target, op, arg)\n tell({ kind: 'call', time: Date.now(), from, target, op, data: arg, result })\n return result\n },\n listen(fn) { listeners.add(fn); return () => { listeners.delete(fn) } },\n async notify(e) {\n const a = registry.get(e.from.instance)?.actions.get(e.op)\n const refuse = (error: string) => { // a refused publish is traced too, with its error\n const result = err(error)\n tell({ kind: 'publish', time: Date.now(), from: e.from, op: e.op, data: e.data, result })\n return result\n }\n if (e.from.registry !== registry.id || !a) return refuse(`${e.from.instance} does not publish ${e.op} in ${registry.id}`)\n if (a.op.output && !Value.Check(a.op.output, e.data)) return refuse(`invalid data for ${e.op}`)\n const results: Result[] = [] // a delivery is a call: same lookup, same input check\n for (const s of registry.matching(e.from.instance, e.op)) {\n const result = await run(s.listener, s.target, e.data)\n tell({ kind: 'delivery', time: Date.now(), from: e.from, target: s.listener, op: s.target, data: e.data, subscription: s.id, result })\n results.push(result)\n }\n const result = { value: results }\n tell({ kind: 'publish', time: Date.now(), from: e.from, op: e.op, data: e.data, result })\n return result\n },\n }\n const outer = policy ? policy(base) : base\n const envs = new Map<string, Environment>()\n registry.listen(d => {\n if (d.type === 'instance-added') {\n const env = registry.get(d.instance)!.env, coord = at(d.instance)\n envs.set(d.instance, env)\n env.added(\n { coord, notify: (op, data, correlation) => outer.notify({ from: coord, op: Ops.key(op), data, correlation }), call: (t, op, arg) => outer.call(coord, t, Ops.key(op), arg) },\n (type, op) => { registry.announce(d.instance, type, op) },\n )\n }\n if (d.type === 'instance-removed') { envs.get(d.instance)?.removed(at(d.instance)); envs.delete(d.instance) }\n void outer.notify({ from: at('registry'), op: `composable/${d.type}`, data: d })\n })\n registry.add('registry', Components.instantiate(registryComponent(registry)))\n return outer\n}\n\n/** Makes runtimes. */\nexport const Runtimes = { create }\n"
10
+ ],
11
+ "mappings": ";AAQA,IAAM,SAAS,CAAC,MACd,MAAM,QAAQ,CAAC,IAAI,EAAE,IAAI,MAAM,IAC7B,KAAK,OAAO,MAAM,WAAW,OAAO,YAAY,OAAO,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,OAAK,CAAC,GAAG,OAAQ,EAA8B,EAAE,CAAC,CAAC,CAAC,IAC9H;AAGG,IAAM,YAAY,CAAC,UAA2B,KAAK,UAAU,OAAO,KAAK,CAAC;AAGjF,IAAM,WAAW,CAAC,MAAe,OAAO,KAAK,CAAC,EAAE,MAAM,OAAK,MAAM,OAAO;AAGjE,IAAM,MAAM;AAAA,EACjB,QAAQ,CAAuC,IAAY,MAAc,OAAU,YAAyB,EAAE,IAAI,MAAM,OAAO,OAAO;AAAA,EACtI,QAAQ,CAAoB,IAAY,MAAc,YAAiC,EAAE,IAAI,MAAM,OAAO;AAAA,EAC1G,MAAM,CAAoB,IAAY,MAAc,WAAgC,EAAE,IAAI,MAAM,MAAM;AAAA,EAEtG,KAAK,CAAC,OAAwC,GAAG,GAAG,MAAM,GAAG;AAAA,EAE7D,MAAM,CAAC,MAAU,OACf,CAAC,CAAC,KAAK,UAAU,CAAC,CAAC,GAAG,UAAU,SAAS,GAAG,KAAK,KAAK,UAAU,KAAK,MAAM,MAAM,UAAU,GAAG,KAAK;AACvG;AASO,IAAM,KAAK,CAAI,OAAU,WAAiC,WAAW,YAAY,EAAE,MAAM,IAAI,EAAE,OAAO,OAAO;AAE7G,IAAM,MAAM,CAAC,OAAe,WAAqC,WAAW,YAAY,EAAE,MAAM,IAAI,EAAE,OAAO,OAAO;AAEpH,IAAM,OAA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A,EACA,MAAM,QAAQ,SAAS,OAAO,IAAI,IAAI;AAAA,EACtC,MAAM,OAAO,IAAI;AAAA,EACjB,SAAS,OAAO,OAAK;AAAA,IACnB,IAAI,EAAE,SAAS,kBAAkB;AAAA,MAC/B,MAAM,MAAM,SAAS,IAAI,EAAE,QAAQ,EAAG,KAAK,QAAQ,GAAG,EAAE,QAAQ;AAAA,MAChE,KAAK,IAAI,EAAE,UAAU,GAAG;AAAA,MACxB,IAAI,MACF,EAAE,OAAO,QAAQ,CAAC,IAAI,MAAM,gBAAgB,MAAM,OAAO,EAAE,MAAM,OAAO,IAAI,IAAI,IAAI,EAAE,GAAG,MAAM,YAAY,CAAC,GAAG,MAAM,CAAC,GAAG,IAAI,QAAQ,MAAM,KAAK,OAAO,GAAG,IAAI,IAAI,EAAE,GAAG,GAAG,EAAE,GAC5K,CAAC,MAAM,OAAO;AAAA,QAAE,SAAS,SAAS,EAAE,UAAU,MAAM,EAAE;AAAA,OACxD;AAAA,IACF;AAAA,IACA,IAAI,EAAE,SAAS,oBAAoB;AAAA,MAAE,KAAK,IAAI,EAAE,QAAQ,GAAG,QAAQ,GAAG,EAAE,QAAQ,CAAC;AAAA,MAAG,KAAK,OAAO,EAAE,QAAQ;AAAA,IAAE;AAAA,IACvG,MAAM,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,cAAc,EAAE,QAAQ,MAAM,EAAE,CAAC;AAAA,GAChF;AAAA,EACD,SAAS,IAAI,YAAY,WAAW,YAAY,kBAAkB,QAAQ,CAAC,CAAC;AAAA,EAC5E,OAAO;AAAA;AAIF,IAAM,WAAW,EAAE,OAAO;",
12
+ "debugId": "7DE4B4DB1C70AABE64756E2164756E21",
13
+ "names": []
14
+ }
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@pritzlaff/nano-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/aaronp/nano.git",
9
+ "directory": "packages/core"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./index.d.ts",
14
+ "import": "./index.js"
15
+ }
16
+ },
17
+ "types": "./index.d.ts",
18
+ "module": "./index.js",
19
+ "sideEffects": false,
20
+ "peerDependencies": {
21
+ "typebox": "^1.4.0"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ }
26
+ }
package/registry.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ import type { Instance } from './component.js';
2
+ import { type Delta, type Op, type Result, type Subscription } from './data.js';
3
+ /** What a registry holds, as plain data. */
4
+ export type Snapshot = {
5
+ id: string;
6
+ instances: {
7
+ id: string;
8
+ ops: Op[];
9
+ }[];
10
+ subscriptions: Subscription[];
11
+ };
12
+ /** Stores instances and subscriptions, and tells its listeners about every change as a Delta. */
13
+ export type Registry = {
14
+ id: string;
15
+ get(id: string): Instance | undefined;
16
+ add(id: string, inst: Instance): Result<void>;
17
+ remove(id: string): Result<void>;
18
+ subscribe(s: Omit<Subscription, 'id'>): Result<Subscription>;
19
+ unsubscribe(id: string): Result<void>;
20
+ /** The subscriptions a publish of `op` by `source` reaches. */
21
+ matching(source: string, op: string): Subscription[];
22
+ snapshot(): Snapshot;
23
+ /** Records that an instance's ops changed; refused for an unknown instance. */
24
+ announce(instance: string, type: 'op-added' | 'op-removed', op: Op): Result<void>;
25
+ listen(fn: (d: Delta) => void): () => void;
26
+ };
27
+ /** Makes an empty registry. */
28
+ export declare const Registries: {
29
+ create(id: string): Registry;
30
+ };
package/runtime.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { Type } from 'typebox';
2
+ import { Ops, type Coord, type Delta, type Event, type Result } from './data.js';
3
+ import type { Registry } from './registry.js';
4
+ /** Calls and publishes by name within one registry. In-process, remote or policy-checked, it is these two functions. */
5
+ export type Runtime = {
6
+ registry: Registry;
7
+ call(from: Coord, target: string, op: string, arg: unknown): Promise<Result>;
8
+ /** Outer Result: was the publish allowed. Inner: one Result per delivery. */
9
+ notify(e: Event): Promise<Result<Result[]>>;
10
+ /** Tells `fn` about every call, publish and delivery as it ends. Returns a function that stops telling it. */
11
+ listen(fn: (t: Trace) => void): () => void;
12
+ };
13
+ /** One message through a runtime, as data: what a histogram, a live wire view or a replay is built from. */
14
+ export type Trace = {
15
+ kind: 'call';
16
+ time: number;
17
+ from: Coord;
18
+ target: string;
19
+ op: string;
20
+ data: unknown;
21
+ result: Result;
22
+ } | {
23
+ kind: 'publish';
24
+ time: number;
25
+ from: Coord;
26
+ op: string;
27
+ data: unknown;
28
+ result: Result<Result[]>;
29
+ } | {
30
+ kind: 'delivery';
31
+ time: number;
32
+ from: Coord;
33
+ target: string;
34
+ op: string;
35
+ data: unknown;
36
+ subscription: string;
37
+ result: Result;
38
+ };
39
+ /** Rules around a runtime: takes the runtime and returns one that enforces them. */
40
+ export type Policy = (inner: Runtime) => Runtime;
41
+ declare const any: Type.TUnknown;
42
+ /** The registry's own ops: change it, read it, and the changes it publishes. */
43
+ export declare const RegistryOps: {
44
+ add: import("./data.js").Op<Type.TObject<{
45
+ id: Type.TString;
46
+ instance: Type.TUnknown;
47
+ }>, Type.TUnknown>;
48
+ remove: import("./data.js").Op<Type.TString, Type.TUnknown>;
49
+ subscribe: import("./data.js").Op<Type.TObject<{
50
+ source: Type.TString;
51
+ op: Type.TString;
52
+ listener: Type.TString;
53
+ target: Type.TString;
54
+ }>, Type.TUnknown>;
55
+ unsubscribe: import("./data.js").Op<Type.TString, Type.TUnknown>;
56
+ snapshot: import("./data.js").Op<Type.TNull, Type.TUnknown>;
57
+ deltas: Record<Delta['type'], ReturnType<typeof Ops.source<typeof any>>>;
58
+ };
59
+ /** Makes the runtime for a registry, adds the registry to itself as 'registry', and publishes its changes. */
60
+ declare function create(registry: Registry, policy?: Policy): Runtime;
61
+ /** Makes runtimes. */
62
+ export declare const Runtimes: {
63
+ create: typeof create;
64
+ };
65
+ export {};