@kylewillett/troupe 0.1.1 → 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.
Files changed (81) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/README.md +129 -3
  3. package/dist/ask.d.ts +5 -1
  4. package/dist/ask.js +16 -0
  5. package/dist/backstage/index.d.ts +2 -1
  6. package/dist/backstage/index.js +1 -0
  7. package/dist/backstage/source.d.ts +1 -1
  8. package/dist/backstage/source.js +65 -2
  9. package/dist/backstage/types.d.ts +65 -4
  10. package/dist/backstage/types.js +2 -1
  11. package/dist/backstage-ui/assets/index-CG896RLZ.css +1 -0
  12. package/dist/backstage-ui/assets/index-DF_Xnc1u.js +9 -0
  13. package/dist/backstage-ui/index.html +2 -2
  14. package/dist/cell.d.ts +16 -14
  15. package/dist/cell.js +38 -13
  16. package/dist/checks.d.ts +10 -0
  17. package/dist/checks.js +34 -2
  18. package/dist/cluster/index.d.ts +6 -0
  19. package/dist/cluster/index.js +4 -0
  20. package/dist/cluster/leases.d.ts +37 -0
  21. package/dist/cluster/leases.js +132 -0
  22. package/dist/cluster/membership.d.ts +100 -0
  23. package/dist/cluster/membership.js +559 -0
  24. package/dist/cluster/memory.d.ts +31 -0
  25. package/dist/cluster/memory.js +187 -0
  26. package/dist/cluster/placement.d.ts +10 -0
  27. package/dist/cluster/placement.js +30 -0
  28. package/dist/cluster/postgres/index.d.ts +1 -0
  29. package/dist/cluster/postgres/index.js +3 -0
  30. package/dist/cluster/postgres/schema.d.ts +7 -0
  31. package/dist/cluster/postgres/schema.js +33 -0
  32. package/dist/cluster/postgres/schema.sql +18 -0
  33. package/dist/cluster/postgres/store.d.ts +28 -0
  34. package/dist/cluster/postgres/store.js +124 -0
  35. package/dist/cluster/region.d.ts +103 -0
  36. package/dist/cluster/region.js +843 -0
  37. package/dist/cluster/remoting.d.ts +79 -0
  38. package/dist/cluster/remoting.js +755 -0
  39. package/dist/cluster/shard-memory.d.ts +14 -0
  40. package/dist/cluster/shard-memory.js +92 -0
  41. package/dist/cluster/shard-store.d.ts +62 -0
  42. package/dist/cluster/shard-store.js +36 -0
  43. package/dist/cluster/shard.d.ts +54 -0
  44. package/dist/cluster/shard.js +278 -0
  45. package/dist/cluster/sharding.d.ts +109 -0
  46. package/dist/cluster/sharding.js +278 -0
  47. package/dist/cluster/table.d.ts +29 -0
  48. package/dist/cluster/table.js +74 -0
  49. package/dist/cluster/transport.d.ts +29 -0
  50. package/dist/cluster/transport.js +4 -0
  51. package/dist/cluster/wire.d.ts +90 -0
  52. package/dist/cluster/wire.js +177 -0
  53. package/dist/hash.d.ts +7 -0
  54. package/dist/hash.js +25 -0
  55. package/dist/internal.d.ts +134 -2
  56. package/dist/internal.js +12 -1
  57. package/dist/json.d.ts +44 -0
  58. package/dist/json.js +143 -0
  59. package/dist/node/cluster/frames.d.ts +31 -0
  60. package/dist/node/cluster/frames.js +73 -0
  61. package/dist/node/cluster/index.d.ts +1 -0
  62. package/dist/node/cluster/index.js +3 -0
  63. package/dist/node/cluster/tcp.d.ts +101 -0
  64. package/dist/node/cluster/tcp.js +416 -0
  65. package/dist/persistence/actor.js +1 -1
  66. package/dist/persistence/backend.d.ts +1 -10
  67. package/dist/persistence/backend.js +4 -34
  68. package/dist/persistence/postgres/index.d.ts +2 -1
  69. package/dist/persistence/postgres/index.js +1 -1
  70. package/dist/persistence/postgres/pool.d.ts +44 -0
  71. package/dist/persistence/postgres/pool.js +65 -0
  72. package/dist/persistence/postgres/postgres.d.ts +1 -33
  73. package/dist/persistence/postgres/postgres.js +4 -63
  74. package/dist/system.d.ts +1 -1
  75. package/dist/system.js +190 -24
  76. package/dist/types.d.ts +86 -3
  77. package/package.json +21 -2
  78. package/dist/backstage-ui/assets/index-Bg0MCiqs.css +0 -1
  79. package/dist/backstage-ui/assets/index-CeefBsDh.js +0 -9
  80. package/dist/persistence/json.d.ts +0 -7
  81. package/dist/persistence/json.js +0 -75
