@tinyactors/node 0.2.0 → 0.3.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/index.mjs ADDED
@@ -0,0 +1,6 @@
1
+ // @tinyactors/node: the direct layer (lib/direct.mjs: the addon's exports,
2
+ // nothing else) and the convenience layer above it (lib/convenience.mjs:
3
+ // JavaScript over the direct layer's exports only; AGENTS.md, "Layers and
4
+ // the resolver").
5
+ export * from './lib/direct.mjs';
6
+ export * from './lib/convenience.mjs';
@@ -0,0 +1,162 @@
1
+ // The convenience layer of @tinyactors/node and @tinyactors/wasm:
2
+ // JavaScript over the direct layer's exports only (AGENTS.md, "Layers and
3
+ // the resolver"). It adds shapes, not behaviour, and imports nothing but
4
+ // `#direct`, the package's direct exports (the lint rule
5
+ // convenience-imports-the-direct-layer): package.json's `imports` maps it
6
+ // to the addon's lib/direct.mjs, and under the export condition
7
+ // `tinyactors-wasm` to the wasm package's wasm/lib/direct.mjs
8
+ // (docs/browser.md, "One API"), so the two packages share this file.
9
+ //
10
+ // Then the shapes chosen for p3-shapes: host.addCharts, host.spawnChart,
11
+ // directoryResolver and Address.prototype.toJSON (below). The only
12
+ // built-ins it reaches are node:fs and node:path, for directoryResolver,
13
+ // through process.getBuiltinModule when the resolver is made: a runtime
14
+ // without them (a browser) refuses it there, with TA_ERROR_UNSUPPORTED.
15
+ //
16
+ // The typed methods return promises when given no handler (the
17
+ // maintainer, 2026-11-18): `host.actorState(params)` returns a promise that
18
+ // resolves with the result and rejects with the TinyactorsError, while
19
+ // `host.actorState(params, onResult, onError?)` is the direct method's call
20
+ // and returns nothing. Each direct method on Host.prototype is replaced by a
21
+ // function that passes a call with a handler straight to it (one argument
22
+ // check and one call more, measured in docs/log.xml,
23
+ // l-maint-promises-built) and otherwise calls it with a result handler that
24
+ // resolves and an error handler that rejects. The promise settles from the
25
+ // handler, in the drain; its continuation runs as a microtask after the
26
+ // turn's native call returns, outside the drain, on a result already
27
+ // converted. A refusal at the call (a closed host, a `this` that is not a
28
+ // Host, params the method cannot write) rejects too, as an async function's
29
+ // throw would. A method still pending at `close()` never settles: the
30
+ // direct layer drops its handlers uncalled. An `onError` without an
31
+ // `onResult` is the direct method's TypeError.
32
+ import { Address, compileCharts, Host, ResolveError, TinyactorsError } from '#direct';
33
+
34
+ /** The direct method `direct` as one that returns a promise of its result
35
+ * when it is given no handler. */
36
+ function promising(direct) {
37
+ return function (params, onResult, onError) {
38
+ if (onResult !== undefined || (onError !== undefined && onError !== null)) return direct.call(this, params, onResult, onError);
39
+ return new Promise((resolve, reject) => {
40
+ direct.call(this, params, (host, result) => resolve(result), (host, error) => reject(error));
41
+ });
42
+ };
43
+ }
44
+
45
+ /** The direct typed methods of Host. */
46
+ const TYPED_METHODS = [
47
+ 'actorState', 'actorContext', 'actorList', 'actorGet', 'hostStats', 'hostConfig',
48
+ 'traceConfigure', 'traceWatch', 'traceUnwatch', 'traceEnd', 'traceSpansDecode',
49
+ ];
50
+
51
+ for (const name of TYPED_METHODS) {
52
+ const direct = Host.prototype[name];
53
+ if (typeof direct !== 'function') throw new Error(`@tinyactors/node: the direct layer has no Host method ${name}`);
54
+ const method = promising(direct);
55
+ // the direct method's name and length (index.d.ts declares them)
56
+ Object.defineProperty(method, 'name', { value: name });
57
+ Object.defineProperty(method, 'length', { value: direct.length });
58
+ // as a class's methods are: writable, configurable, not enumerable
59
+ Object.defineProperty(Host.prototype, name, { value: method, writable: true, configurable: true, enumerable: false });
60
+ }
61
+
62
+ // ---- shapes a JavaScript programmer would otherwise write (p3-shapes) ----
63
+
64
+ /** Defines `value` on `target` as a class's method is: writable,
65
+ * configurable, not enumerable, its `name` the property's. */
66
+ function method(target, name, value) {
67
+ Object.defineProperty(value, 'name', { value: name });
68
+ Object.defineProperty(target, name, { value, writable: true, configurable: true, enumerable: false });
69
+ }
70
+
71
+ /** The options of addCharts: the compile call's resolver, nothing else. */
72
+ const ADD_CHARTS_OPTIONS = new Set(['resolver']);
73
+
74
+ // host.addCharts({name: text}, {resolver}?) → segment: compileCharts of the
75
+ // mapping's entries in their order (the first the boot chart), addImage of
76
+ // the image, close of the result, in one call. The result is closed on every
77
+ // path, so a refused image leaves nothing behind; a CompileError is
78
+ // compileCharts's own, with every diagnostic.
79
+ method(Host.prototype, 'addCharts', function (charts, options) {
80
+ if (typeof charts !== 'object' || charts === null || Array.isArray(charts))
81
+ throw new TypeError('addCharts: charts must be an object of document names to texts');
82
+ if (options !== undefined) {
83
+ if (typeof options !== 'object' || options === null) throw new TypeError('addCharts: options must be an object');
84
+ for (const key of Object.keys(options))
85
+ if (!ADD_CHARTS_OPTIONS.has(key)) throw new TypeError(`addCharts: unknown option ${key}`);
86
+ }
87
+ const sources = Object.entries(charts).map(([name, text]) => ({ name, text }));
88
+ const compiled = compileCharts(sources, options?.resolver);
89
+ try {
90
+ return this.addImage(compiled.image);
91
+ } finally {
92
+ compiled.close();
93
+ }
94
+ });
95
+
96
+ // host.spawnChart(name, options?) → session: spawn of the chart's current
97
+ // version, host.chart(name) then host.spawn(ref, options).
98
+ method(Host.prototype, 'spawnChart', function (name, options) {
99
+ return this.spawn(this.chart(name), options);
100
+ });
101
+
102
+ // Address.prototype.toJSON: its text, so JSON.stringify writes an address
103
+ // as the string an Address is made from (new Address(text) reads it back).
104
+ method(Address.prototype, 'toJSON', function () {
105
+ return this.text;
106
+ });
107
+
108
+ // directoryResolver(root) → resolver: a resolver for the compile calls that
109
+ // reads `source` as a file under `root`, relative to the directory of
110
+ // `base` (a document named `charts/order.scxml` asking for `child.scxml`
111
+ // reads `root/charts/child.scxml`), and refuses, with a ResolveError, a
112
+ // path that leaves `root`: `..`, an absolute path, or a symbolic link
113
+ // anywhere on the way that points outside. `root` is resolved through its
114
+ // own links once, when the resolver is made (a root that does not exist
115
+ // throws there). A file that does not exist is a ResolveError too, so the
116
+ // compile call reports it as a diagnostic; any other error of the file
117
+ // system (a directory, no permission) is thrown from the compile call as it
118
+ // is. The text must be UTF-8: bytes that are not are refused, never
119
+ // replaced.
120
+ const UTF8 = new TextDecoder('utf-8', { fatal: true });
121
+
122
+ /** node:fs and node:path, from the runtime (node, bun); a runtime without
123
+ * them refuses directoryResolver. */
124
+ function builtins() {
125
+ const get = globalThis.process?.getBuiltinModule;
126
+ if (typeof get !== 'function') {
127
+ throw new TinyactorsError('directoryResolver reads files with node:fs, which this runtime does not have', {
128
+ status: 'TA_ERROR_UNSUPPORTED',
129
+ });
130
+ }
131
+ return { fs: get.call(globalThis.process, 'node:fs'), path: get.call(globalThis.process, 'node:path') };
132
+ }
133
+
134
+ /** Whether `file`, absolute, is `root` or under it (`path`: node:path). */
135
+ function inside(path, root, file) {
136
+ const rest = path.relative(root, file);
137
+ return rest !== '' && rest !== '..' && !rest.startsWith(`..${path.sep}`) && !path.isAbsolute(rest);
138
+ }
139
+
140
+ export function directoryResolver(root) {
141
+ const { fs, path } = builtins();
142
+ const top = fs.realpathSync(root);
143
+ return function resolve(base, source) {
144
+ const file = path.resolve(top, path.dirname(base), source);
145
+ if (!inside(path, top, file)) throw new ResolveError(`${source} (from ${base}) leaves the resolver's root`);
146
+ let real;
147
+ try {
148
+ real = fs.realpathSync(file);
149
+ } catch (error) {
150
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR')
151
+ throw new ResolveError(`${source} (from ${base}): no such file under the resolver's root`);
152
+ throw error;
153
+ }
154
+ if (!inside(path, top, real)) throw new ResolveError(`${source} (from ${base}) leaves the resolver's root through a symbolic link`);
155
+ const bytes = fs.readFileSync(real);
156
+ try {
157
+ return UTF8.decode(bytes);
158
+ } catch {
159
+ throw new ResolveError(`${source} (from ${base}) is not UTF-8`);
160
+ }
161
+ };
162
+ }
package/lib/direct.mjs ADDED
@@ -0,0 +1,65 @@
1
+ // The direct layer of @tinyactors/node: loads the addon and re-exports it,
2
+ // nothing else (AGENTS.md, "Layers and the resolver"). index.mjs exports
3
+ // these names and the convenience layer's (lib/convenience.mjs), which
4
+ // imports this module only. In the repository the addon is
5
+ // build/tinyactors.node, which `mise run build` makes; an installed package
6
+ // has no build/, and its addon is this platform's package,
7
+ // @tinyactors/node-<platform>-<arch>, which an install of @tinyactors/node
8
+ // brings as an optional dependency at exactly its own version (npm, pnpm
9
+ // and Bun install only the one whose os and cpu match).
10
+ //
11
+ // The development build comes first: Bun, run where no node_modules is
12
+ // (the repository), installs a package it cannot resolve from the
13
+ // registry, so asking for the platform package there would load the last
14
+ // release's addon. The platform package's version must be this package's
15
+ // for the same reason.
16
+ import { createRequire } from 'node:module';
17
+
18
+ const require = createRequire(import.meta.url);
19
+ const platformPackage = `@tinyactors/node-${process.platform}-${process.arch}`;
20
+
21
+ function notFound(error) {
22
+ return error?.code === 'MODULE_NOT_FOUND';
23
+ }
24
+
25
+ function load() {
26
+ try {
27
+ return require('../build/tinyactors.node');
28
+ } catch (error) {
29
+ if (!notFound(error)) throw error;
30
+ }
31
+ const { version } = require('../package.json');
32
+ let installed;
33
+ try {
34
+ installed = require(`${platformPackage}/package.json`).version;
35
+ } catch (error) {
36
+ if (!notFound(error)) throw error;
37
+ throw new Error(
38
+ `@tinyactors/node: no addon for ${process.platform}-${process.arch}: ${platformPackage} is not installed ` +
39
+ '(an install of @tinyactors/node brings it where the platform has one), and this is not a build in the ' +
40
+ 'repository (mise run build); @tinyactors/wasm runs the same API on any platform, without an addon',
41
+ { cause: error },
42
+ );
43
+ }
44
+ if (installed !== version) {
45
+ throw new Error(`@tinyactors/node: ${platformPackage} is ${installed}, not ${version}: reinstall @tinyactors/node`);
46
+ }
47
+ return require(platformPackage);
48
+ }
49
+
50
+ const addon = load();
51
+
52
+ export const {
53
+ encode,
54
+ decode,
55
+ TinyactorsError,
56
+ CompileError,
57
+ ResolveError,
58
+ compileCharts,
59
+ compileSystem,
60
+ Host,
61
+ SimulatedClock,
62
+ Address,
63
+ encodeHTTPPost,
64
+ parseHTTPRequest,
65
+ } = addon;
package/package.json CHANGED
@@ -1,46 +1,54 @@
1
1
  {
2
2
  "name": "@tinyactors/node",
3
- "version": "0.2.0",
4
- "description": "xstate-style state machines and actors on the tinyactors SCXML runtime (N-API addon); hibernation, links",
3
+ "version": "0.3.0",
4
+ "description": "SCXML statecharts as actors on the tinyactors host, from Node.js and Bun (a Node-API addon)",
5
5
  "keywords": [
6
6
  "actor",
7
7
  "actors",
8
8
  "statechart",
9
9
  "scxml",
10
10
  "state-machine",
11
- "xstate",
12
11
  "napi",
13
12
  "bun"
14
13
  ],
15
- "homepage": "https://github.com/dhamidi/tinyactors/tree/main/tinyactors-core/bindings/node#readme",
14
+ "homepage": "https://github.com/tinyactors-dev/tinyactors-napi#readme",
16
15
  "repository": {
17
16
  "type": "git",
18
- "url": "git+https://github.com/dhamidi/tinyactors.git",
19
- "directory": "tinyactors-core/bindings/node"
17
+ "url": "git+https://github.com/tinyactors-dev/tinyactors.git",
18
+ "directory": "tinyactors-napi"
20
19
  },
21
20
  "bugs": {
22
- "url": "https://github.com/dhamidi/tinyactors/issues"
21
+ "url": "https://github.com/tinyactors-dev/tinyactors/issues"
23
22
  },
24
23
  "license": "MIT",
25
- "main": "node/index.js",
26
- "types": "node/index.d.ts",
27
24
  "engines": {
28
- "node": ">=22.12"
25
+ "node": ">=22.3.0"
26
+ },
27
+ "type": "module",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./index.d.ts",
31
+ "default": "./index.mjs"
32
+ }
29
33
  },
30
34
  "files": [
31
- "node/index.js",
32
- "node/index.d.ts",
33
- "node/transports.js",
34
- "node/ws.js",
35
- "shared/core.mjs",
36
- "shared/ecmascript.mjs",
35
+ "index.mjs",
36
+ "lib",
37
+ "index.d.ts",
37
38
  "README.md",
38
- "LICENSE"
39
+ "LICENSE",
40
+ "docs/guide",
41
+ "docs/values.md"
39
42
  ],
43
+ "imports": {
44
+ "#direct": {
45
+ "default": "./lib/direct.mjs"
46
+ }
47
+ },
40
48
  "optionalDependencies": {
41
- "@tinyactors/node-darwin-arm64": "0.2.0",
42
- "@tinyactors/node-darwin-x64": "0.2.0",
43
- "@tinyactors/node-linux-x64": "0.2.0",
44
- "@tinyactors/node-linux-arm64": "0.2.0"
49
+ "@tinyactors/node-darwin-arm64": "0.3.0",
50
+ "@tinyactors/node-darwin-x64": "0.3.0",
51
+ "@tinyactors/node-linux-x64": "0.3.0",
52
+ "@tinyactors/node-linux-arm64": "0.3.0"
45
53
  }
46
54
  }