@synapse-sdk/client 0.3.3 → 0.3.4

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/dist/synapse.js CHANGED
@@ -2,17 +2,17 @@
2
2
  // loop (`node.ts`) drives sessions; publishers, registrations, subscriptions and namespaces are their
3
3
  // own tasks, told about sessions by the loop; every fact about the world is read from the current
4
4
  // `Session` (the runtime's statement) at the moment it is asked for, never copied here.
5
- import { ClockSync, SynapseError, ageOf, defaultDomId, fecSymbolSizeFor, isServiceContract, nowUs, resolveTopic, serviceName, toLocalUs, } from "@synapse-sdk/core";
6
- import { callStream, startOn } from "./calls.js";
7
- import { Node, resolveTarget, startNode } from "./node.js";
5
+ import { SynapseError, ageOf, fecSymbolSizeFor, isServiceContract, nowUs, resolveTopic, serviceName, } from "@synapse-sdk/core";
6
+ import { callStream, failedRun, startOn } from "./calls.js";
7
+ import { Node, createNode, endpointDial, resolveTarget } from "./node.js";
8
8
  import { ServiceRegistration } from "./serve.js";
9
9
  import { openScene } from "./scene.js";
10
10
  import { Namespace, StoreHandleImpl, attachStore, openStore } from "./store.js";
11
11
  import { TasksFacet } from "./tasks.js";
12
12
  import { PublisherHandle, TopicPublisher, TopicSubscription, wasmFor } from "./topics.js";
13
13
  import { TopicView } from "./view.js";
14
- /** How long the first `connect()` keeps trying a retryable failure before `failed` (SDK §2: the first connect is bounded). */
15
- export const FIRST_CONNECT_GIVE_UP_MS = 30_000;
14
+ import { watchState } from "./util.js";
15
+ export { FIRST_CONNECT_GIVE_UP_MS } from "./node.js";
16
16
  /** The descriptor a publisher of `contract` on node `n` declares (as `TopicPublisher` builds it: a `fec` symbol size of 0 is the node's). */