@@ -0,0 +1,177 @@
1
+ // The wire format (decision 0025). A message that leaves a node is JSON text, and every ref in it
2
+ // becomes a URI naming the cluster, the node's address and uid, and the actor's path. Decoding
3
+ // turns each URI back into a ref: a live local actor, a ref whose tells are dead letters, or a
4
+ // remote ref from remoting. Nothing here throws: a message that can't be sent, or text a peer
5
+ // sent that can't be read, is a problem with the path to its first bad part.
6
+ import { checkInt, describe } from '../checks.js';
7
+ import { defineKey, jsonCopy, keyPath } from '../json.js';
8
+ import { isValidName } from '../names.js';
9
+ const SCHEME = 'troupe://';
10
+ export const CLUSTER_NAME = /^[a-z0-9-]+$/;
11
+ // What a transport address may hold: anything but the URI's separators and whitespace.
12
+ export const ADDRESS = /^[^@#/\s]+$/;
13
+ // Path segments are actor names or generated names (src/names.ts), so URIs need no escaping.
14
+ const REF_URI = /^troupe:\/\/([a-z0-9-]+)@([^@#/\s]+)#(0|[1-9][0-9]{0,15})((?:\/[A-Za-z0-9._~$-]+)+)$/;
15
+ /**
16
+ * Makes the codec for one node.
17
+ * @throws TypeError if `self` has a bad cluster name, address or uid.
18
+ */
19
+ export function createCodec(opts) {
20
+ const { self, hooks, remote, entities = () => undefined } = opts;
21
+ checkNodeId(self);
22
+ const prefix = `${SCHEME}${self.cluster}@${self.address}#${String(self.uid)}`;
23
+ const uri = (path) => (path.startsWith(SCHEME) ? path : `${prefix}${path}`);
24
+ const refHook = (value, at) => {
25
+ if (!isRefShaped(value))
26
+ return undefined;
27
+ const entity = entities()?.identify(value);
28
+ if (entity !== undefined)
29
+ return { value: { $entity: { type: entity.type, id: entity.id } } };
30
+ if (!hooks.owns(value))
31
+ return { problem: `${at} is a ref from another actor system` };
32
+ return { value: { $ref: uri(value.path) } };
33
+ };
34
+ const copyHooks = { ref: refHook, key: escapeKey };
35
+ const deadRef = (path) => hooks.makeRef(path, (message) => {
36
+ hooks.deadLetter(path, message, 'stopped');
37
+ });
38
+ const resolve = (text, at) => {
39
+ const address = parseRefUri(text);
40
+ if (address === undefined)
41
+ return `${at} is not a ref URI`;
42
+ if (address.cluster !== self.cluster) {
43
+ return `${at} is a ref in cluster "${address.cluster}", not "${self.cluster}"`;
44
+ }
45
+ if (address.address !== self.address)
46
+ return remote(text, address);
47
+ // An old incarnation of this node: its actors are gone, whatever their paths.
48
+ if (address.uid !== self.uid)
49
+ return deadRef(text);
50
+ return hooks.lookup(address.path) ?? deadRef(address.path);
51
+ };
52
+ const resolveEntity = (name, at) => {
53
+ const { type, id } = (typeof name === 'object' && name !== null ? name : {});
54
+ if (typeof name !== 'object' ||
55
+ name === null ||
56
+ Array.isArray(name) ||
57
+ Object.keys(name).length !== 2 ||
58
+ !isValidName(type) ||
59
+ !isValidName(id)) {
60
+ return `${at} is not an entity's type and id`;
61
+ }
62
+ const refs = entities();
63
+ if (refs === undefined)
64
+ return `${at} is an entity ref, and this node has no sharding`;
65
+ return refs.ref({ type, id });
66
+ };
67
+ const decodeValue = (parsed) => {
68
+ try {
69
+ return { ok: true, value: unescape(parsed, '$', resolve, resolveEntity) };
70
+ }
71
+ catch (error) {
72
+ if (error instanceof DecodeProblem)
73
+ return { ok: false, problem: error.text };
74
+ return { ok: false, problem: `$ can't be decoded: ${errorText(error)}` };
75
+ }
76
+ };
77
+ return {
78
+ encode(message) {
79
+ try {
80
+ const copied = jsonCopy(message, copyHooks);
81
+ return copied.ok ? { ok: true, text: JSON.stringify(copied.value) } : copied;
82
+ }
83
+ catch (error) {
84
+ // A throwing getter, a revoked proxy, or nesting deeper than the stack.
85
+ return { ok: false, problem: `$ can't be read: ${errorText(error)}` };
86
+ }
87
+ },
88
+ decode(text) {
89
+ let parsed;
90
+ try {
91
+ parsed = JSON.parse(text);
92
+ }
93
+ catch (error) {
94
+ return { ok: false, problem: `$ is not JSON: ${errorText(error)}` };
95
+ }
96
+ return decodeValue(parsed);
97
+ },
98
+ decodeValue,
99
+ uri,
100
+ };
101
+ }
102
+ /** Parses a ref URI, or gives `undefined` if `text` isn't one. */
103
+ export function parseRefUri(text) {
104
+ const match = REF_URI.exec(text);
105
+ if (match === null)
106
+ return undefined;
107
+ const [, cluster, address, uid, path] = match;
108
+ const n = Number(uid);
109
+ if (!Number.isSafeInteger(n))
110
+ return undefined;
111
+ return { cluster, address, uid: n, path };
112
+ }
113
+ /** Throws `TypeError` unless `id` is a usable node identity. */
114
+ export function checkNodeId(id) {
115
+ if (typeof id.cluster !== 'string' || !CLUSTER_NAME.test(id.cluster)) {
116
+ throw new TypeError(`cluster name must be lower-case letters, digits and "-", got ${describe(id.cluster)}`);
117
+ }
118
+ if (typeof id.address !== 'string' || !ADDRESS.test(id.address)) {
119
+ throw new TypeError(`address must be non-empty, without "@", "#", "/" or spaces, got ${describe(id.address)}`);
120
+ }
121
+ checkInt(id.uid, 'uid', { min: 0 });
122
+ }
123
+ /** Whether `value` has a ref's shape, as Backstage's encoding recognises refs (decision 0021). */
124
+ function isRefShaped(value) {
125
+ const { path, tell, ask } = value;
126
+ return typeof path === 'string' && typeof tell === 'function' && typeof ask === 'function';
127
+ }
128
+ function escapeKey(key) {
129
+ return key.startsWith('$') ? `$${key}` : key;
130
+ }
131
+ class DecodeProblem extends Error {
132
+ text;
133
+ constructor(text) {
134
+ super(text);
135
+ this.text = text;
136
+ }
137
+ }
138
+ /**
139
+ * The decoded message: `$$` keys lose their first `$`, `{ "$ref": uri }` becomes a ref, and
140
+ * `{ "$entity": { type, id } }` an entity ref. Any other key starting with a single `$` is a
141
+ * marker this version doesn't know.
142
+ */
143
+ function unescape(value, at, resolve, resolveEntity) {
144
+ if (typeof value !== 'object' || value === null)
145
+ return value;
146
+ if (Array.isArray(value)) {
147
+ const items = value;
148
+ return items.map((item, i) => unescape(item, `${at}[${String(i)}]`, resolve, resolveEntity));
149
+ }
150
+ const record = value;
151
+ const keys = Object.keys(record);
152
+ const marker = keys.find((key) => key.startsWith('$') && !key.startsWith('$$'));
153
+ if (marker !== undefined) {
154
+ let ref;
155
+ if (marker === '$ref' && keys.length === 1 && typeof record.$ref === 'string') {
156
+ ref = resolve(record.$ref, at);
157
+ }
158
+ else if (marker === '$entity' && keys.length === 1) {
159
+ ref = resolveEntity(record.$entity, at);
160
+ }
161
+ else {
162
+ throw new DecodeProblem(`${at} has an unknown marker "${marker}"`);
163
+ }
164
+ if (typeof ref === 'string')
165
+ throw new DecodeProblem(ref);
166
+ return ref;
167
+ }
168
+ const out = {};
169
+ for (const key of keys) {
170
+ const name = key.startsWith('$') ? key.slice(1) : key;
171
+ defineKey(out, name, unescape(record[key], `${at}${keyPath(name)}`, resolve, resolveEntity));
172
+ }
173
+ return out;
174
+ }
175
+ function errorText(error) {
176
+ return error instanceof Error ? error.message : String(error);
177
+ }
package/dist/hash.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /** A 32-bit FNV-1a hash of `text`, as an unsigned integer. */
2
+ export declare function fnv1a(text: string): number;
3
+ /**
4
+ * MurmurHash3's finalizer: every input bit affects every output bit. FNV-1a alone changes little
5
+ * in its high bits when only a string's end differs, so rendezvous scores mix it with this.
6
+ */
7
+ export declare function mix32(hash: number): number;
package/dist/hash.js ADDED
@@ -0,0 +1,25 @@
1
+ // The one string hash in the package: 32-bit FNV-1a, over UTF-16 code units. Postgres's lock keys
2
+ // use it (decision 0016), and so does sharding, to place entity ids in shards (decision 0030).
3
+ // Computed here rather than by any runtime or database, so every process agrees on it.
4
+ /** A 32-bit FNV-1a hash of `text`, as an unsigned integer. */
5
+ export function fnv1a(text) {
6
+ let hash = 0x811c9dc5;
7
+ for (let i = 0; i < text.length; i++) {
8
+ hash ^= text.charCodeAt(i);
9
+ hash = Math.imul(hash, 0x01000193);
10
+ }
11
+ return hash >>> 0;
12
+ }
13
+ /**
14
+ * MurmurHash3's finalizer: every input bit affects every output bit. FNV-1a alone changes little
15
+ * in its high bits when only a string's end differs, so rendezvous scores mix it with this.
16
+ */
17
+ export function mix32(hash) {
18
+ let h = hash >>> 0;
19
+ h ^= h >>> 16;
20
+ h = Math.imul(h, 0x85ebca6b);
21
+ h ^= h >>> 13;
22
+ h = Math.imul(h, 0xc2b2ae35);
23
+ h ^= h >>> 16;
24
+ return h >>> 0;
25
+ }
@@ -2,7 +2,7 @@ import type { EventBody } from './events.js';
2
2
  import type { Logger } from './logger.js';
3
3
  import type { Persistence } from './persistence/types.js';
4
4
  import type { Scheduler } from './scheduler.js';
5
- import type { ActorContext, ActorSystem } from './types.js';
5
+ import type { ActorContext, ActorDef, ActorRef, ActorSystem, AnyRef, DeadLetterReason, SpawnOptions } from './types.js';
6
6
  /**
7
7
  * An optional async step on an `ActorDef`, run after `initial` and before any message. It gets the
8
8
  * state `initial` made and returns the state to start with. The cell holds its mailbox until it
@@ -60,8 +60,47 @@ export interface SystemInspection {
60
60
  readonly scheduler: Scheduler;
61
61
  /** The system's logger, wrapped so it never throws. For an inspector's own failures. */
62
62
  readonly log: Logger;
63
- /** Every live actor under `/user`, depth first, each parent before its children in spawn order. */
63
+ /**
64
+ * Every live actor under `/user`, then every one under `/system/sharding` (the cluster's
65
+ * regions, shards and entities), depth first, each parent before its children in spawn order.
66
+ */
64
67
  walk(): CellInspection[];
68
+ /** This node's place in a cluster, once it has joined one. */
69
+ cluster(): ClusterInspection | undefined;
70
+ /**
71
+ * Calls `listener` whenever this node's view of its cluster may have changed: a member, its
72
+ * reachability, or a shard owner this node knows of. It must not throw.
73
+ * @returns A function that stops the calls.
74
+ */
75
+ onClusterChange(listener: () => void): () => void;
76
+ }
77
+ /** One member of a cluster, as the node an inspector is attached to sees it. */
78
+ export interface MemberInspection {
79
+ readonly address: string;
80
+ readonly uid: number;
81
+ readonly status: 'up' | 'leaving' | 'down';
82
+ readonly reachable: boolean;
83
+ }
84
+ /** One entity type on a node, and the shard owners that node knows of. */
85
+ export interface EntityTypeInspection {
86
+ readonly type: string;
87
+ readonly shardCount: number;
88
+ /** Whether this node hosts the type's shards, or only routes to them. */
89
+ readonly host: boolean;
90
+ /**
91
+ * The holder of each shard this node knows of, `<address>#<uid>`, in shard order: its own
92
+ * shards, and the holders its region last learned for the others (decision 0030).
93
+ */
94
+ readonly owners: readonly (readonly [shard: number, holder: string])[];
95
+ }
96
+ /** What the cluster shows an inspector of the node it runs on. Read-only. */
97
+ export interface ClusterInspection {
98
+ readonly address: string;
99
+ readonly uid: number;
100
+ /** The members as this node sees them, itself included, sorted by address. */
101
+ members(): readonly MemberInspection[];
102
+ /** The entity types this node has registered, in the order it registered them. */
103
+ entityTypes(): readonly EntityTypeInspection[];
65
104
  }
66
105
  /** What a persistent actor's definition offers an inspector, without touching a live actor. */
67
106
  export interface PersistentHook {
@@ -79,3 +118,96 @@ export interface PersistentHook {
79
118
  export declare function inspectSystem(system: ActorSystem): SystemInspection;
80
119
  /** The persistent hook of a definition, if it's a persistent actor's. */
81
120
  export declare function persistentHookOf(def: object): PersistentHook | undefined;
121
+ /** Something told when a watched actor terminates: a cell, a testkit probe, or remoting. */
122
+ export interface Watcher {
123
+ /** Tells the watcher that `target` has terminated. It must not throw. */
124
+ notifyTerminated(target: WatchTarget): void;
125
+ }
126
+ /**
127
+ * Something `ctx.watch` can watch: a local actor's cell, or an actor on another node, which
128
+ * remoting stands in for (decision 0026).
129
+ */
130
+ export interface WatchTarget {
131
+ /** The watched actor's ref, as the `terminated` signal carries it. */
132
+ readonly ref: AnyRef;
133
+ readonly terminated: boolean;
134
+ /** Present once it has terminated, when it stopped because it failed. */
135
+ readonly failure: {
136
+ readonly error: unknown;
137
+ } | undefined;
138
+ /** Starts telling `watcher` when it terminates. Adding one twice is the same as once. */
139
+ addWatcher(watcher: Watcher): void;
140
+ removeWatcher(watcher: Watcher): void;
141
+ }
142
+ /** The cluster's hook on a system the core made (decision 0025). */
143
+ export declare const HOOKS: unique symbol;
144
+ /** What `system[HOOKS]` holds. */
145
+ export interface SystemHooks {
146
+ /** The scheduler the system runs on. */
147
+ readonly scheduler: Scheduler;
148
+ /** The system's source of chance (decision 0003). */
149
+ readonly random: () => number;
150
+ /** The system's logger, wrapped so it never throws. */
151
+ readonly log: Logger;
152
+ /**
153
+ * Spawns an actor under `/system`, with every check `spawn` makes: a top-level one, or with
154
+ * `parent`, a child of an actor already under `/system`, as sharding's regions are (decision
155
+ * 0030). `terminate()` stops these after everything under `/user`, so user actors can still
156
+ * reach the cluster as they stop.
157
+ * @throws TypeError if `parent` isn't a live actor under `/system`.
158
+ */
159
+ spawnSystem<M, S>(def: ActorDef<M, S>, name?: string, opts?: SpawnOptions, parent?: AnyRef): ActorRef<M>;
160
+ /**
161
+ * The ref at a local path: a live actor under `/user` or `/system`, or the temporary ref of an
162
+ * ask that's still waiting, under `/temp`. `undefined` for anything else.
163
+ */
164
+ lookup(path: string): AnyRef | undefined;
165
+ /** Whether this system made `ref`, through spawn, ask, a probe or {@link SystemHooks.makeRef}. */
166
+ owns(ref: unknown): boolean;
167
+ /** Makes a ref with this system's `ask`, such as a remote ref. */
168
+ makeRef<M>(path: string, tell: (msg: M) => void): ActorRef<M>;
169
+ /** Publishes a system event, stamped by the system's bus: the cluster's member events. */
170
+ publish(body: EventBody): void;
171
+ /** Publishes a `deadLetter` event. */
172
+ deadLetter(recipient: string, message: unknown, reason: DeadLetterReason): void;
173
+ /**
174
+ * What `ctx.watch` would watch for `ref`: a local actor's cell, or what the watch resolver
175
+ * gives. `undefined` for a ref nothing can watch, such as a temporary ask ref.
176
+ */
177
+ watchTarget(ref: unknown): WatchTarget | undefined;
178
+ /**
179
+ * Installs what `ctx.watch` and probes use for refs that aren't local actors: remoting's
180
+ * remote refs (decision 0026). One per system.
181
+ * @throws Error if one is already installed.
182
+ */
183
+ setWatchResolver(resolve: (ref: unknown) => WatchTarget | undefined): void;
184
+ /**
185
+ * The path of the actor sending right now, as `delivered.from` would name it, when it's known
186
+ * (decision 0020). Only known while a subscriber wants message events.
187
+ */
188
+ sender(): string | undefined;
189
+ /**
190
+ * Stops a local actor once it has handled every message already in its mailbox, as if a stop
191
+ * were its last message. What's sent after this is a `stopped` dead letter, so the caller holds
192
+ * it: sharding's passivation and handoff (decision 0030).
193
+ * @throws TypeError if `ref` isn't a local actor of this system.
194
+ */
195
+ stopWhenIdle(ref: AnyRef): void;
196
+ /**
197
+ * Runs `task` once `terminate()` has stopped every actor under `/user`, and stops the actors
198
+ * under `/system` only after every such task has settled. Until then they still spawn and take
199
+ * messages, so the cluster can hand its shards off as the node terminates (decision 0030).
200
+ * @throws Error once termination has got that far.
201
+ */
202
+ onTerminate(task: () => Promise<void>): void;
203
+ /** Tells `ref` with `from` as the sender, for a message from another node (decision 0026). */
204
+ tellFrom(ref: AnyRef, message: unknown, from: string | undefined): void;
205
+ /**
206
+ * Shows `view` to inspectors of this system, such as Backstage. One per system.
207
+ * @returns A function the cluster calls whenever the view may have changed.
208
+ * @throws Error if a view is already set.
209
+ */
210
+ setCluster(view: ClusterInspection): () => void;
211
+ }
212
+ /** The cluster's hook on a system the core made. */
213
+ export declare function hooksOf(system: ActorSystem): SystemHooks;
package/dist/internal.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // Hooks between the core and the package's other entry points. None of this is public API: the
2
2
  // symbols are exported only to the package's own modules, never from an entry point, so user
3
3
  // actors can't reach them. Persistent actors use them to recover before any message (milestone 2),
4
- // and Backstage uses them to read what the public API doesn't show (milestone 3).
4
+ // Backstage uses them to read what the public API doesn't show (milestone 3), and the cluster uses
5
+ // them to put its actors under /system and to turn paths from the wire back into refs (milestone
6
+ // 4). The core still knows nothing about the network.
5
7
  /**
6
8
  * An optional async step on an `ActorDef`, run after `initial` and before any message. It gets the
7
9
  * state `initial` made and returns the state to start with. The cell holds its mailbox until it
@@ -34,3 +36,12 @@ export function inspectSystem(system) {
34
36
  export function persistentHookOf(def) {
35
37
  return def[PERSISTENT];
36
38
  }
39
+ /** The cluster's hook on a system the core made (decision 0025). */
40
+ export const HOOKS = Symbol('troupe.hooks');
41
+ /** The cluster's hook on a system the core made. */
42
+ export function hooksOf(system) {
43
+ const hooks = system[HOOKS];
44
+ if (hooks === undefined)
45
+ throw new TypeError('this system was not made by createActorSystem');
46
+ return hooks;
47
+ }
package/dist/json.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ /** A JSON value: what `JSON.parse` could have produced. */
2
+ export type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
3
+ readonly [key: string]: JsonValue;
4
+ };
5
+ /** What a {@link JsonHooks.ref} hook says about an object that is a ref. */
6
+ export type RefVerdict = {
7
+ readonly value: JsonValue;
8
+ } | {
9
+ readonly problem: string;
10
+ };
11
+ /** How {@link jsonCopy} treats refs and keys. */
12
+ export interface JsonHooks {
13
+ /**
14
+ * Called for every object before it's checked as a plain object. `undefined` if it isn't a ref;
15
+ * otherwise the JSON value it becomes, or why it can't be used (said of `path`, as `$.to`).
16
+ */
17
+ readonly ref?: (value: object, path: string) => RefVerdict | undefined;
18
+ /** Renames every object key in the copy, such as the wire's `$` escaping. */
19
+ readonly key?: (key: string) => string;
20
+ }
21
+ /**
22
+ * Where `value` stops being a JSON value, as a path such as `$.items[2]` with the reason, or
23
+ * `undefined` if it is one.
24
+ */
25
+ export declare function jsonProblem(value: unknown): string | undefined;
26
+ /** Whether `value` is a JSON value: what `JSON.parse` could have produced. */
27
+ export declare function isJsonValue(value: unknown): boolean;
28
+ /**
29
+ * Copies `value` as a JSON value in one walk, turning refs into what `hooks.ref` says and renaming
30
+ * keys with `hooks.key`, or names where it stops being one, as {@link jsonProblem} does.
31
+ *
32
+ * A getter that throws, or a revoked proxy, propagates its error.
33
+ */
34
+ export declare function jsonCopy(value: unknown, hooks: JsonHooks): {
35
+ readonly ok: true;
36
+ readonly value: JsonValue;
37
+ } | {
38
+ readonly ok: false;
39
+ readonly problem: string;
40
+ };
41
+ /** Sets an own property, so a `__proto__` key is data, as `JSON.parse` makes it. */
42
+ export declare function defineKey(out: Record<string, unknown>, key: string, value: unknown): void;
43
+ /** How a key reads in a problem's path: `.name`, or `["a key"]` when it isn't an identifier. */
44
+ export declare function keyPath(key: string): string;
package/dist/json.js ADDED
@@ -0,0 +1,143 @@
1
+ // What a JSON value is, once for the whole package. Events and snapshot states must be JSON values
2
+ // (decision 0014): what every backend can store and give back deep-equal. Messages that cross a
3
+ // node are JSON values plus refs (decision 0025), checked by the same walk with a ref hook. The
4
+ // checks run before anything is written or sent, so a value that JSON would quietly change, such
5
+ // as `undefined` or a `Date`, fails where it's produced instead of on recovery or on another node.
6
+ /**
7
+ * Where `value` stops being a JSON value, as a path such as `$.items[2]` with the reason, or
8
+ * `undefined` if it is one.
9
+ */
10
+ export function jsonProblem(value) {
11
+ try {
12
+ new Walk(undefined, false).at(value, '$');
13
+ return undefined;
14
+ }
15
+ catch (error) {
16
+ if (error instanceof Problem)
17
+ return error.text;
18
+ throw error;
19
+ }
20
+ }
21
+ /** Whether `value` is a JSON value: what `JSON.parse` could have produced. */
22
+ export function isJsonValue(value) {
23
+ return jsonProblem(value) === undefined;
24
+ }
25
+ /**
26
+ * Copies `value` as a JSON value in one walk, turning refs into what `hooks.ref` says and renaming
27
+ * keys with `hooks.key`, or names where it stops being one, as {@link jsonProblem} does.
28
+ *
29
+ * A getter that throws, or a revoked proxy, propagates its error.
30
+ */
31
+ export function jsonCopy(value, hooks) {
32
+ try {
33
+ return { ok: true, value: new Walk(hooks, true).at(value, '$') };
34
+ }
35
+ catch (error) {
36
+ if (error instanceof Problem)
37
+ return { ok: false, problem: error.text };
38
+ throw error;
39
+ }
40
+ }
41
+ /** Sets an own property, so a `__proto__` key is data, as `JSON.parse` makes it. */
42
+ export function defineKey(out, key, value) {
43
+ Object.defineProperty(out, key, { value, enumerable: true, writable: true, configurable: true });
44
+ }
45
+ // Thrown inside a walk and caught at its top, so the common case, a valid value, checks nothing
46
+ // on the way back up.
47
+ class Problem extends Error {
48
+ text;
49
+ constructor(text) {
50
+ super(text);
51
+ this.text = text;
52
+ }
53
+ }
54
+ /**
55
+ * One walk of a value. Without `copy` it only checks, and returns `null` from every step, so
56
+ * checking an event allocates nothing but the set of ancestors.
57
+ */
58
+ class Walk {
59
+ hooks;
60
+ copy;
61
+ #ancestors = new Set();
62
+ constructor(hooks, copy) {
63
+ this.hooks = hooks;
64
+ this.copy = copy;
65
+ }
66
+ at(value, path) {
67
+ switch (typeof value) {
68
+ case 'string':
69
+ case 'boolean':
70
+ return value;
71
+ case 'number':
72
+ // -0 passes, as JSON.parse('-0') gives it, though it comes back as 0.
73
+ if (Number.isFinite(value))
74
+ return value;
75
+ throw new Problem(`${path} is ${String(value)}`);
76
+ case 'object':
77
+ if (value === null)
78
+ return null;
79
+ return this.#object(value, path);
80
+ case 'undefined':
81
+ throw new Problem(`${path} is undefined`);
82
+ default:
83
+ throw new Problem(`${path} is a ${typeof value}`);
84
+ }
85
+ }
86
+ #object(value, path) {
87
+ const verdict = this.hooks?.ref?.(value, path);
88
+ if (verdict !== undefined) {
89
+ if ('problem' in verdict)
90
+ throw new Problem(verdict.problem);
91
+ return verdict.value;
92
+ }
93
+ const ancestors = this.#ancestors;
94
+ if (ancestors.has(value))
95
+ throw new Problem(`${path} is a cycle`);
96
+ if (Object.getOwnPropertySymbols(value).length > 0) {
97
+ throw new Problem(`${path} has symbol keys`);
98
+ }
99
+ ancestors.add(value);
100
+ try {
101
+ if (Array.isArray(value))
102
+ return this.#array(value, path);
103
+ const proto = Object.getPrototypeOf(value);
104
+ if (proto !== Object.prototype && proto !== null) {
105
+ throw new Problem(`${path} is not a plain object (${constructorName(value)})`);
106
+ }
107
+ return this.#plain(value, path);
108
+ }
109
+ finally {
110
+ ancestors.delete(value);
111
+ }
112
+ }
113
+ #array(value, path) {
114
+ const out = this.copy ? [] : undefined;
115
+ for (let i = 0; i < value.length; i++) {
116
+ // A hole would come back as null.
117
+ if (!(i in value))
118
+ throw new Problem(`${path}[${String(i)}] is a hole`);
119
+ const item = this.at(value[i], `${path}[${String(i)}]`);
120
+ out?.push(item);
121
+ }
122
+ return out ?? null;
123
+ }
124
+ #plain(value, path) {
125
+ const out = this.copy ? {} : undefined;
126
+ const rename = this.hooks?.key;
127
+ for (const [key, item] of Object.entries(value)) {
128
+ const copied = this.at(item, `${path}${keyPath(key)}`);
129
+ if (out !== undefined)
130
+ defineKey(out, rename === undefined ? key : rename(key), copied);
131
+ }
132
+ return out ?? null;
133
+ }
134
+ }
135
+ function constructorName(value) {
136
+ const ctor = value.constructor;
137
+ return typeof ctor === 'function' && ctor.name !== '' ? ctor.name : 'an anonymous class';
138
+ }
139
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
140
+ /** How a key reads in a problem's path: `.name`, or `["a key"]` when it isn't an identifier. */
141
+ export function keyPath(key) {
142
+ return IDENTIFIER.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
143
+ }
@@ -0,0 +1,31 @@
1
+ /** Encodes one frame: its UTF-8 bytes, after their length. */
2
+ export declare function encodeFrame(text: string): Buffer;
3
+ /** The next thing in the stream: a whole frame, or the length of one over the limit. */
4
+ export type Next = {
5
+ readonly frame: string;
6
+ readonly tooLong?: undefined;
7
+ } | {
8
+ readonly frame?: undefined;
9
+ readonly tooLong: number;
10
+ };
11
+ /**
12
+ * Turns chunks of a stream into frames, one at a time, so the limit can change between frames.
13
+ * That's how the transport keeps a peer to small frames until it has proven the secret, even when
14
+ * its proof and its first big frame arrive in one chunk.
15
+ */
16
+ export declare class FrameDecoder {
17
+ #private;
18
+ /** The largest frame accepted, in bytes. */
19
+ limit: number;
20
+ constructor(limit: number);
21
+ /** Adds a chunk of the stream. */
22
+ push(chunk: Buffer): void;
23
+ /**
24
+ * The next whole frame, or undefined until there is one. A frame whose length is over the
25
+ * limit is reported as soon as its header arrives, before its body is buffered, and decoding
26
+ * should stop there.
27
+ */
28
+ next(): Next | undefined;
29
+ /** Whether part of a frame is waiting for the rest. */
30
+ get partial(): boolean;
31
+ }