17
17
  function wantedDesc(contract, n) {
18
18
  const d = contract.desc(n.dom);
@@ -24,73 +24,140 @@ function wantedDesc(contract, n) {
24
24
  function descKey(d) {
25
25
  return JSON.stringify({ delivery: d.delivery, content_type: d.content_type, schema_hash: d.schema_hash ?? null, fec: d.fec ?? null });
26
26
  }
27
+ /**
28
+ * A fact of the node as a state value (`node.status`, `node.catalog`, `node.project`): `read` is the fact now, the same
29
+ * object while it is unchanged. It changes with the node's link and, while connected, with the current session's values
30
+ * that `watched` names; a callback is rebound to the new session's values on every link change.
31
+ */
32
+ class NodeCell {
33
+ node;
34
+ read;
35
+ watched;
36
+ constructor(node, read, watched) {
37
+ this.node = node;
38
+ this.read = read;
39
+ this.watched = watched;
40
+ }
41
+ get() { return this.read(); }
42
+ /** `cb` with the value on each change of what it is read from; returns the remover. */
43
+ onChange(cb) {
44
+ const listener = () => cb(this.read());
45
+ let un = [];
46
+ const bind = () => {
47
+ for (const u of un)
48
+ u();
49
+ const s = this.node.currentSession();
50
+ un = s ? this.watched(s).map(c => c.subscribe(listener)) : [];
51
+ };
52
+ bind();
53
+ const unLink = this.node.link.subscribe(() => { bind(); listener(); });
54
+ return () => { unLink(); for (const u of un)
55
+ u(); };
56
+ }
57
+ /** The value after its next change; once the node ends, the value then, whether or not it changed (nothing will change any more). */
58
+ changed() {
59
+ const from = this.read();
60
+ if (this.node.isEnded)
61
+ return Promise.resolve(from);
62
+ return new Promise(resolve => {
63
+ let done = false;
64
+ const finish = (v) => { if (done)
65
+ return; done = true; un(); resolve(v); };
66
+ const un = this.onChange(v => { if (v !== from)
67
+ finish(v); });
68
+ void this.node.ended.promise.then(() => finish(this.read()));
69
+ });
70
+ }
71
+ /** The value after each change; ends when the node ends. */
72
+ watch() { return watchState(cb => this.onChange(cb), this.read, () => this.node.isEnded); }
73
+ }
74
+ const NO_TOPICS = Object.freeze({});
75
+ const NO_SERVICES = Object.freeze({});
27
76
  export class Synapse {
28
77
  #node;
29
- #connecting;
30
- #starting;
31
78
  #publishers = new Map();
32
79
  #stores = new Map();
33
80
  warn;
34
- // Private: the options hold the token and the credential, which nothing prints.
35
- #opts;
81
+ /**
82
+ * The node, usable at once and `idle` (no target) until `connect()`: constructing opens no connection. Where to connect
83
+ * (the url, its token, the certificate pin) is the target's, given to `connect()`. Throws `invalid_input` for options
84
+ * that can never work (a bad `name`).
85
+ */
36
86
  constructor(opts) {
37
- this.#opts = opts;
38
87
  this.warn = msg => console.warn(`[synapse] ${msg}`);
88
+ const n = this.#node = createNode(opts);
89
+ let lastLink = n.link.get(), lastState = n.state();
90
+ this.status = new NodeCell(n, () => {
91
+ const l = n.link.get();
92
+ if (l !== lastLink) {
93
+ lastLink = l;
94
+ lastState = n.state();
95
+ }
96
+ return lastState;
97
+ }, () => []);
98
+ let lastCatalog;
99
+ this.catalog = new NodeCell(n, () => {
100
+ const s = n.currentSession();
101
+ const topics = s?.topics.get().topics ?? NO_TOPICS, services = s?.services.get().services ?? NO_SERVICES;
102
+ if (lastCatalog?.topics !== topics || lastCatalog.services !== services)
103
+ lastCatalog = { topics, services, describe: name => services[name]?.card };
104
+ return lastCatalog;
105
+ }, s => [s.topics, s.services]);
106
+ this.project = new NodeCell(n, () => n.currentSession()?.project.get(), s => [s.project]);
39
107
  }
40
- /** `await Synapse.connect(opts)`: a node with a session, or the reason there is none. */
41
- static connect(opts) { return new Synapse(opts).connect(); }
42
- /** Connects (once; later calls return the same promise). Resolves once a session is established. */
43
- connect() {
44
- this.#connecting ??= (async () => {
45
- const started = startNode(this.#opts, FIRST_CONNECT_GIVE_UP_MS);
46
- // The node as soon as its loop runs (or none: the options were refused), for a `close()` during the first dial.
47
- this.#starting = started.then(s => s.node, () => undefined);
48
- const { node, connected } = await started;
49
- await connected;
50
- this.#node = node;
51
- return this;
52
- })();
53
- return this.#connecting;
54
- }
55
- get node() {
56
- if (!this.#node)
57
- throw new SynapseError("not_connected", "connect() has not completed");
58
- return this.#node;
59
- }
60
- #session() { return this.node.currentSession(); }
61
- // ------------------------------------------------------------------------------ lifecycle
62
- get status() { return this.#node?.state() ?? { status: "connecting", attempt: 1 }; }
63
- get connected() { return this.#node?.isConnected ?? false; }
64
- /** Called on every change of the connection state; returns the unsubscribe. */
65
- watchStatus(cb) { return this.node.link.subscribe(() => cb(this.node.state())); }
66
- /** Resolves on the next connected session (at once if connected); rejects once the node ended. */
67
- whenConnected() {
68
- const n = this.node;
69
- if (n.isConnected)
70
- return Promise.resolve();
108
+ /**
109
+ * Connects the node to `target` (a string is the url), the one connect verb: the first connect, and how an HMI moves
110
+ * from one robot's runtime to another. The current session, if any, is torn down before `target` is dialed; every
111
+ * handle re-binds to the new session as across a reconnect. Identity fields `target` leaves out keep the node's.
112
+ *
113
+ * Operator intent is never lost under quick clicking: the newest call wins. The node works toward its latest target; a
114
+ * call superseded by a newer `connect()` or `disconnect()` resolves quietly. The target already declared declares
115
+ * nothing and settles with it, except from its own `failed`, where it is dialed again.
116
+ *
117
+ * Bounded (SDK §2): a retryable failure is tried again, paced by the reconnect policy, until `FIRST_CONNECT_GIVE_UP_MS`
118
+ * after the first attempt, a hard bound (an attempt still outstanding then is cut); `unauthorized` gives up at once.
119
+ * Resolves once a session to *this* target is connected (or a newer call superseded it). Rejects with this target's
120
+ * error when the node rests `failed` (still usable: `connect()` dials again), `invalid_input` at once for a malformed
121
+ * target, `not_connected` once the node has ended (`close()`).
122
+ *
123
+ * With no target: the declared target, if there is one (settles with it, as above), else `SYNAPSE_ENDPOINT` (Bun/Node;
124
+ * the runtime sets it for every task it starts); neither (or a browser) is `invalid_input` and the node stays `idle`.
125
+ *
126
+ * The outcome is handled: `node.connect(url);` without a handler is safe (`useConnection()` shows `failed`); `await` still rejects.
127
+ */
128
+ connect(target) {
129
+ const n = this.#node;
130
+ let p;
71
131
  if (n.isEnded)
72
- return Promise.reject(new SynapseError("not_connected", "node closed"));
73
- return new Promise((resolve, reject) => {
74
- const un = n.link.subscribe(l => { if (l.status === "connected") {
75
- un();
76
- resolve();
77
- } });
78
- // The node's end settles it (a resolved promise ignores the later reject).
79
- void n.ended.promise.then(() => { un(); reject(new SynapseError("not_connected", "node closed")); });
80
- });
81
- }
82
- /** Declares a new target (broker, identity); resolves once connected to it (or rejects with why not). `null` disconnects for good. */
83
- setTarget(target) { return this.node.setTarget(target ? resolveTarget(this.node, target) : undefined); }
84
- /** Tells the runtime we are leaving, ends every handle, and resolves once the node has ended. */
85
- /** During the first `connect()` it ends that attempt: the node ends `closed` and `connect()` rejects `not_connected`. */
86
- async close() {
87
- const n = this.#node ?? (await this.#starting);
88
- if (n)
89
- await n.close();
132
+ p = Promise.reject(new SynapseError("not_connected", "node closed"));
133
+ else {
134
+ let dial;
135
+ try {
136
+ dial = target === undefined ? (n.target.get().dial ?? endpointDial(n)) : resolveTarget(n, typeof target === "string" ? { url: target } : target);
137
+ }
138
+ catch (e) {
139
+ return Promise.reject(e);
140
+ }
141
+ p = n.declare(dial).then(() => this);
142
+ }
143
+ p.catch(() => { });
144
+ return p;
90
145
  }
146
+ /**
147
+ * Disconnects: the session, if any, is torn down and the node rests `idle` (no target), not ended. Every handle is kept,
148
+ * exactly as between two sessions, and a later `connect()` dials again. A `connect()` still pursuing is superseded (it
149
+ * resolves quietly). Resolves once the session is gone; already `idle`: at once. `not_connected` once the node has ended.
150
+ */
151
+ disconnect() { return this.#node.declare(undefined); }
152
+ /** The node's engine (the SDK's own modules and tests use it). */
153
+ get node() { return this.#node; }
154
+ #session() { return this.#node.currentSession(); }
155
+ // ------------------------------------------------------------------------------ lifecycle
156
+ /** Where the node stands (`ConnectionState`), a state value: `get()` now, `onChange` for each change, `changed()` for the next one, `watch()` for each one in a loop. */
157
+ status;
158
+ /** Tells the runtime we are leaving, ends every handle, and resolves once the node has ended (`closed`, for good). A `connect()` in flight rejects `not_connected`. */
159
+ async close() { await this.#node.close(); }
91
160
  async [Symbol.asyncDispose]() { await this.close(); }
92
- /** Resolves once the node has ended (closed, failed, or the policy gave up). */
93
- get ended() { return this.node.ended.promise; }
94
161
  info() {
95
162
  const n = this.node;
96
163
  const id = n.target.get().identity;
@@ -98,21 +165,17 @@ export class Synapse {
98
165
  return { name: id.name ?? "", type: id.type, userId: id.user_id, prefix: s?.prefix ?? "", role: s?.role ?? "observer", dom: n.dom, brokerDom: s?.hello.dom ?? "", brokerVersion: s?.hello.broker_version ?? "", robot: s?.hello.robot ?? "", runtimeName: s?.hello.runtime_name ?? "", runtimeId: s?.hello.runtime_id ?? "", url: n.target.get().dial?.url ?? "" };
99
166
  }
100
167
  metrics() { const n = this.node; return { sessions: n.epochs, reconnects: n.reconnects, callsSent: n.callsSent, callsAnswered: n.callsAnswered }; }
101
- /** Broker notices addressed to this node (an error body on `res` without a call). */
102
- onNotice(cb) { this.node.notices.add(cb); return () => { this.node.notices.delete(cb); }; }
103
- /** `promoted`/`demoted` notices (WP §3.5). */
104
- onProjectNotice(cb) { this.node.projectNotices.add(cb); return () => { this.node.projectNotices.delete(cb); }; }
168
+ /** Notices addressed to this node: `cb` per notice (an error body on `res` without a call, and a refused live override claim of this node's scene); returns the unsubscribe. */
169
+ notices(cb) { this.node.notices.add(cb); return () => { this.node.notices.delete(cb); }; }
105
170
  // ---------------------------------------------------------------------------------- clock
106
171
  nowUs() { return nowUs(); }
107
- clock() { const s = this.#session(); return s ? s.clock.get() : new ClockSync(this.node.dom.id, "", 0).info(); }
108
- timeOffsets() { return this.#session()?.timeOffsets.get() ?? {}; }
109
- /** A publisher stamp in our clock (WP §7.4), when the offsets allow it. */
110
- toLocalUs(tUs, dom) { const s = this.#session(); return s ? toLocalUs(s.clock.get(), s.timeOffsets.get(), tUs, dom) : undefined; }
111
172
  /** How old a message is now, in our clock. */
112
173
  ageUs(env) { const s = this.#session(); return s ? ageOf(s.clock.get(), s.timeOffsets.get(), env.tUs, env.dom, nowUs()) : undefined; }
113
174
  async publisher(topic) {
114
175
  const contract = resolveTopic(topic);
115
176
  const n = this.node;
177
+ // Its descriptor names the node's time domain: final before any publisher is made.
178
+ await n.prepared;
116
179
  const name = contract.name;
117
180
  let p;
118
181
  let held;
@@ -157,9 +220,13 @@ export class Synapse {
157
220
  }
158
221
  return h;
159
222
  }
160
- subscribe(topic, opts = {}) {
223
+ subscribe(topic, cbOrOpts, opts = {}) {
161
224
  const contract = resolveTopic(topic);
162
- return new TopicSubscription(this.node, contract, opts, this.warn);
225
+ if (typeof cbOrOpts !== "function")
226
+ return new TopicSubscription(this.node, contract, cbOrOpts ?? {}, this.warn);
227
+ const sub = new TopicSubscription(this.node, contract, opts, this.warn);
228
+ sub.deliverTo(cbOrOpts);
229
+ return sub;
163
230
  }
164
231
  view(topic, opts = {}) {
165
232
  const contract = resolveTopic(topic);
@@ -169,7 +236,7 @@ export class Synapse {
169
236
  call(svc, args = {}, opts = {}) {
170
237
  const s = this.#session();
171
238
  if (!s)
172
- throw new SynapseError("not_connected", "no session: the call was not sent");
239
+ return failedRun(new SynapseError("not_connected", "no session: the call was not sent"));
173
240
  const contract = isServiceContract(svc) ? svc : undefined;
174
241
  return startOn(this.node, s, serviceName(svc), args, opts, contract);
175
242
  }
@@ -204,57 +271,57 @@ export class Synapse {
204
271
  // ---------------------------------------------------------------------------------- store
205
272
  /** Opens namespace `name` (SDK §9); resolves once the mirror is in (or the namespace is known absent). */
206
273
  store(name, opts = {}) { return openStore(this.node, this.#stores, name, opts, this.warn); }
207
- /** The runtime's `config` namespace (operators write it). */
208
- config(opts = {}) { return this.store("config", opts); }
209
274
  // ---------------------------------------------------------------------------------- scene
210
275
  #scenes = { current: undefined };
211
276
  /** The active project's scene (PLAN v0.24 §5); resolves attached, or at once `detached` when no project is active. */
212
277
  scene() { return openScene(this.node, this.#scenes, this.warn); }
213
278
  // -------------------------------------------------------------------------------- catalog
214
- /** The runtime's catalogs as the current session last read them; empty between sessions. */
215
- get catalog() {
216
- const s = this.#session();
217
- const topics = s?.topics.get().topics ?? {};
218
- const services = s?.services.get().services ?? {};
219
- return { topics, services, describe: name => services[name]?.card };
220
- }
221
- /** Called when either catalog changes on the current session. */
222
- watchCatalog(cb) {
223
- let un = [];
224
- const bind = () => {
225
- for (const u of un)
226
- u();
227
- un = [];
228
- const s = this.#session();
229
- if (!s)
230
- return;
231
- un.push(s.topics.subscribe(() => cb(this.catalog)), s.services.subscribe(() => cb(this.catalog)));
232
- };
233
- bind();
234
- const unLink = this.node.link.subscribe(() => { bind(); cb(this.catalog); });
235
- return () => { unLink(); for (const u of un)
236
- u(); };
237
- }
279
+ /** The runtime's catalogs as the current session last read them (empty between sessions), a state value: `get()` now, `onChange` for each change, `changed()` for the next one, `watch()` for each one in a loop. */
280
+ catalog;
238
281
  // -------------------------------------------------------------------------------- project
239
- /** The project state the current session last read (WP §3.5); `undefined` between sessions or before the first snapshot. */
240
- project() { return this.#session()?.project.get(); }
241
- watchProject(cb) {
242
- let un;
243
- const bind = () => { un?.(); un = this.#session()?.project.subscribe(p => cb(p)); };
244
- bind();
245
- const unLink = this.node.link.subscribe(() => { bind(); cb(this.project()); });
246
- return () => { unLink(); un?.(); };
282
+ /** The project state the current session last read (WP §3.5), a state value; `get()` is `undefined` between sessions or before the first snapshot. */
283
+ project;
284
+ /**
285
+ * A project call on the current session. The runtime tells a web session whose role it changed before it answers on
286
+ * it (the notice, then the answer, on the same `res` track, read in order) and closes it `role_changed` after: a role
287
+ * that differs from the session's hello grant means the switch is coming, and the call resolves once a session other
288
+ * than the one it went out on is connected (`not_connected` if the node ends or is disconnected meanwhile, the error
289
+ * if it rests `failed`). An hmi's role is `hmi` from admission and never changes, so its calls resolve on the answer.
290
+ */
291
+ async #projectCall(op, args) {
292
+ const n = this.node;
293
+ const asked = n.currentSession();
294
+ if (!asked)
295
+ throw new SynapseError("not_connected", "no session: the call was not sent");
296
+ const snapshot = await startOn(n, asked, `synapse/project/${op}`, args, {}).result;
297
+ if (asked.role !== asked.hello.role) {
298
+ // The runtime replaces this session (the role changed): its close is expected, as one we make ourselves, so
299
+ // @moq/net's track and discovery lines about it are routine (moq_log.ts).
300
+ asked.log?.closing();
301
+ await n.switchedFrom(asked);
302
+ }
303
+ return snapshot;
247
304
  }
248
- #projectCall(op, args) { return this.call(`synapse/project/${op}`, args).result; }
249
- /** `synapse/project/activate {id}`: activates `id` (or joins it when active); promoted to operator. */
305
+ /**
306
+ * `synapse/project/activate {id}`: activates `id` when no project is active, or joins it when it is the active one;
307
+ * `project_busy` while another project is active (no takeover: deactivate it first). A web node is promoted to
308
+ * operator and resolves once the session with the new role is connected; an hmi stays `hmi` and resolves on the answer.
309
+ */
250
310
  activateProject(id) { return this.#projectCall("activate", { id }); }
251
- /** `synapse/project/deactivate {}`: every operator is demoted. */
311
+ /**
312
+ * `synapse/project/deactivate {}`: any operator or hmi may deactivate, except a project an hmi activated
313
+ * (`active.activated_by_hmi`), which only an hmi may (`not_operator`). Every web operator is demoted; when that
314
+ * demotes this node, resolves once the demoted session is connected. An hmi is never demoted.
315
+ */
252
316
  deactivateProject() { return this.#projectCall("deactivate", {}); }
253
- /** `synapse/project/join {as: "operator"}`: promoted on the active project, or `project_inactive`. */
317
+ /** `synapse/project/join {as: "operator"}`: an operator of the active project, or `project_inactive`. A web node resolves once the promoted session is connected; an hmi on the answer. */
254
318
  joinProject(as = "operator") { return this.#projectCall("join", { as }); }
255
- /** `synapse/project/leave {}`: drops our standing (every session of our `user_id`). */
319
+ /**
320
+ * `synapse/project/leave {}`: drops our standing. For an hmi membership is per session: this session only (it stays
321
+ * `hmi`, never closed). For a web node it removes our `user_id`'s web sessions only; when that demotes this node,
322
+ * resolves once the demoted session is connected.
323
+ */
256
324
  leaveProject() { return this.#projectCall("leave", {}); }
257
- getProject() { return this.#projectCall("get", {}); }
258
325
  // -------------------------------------------------------------------------------- tasks
259
326
  #tasks;
260
327
  /**
package/dist/tasks.d.ts CHANGED
@@ -8,7 +8,7 @@ export declare const TASKS_NAMESPACES: {
8
8
  readonly status: "task_status";
9
9
  readonly catalog: "task_catalog";
10
10
  };
11
- /** What `status.value` is before the runtime said anything: neither scope's state known, no tasks. */
11
+ /** What `status.get()` is before the runtime said anything: neither scope's state known, no tasks. */
12
12
  export declare const EMPTY_TASKS_STATUS: TasksStatus;
13
13
  /**
14
14
  * `task_status`'s rows as a `TasksStatus`. A run row is the one keyed `robot` or `project`; an instance
package/dist/tasks.js CHANGED
@@ -7,9 +7,10 @@
7
7
  // unchanged part keeps its object.
8
8
  import { SynapseError } from "@synapse-sdk/core";
9
9
  import { replaceEqualDeep } from "./util.js";
10
+ import { ulid } from "./scene.js";
10
11
  /** The namespaces the facet reads and writes (the runtime's names). */
11
12
  export const TASKS_NAMESPACES = { declarations: "tasks", status: "task_status", catalog: "task_catalog" };
12
- /** What `status.value` is before the runtime said anything: neither scope's state known, no tasks. */
13
+ /** What `status.get()` is before the runtime said anything: neither scope's state known, no tasks. */
13
14
  export const EMPTY_TASKS_STATUS = { robot: { state: undefined, tasks: {} }, project: { state: undefined, tasks: {} } };
14
15
  const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
15
16
  /** A run row (`robot` / `project`: `{state, since, reason?}`) as the scope's run fields. */
@@ -49,7 +50,7 @@ export function tasksStatusOf(rows, unplaced = () => { }) {
49
50
  return { robot: { ...runOf(rows.robot), tasks: robot }, project: { ...runOf(rows.project), tasks: project } };
50
51
  }
51
52
  /**
52
- * A read-only handle over one namespace of the node: `value` is `derive` of the mirror, recomputed only
53
+ * A read-only handle over one namespace of the node: `get()` is `derive` of the mirror, recomputed only
53
54
  * when the mirror changed and shared structurally with the previous value. The namespace is opened on
54
55
  * the first touch of any member.
55
56
  */
@@ -65,8 +66,8 @@ class DerivedHandle {
65
66
  this.#value = empty;
66
67
  }
67
68
  #handle() { return (this.#h ??= this.open()); }
68
- get value() {
69
- const rows = this.#handle().value;
69
+ get() {
70
+ const rows = this.#handle().get();
70
71
  if (rows !== this.#from) {
71
72
  this.#from = rows;
72
73
  this.#value = replaceEqualDeep(this.#value, this.derive(rows));
@@ -77,9 +78,9 @@ class DerivedHandle {
77
78
  ready() { return this.#handle().ready(); }
78
79
  async *watch() {
79
80
  for await (const _ of this.#handle().watch())
80
- yield this.value;
81
+ yield this.get();
81
82
  }
82
- subscribe(listener) { return this.#handle().subscribe(listener); }
83
+ onChange(cb) { return this.#handle().onChange(() => cb(this.get())); }
83
84
  }
84
85
  /** The robot's declarations: the node's handle on `tasks`; every write waits for the value to be current first. */
85
86
  class Declarations {
@@ -89,20 +90,33 @@ class Declarations {
89
90
  this.open = open;
90
91
  }
91
92
  #handle() { return (this.#h ??= this.open()); }
92
- get value() { return this.#handle().value; }
93
- get(instance) { return this.#handle().get(instance); }
93
+ get(instance) {
94
+ const h = this.#handle();
95
+ return (instance === undefined ? h.get() : h.get(instance));
96
+ }
94
97
  get synced() { return this.#handle().synced; }
95
98
  get status() { return this.#handle().status; }
99
+ changed() { return this.#handle().changed(); }
96
100
  ready() { return this.#handle().ready(); }
97
101
  async set(a, b) {
98
102
  const h = this.#handle();
99
103
  await h.ready();
100
- await (typeof a === "string" ? h.set(a, b) : h.set(a));
104
+ if (typeof a === "string") {
105
+ await h.set(a, b);
106
+ return;
107
+ }
108
+ // One object: a declaration (its `ref` is a string) gets a minted instance; else it is a map of declarations.
109
+ if (typeof a.ref === "string") {
110
+ const instance = ulid();
111
+ await h.set(instance, a);
112
+ return instance;
113
+ }
114
+ await h.set(a);
101
115
  }
102
116
  async delete(instance) { const h = this.#handle(); await h.ready(); await h.delete(instance); }
103
117
  async clear() { const h = this.#handle(); await h.ready(); await h.clear(); }
104
118
  watch(instance) { return this.#handle().watch(instance); }
105
- subscribe(listener) { return this.#handle().subscribe(listener); }
119
+ onChange(cb) { return this.#handle().onChange(cb); }
106
120
  }
107
121
  /** `node.tasks`. `attach(name)` hands out the node's handle on a namespace; `call` starts a call on the current session. */
108
122
  export class TasksFacet {
package/dist/topics.d.ts CHANGED
@@ -147,5 +147,7 @@ export declare class TopicSubscription<T> implements Subscription<T> {
147
147
  /** Ends the subscription: the follow task stops, every track is closed, a pending `next()` returns `undefined`. */
148
148
  unsubscribe(): void;
149
149
  [Symbol.asyncDispose](): Promise<void>;
150
+ /** The callback form's read loop (`node.subscribe(topic, cb)`): `cb` with each batch `next()` returns, until the subscription ends; a throwing `cb` is rethrown later and the loop goes on. */
151
+ deliverTo(cb: (batch: Envelope<T>[]) => void): void;
150
152
  }
151
153
  export {};
package/dist/topics.js CHANGED
@@ -16,7 +16,7 @@ import { FLAGS, MSGPACK, SynapseError, TYPES, auParamSets, auSyncPoints, decode
16
16
  import { Handle, start as startHandle } from "./channel.js";
17
17
  import { FecReader, FecWriter, ReportWriter, feedbackListener, requireFec } from "./fec.js";
18
18
  import { RETAINED_FRAME_MAX_AGE_MS, StreamWriter, latestSubscription, moqTimestamp, streamTopicSubscription, waitActive, writeLatest } from "./session.js";
19
- import { AsyncQueue, deferred, withTimeout, TIMEOUT } from "./util.js";
19
+ import { AsyncQueue, deferred, rethrowLater, withTimeout, TIMEOUT } from "./util.js";
20
20
  /** moq's cap on one `stream` frame (a group's cache). */
21
21
  const STREAM_FRAME_MAX = 32 * 1024 * 1024;
22
22
  /** The bound on adding one publisher (its broadcast, its `desc`, its `data` subscription). */
@@ -627,6 +627,22 @@ export class TopicSubscription {
627
627
  this.#signal();
628
628
  }
629
629
  async [Symbol.asyncDispose]() { this.unsubscribe(); }
630
+ /** The callback form's read loop (`node.subscribe(topic, cb)`): `cb` with each batch `next()` returns, until the subscription ends; a throwing `cb` is rethrown later and the loop goes on. */
631
+ deliverTo(cb) {
632
+ void (async () => {
633
+ for (;;) {
634
+ const b = await this.next();
635
+ if (!b)
636
+ return;
637
+ try {
638
+ cb(b);
639
+ }
640
+ catch (e) {
641
+ rethrowLater(e);
642
+ }
643
+ }
644
+ })();
645
+ }
630
646
  }
631
647
  /** A source is done: its subscription and its request are closed (its pending read settles as the end). */
632
648
  function closeSource(src) {