@frondruntime/devtools 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/src/full.ts ADDED
@@ -0,0 +1,232 @@
1
+ import { describeError } from "./cause.ts";
2
+ import { type ShapeDescriptor, UNREADABLE } from "./descriptors.ts";
3
+
4
+ /**
5
+ * Bounds for `"full"`. Termination guards, not a byte budget.
6
+ *
7
+ * This encoder runs against a loopback socket, so bytes are close to free; what
8
+ * these stop is a cycle the `seen` set cannot catch, a proxy that manufactures
9
+ * keys on demand, or a linked list a few hundred thousand long — cases where the
10
+ * walk would hang the observed app inside its own devtools. Set them where a
11
+ * pathological structure trips them and a large-but-real one does not, and every
12
+ * one of them announces itself in the output. A cap an agent cannot see is worse
13
+ * than a low cap: it turns "there was more" into "that was all", which is the
14
+ * one thing this feed must never say.
15
+ */
16
+ const FULL_MAX_DEPTH = 24;
17
+ const FULL_MAX_STRING_LENGTH = 65536;
18
+ const FULL_MAX_ENTRIES = 4096;
19
+ /**
20
+ * Total encoded values per record, across the whole tree.
21
+ *
22
+ * Counts values, not characters: one 64k string spends the same allowance as
23
+ * `true`. So this bounds how long the walk runs, and only loosely bounds what it
24
+ * produces — which is the right trade here, where the walk is the expensive half
25
+ * and the wire is a socket to the same machine.
26
+ */
27
+ export const FULL_MAX_NODES = 50000;
28
+
29
+ export type Budget = { remaining: number };
30
+
31
+ /**
32
+ * Reduces a value to JSON-safe form while keeping its contents.
33
+ *
34
+ * The counterpart to `describeShape`, and the opposite default: where the shape
35
+ * encoder asks "what can I say without revealing this", this one asks "what is
36
+ * the least I can leave out".
37
+ *
38
+ * Which is also why it does not share that encoder's string vocabulary. Here the
39
+ * values around a marker are real data, so a marker has to stay
40
+ * distinguishable from one — hence `{_: "elided"}` rather than a word. There,
41
+ * nothing structured is real, so there is nothing for a word to collide with.
42
+ *
43
+ * `seen` is the ancestor path, not every value visited. A value that appears
44
+ * twice in a result — a shared config object, the same node referenced by two
45
+ * dependents — is legitimately encoded twice; only a value containing *itself*
46
+ * is a cycle. Tracking all visited values instead would silently blank out
47
+ * shared structure and read as data loss.
48
+ */
49
+ export function describeFull(
50
+ value: unknown,
51
+ depth: number,
52
+ seen: Set<object>,
53
+ budget: Budget
54
+ ): unknown {
55
+ if (budget.remaining <= 0) {
56
+ return { _: "elided", by: "budget" } satisfies ShapeDescriptor;
57
+ }
58
+
59
+ budget.remaining -= 1;
60
+
61
+ if (value === null || value === undefined) {
62
+ return value ?? null;
63
+ }
64
+
65
+ switch (typeof value) {
66
+ case "boolean":
67
+ case "number": {
68
+ return value;
69
+ }
70
+ // Not JSON-safe, and no rendering of them is more useful than saying what
71
+ // they were.
72
+ case "bigint": {
73
+ return { _: "opaque", type: `bigint:${value.toString()}` } satisfies ShapeDescriptor;
74
+ }
75
+ case "function": {
76
+ return {
77
+ _: "opaque",
78
+ type: `function:${(value as { readonly name?: string }).name || "anonymous"}`,
79
+ } satisfies ShapeDescriptor;
80
+ }
81
+ case "symbol": {
82
+ return { _: "opaque", type: value.toString() } satisfies ShapeDescriptor;
83
+ }
84
+ case "string": {
85
+ return value.length <= FULL_MAX_STRING_LENGTH
86
+ ? value
87
+ : ({
88
+ _: "string",
89
+ length: value.length,
90
+ head: value.slice(0, FULL_MAX_STRING_LENGTH),
91
+ } satisfies ShapeDescriptor);
92
+ }
93
+ default: {
94
+ return describeFullStructure(value as object, depth, seen, budget);
95
+ }
96
+ }
97
+ }
98
+
99
+ function describeFullStructure(
100
+ value: object,
101
+ depth: number,
102
+ seen: Set<object>,
103
+ budget: Budget
104
+ ): unknown {
105
+ try {
106
+ return describeFullStructureUnguarded(value, depth, seen, budget);
107
+ } catch {
108
+ // See {@link UNREADABLE}. The `seen` set is left as this call found it: the
109
+ // one place that adds to it deletes in a `finally`.
110
+ return UNREADABLE;
111
+ }
112
+ }
113
+
114
+ function describeFullStructureUnguarded(
115
+ value: object,
116
+ depth: number,
117
+ seen: Set<object>,
118
+ budget: Budget
119
+ ): unknown {
120
+ if (seen.has(value)) {
121
+ return { _: "cycle" } satisfies ShapeDescriptor;
122
+ }
123
+
124
+ if (value instanceof Error) {
125
+ const described = describeError(value, "full", {
126
+ seen,
127
+ encodeValue: (own) => describeFull(own, depth + 1, seen, budget),
128
+ });
129
+
130
+ // Charged against the record's allowance like any other subtree, so one
131
+ // deeply-wrapped failure cannot spend the whole budget on itself.
132
+ budget.remaining -= described.causes.length;
133
+
134
+ return described;
135
+ }
136
+
137
+ if (value instanceof Date) {
138
+ return value.toISOString();
139
+ }
140
+
141
+ if (depth >= FULL_MAX_DEPTH) {
142
+ return { _: "elided", by: "depth" } satisfies ShapeDescriptor;
143
+ }
144
+
145
+ seen.add(value);
146
+
147
+ try {
148
+ if (Array.isArray(value)) {
149
+ const kept = value.slice(0, FULL_MAX_ENTRIES);
150
+ const encoded: Array<unknown> = kept.map((entry) =>
151
+ describeFull(entry, depth + 1, seen, budget)
152
+ );
153
+
154
+ if (value.length > FULL_MAX_ENTRIES) {
155
+ encoded.push({
156
+ _: "elided",
157
+ by: "entries",
158
+ length: value.length,
159
+ } satisfies ShapeDescriptor);
160
+ }
161
+
162
+ return encoded;
163
+ }
164
+
165
+ if (value instanceof Map) {
166
+ return {
167
+ _: "map",
168
+ entries: [...value.entries()]
169
+ .slice(0, FULL_MAX_ENTRIES)
170
+ .map(
171
+ ([key, entry]) =>
172
+ [
173
+ describeFull(key, depth + 1, seen, budget),
174
+ describeFull(entry, depth + 1, seen, budget),
175
+ ] as const
176
+ ),
177
+ size: value.size,
178
+ } satisfies ShapeDescriptor;
179
+ }
180
+
181
+ if (value instanceof Set) {
182
+ return {
183
+ _: "set",
184
+ values: [...value.values()]
185
+ .slice(0, FULL_MAX_ENTRIES)
186
+ .map((entry) => describeFull(entry, depth + 1, seen, budget)),
187
+ size: value.size,
188
+ } satisfies ShapeDescriptor;
189
+ }
190
+
191
+ const out: Record<string, unknown> = {};
192
+
193
+ // Own enumerable keys only. Walking the prototype chain would drag in
194
+ // methods and framework internals, which is noise rather than visibility.
195
+ const allKeys = Object.keys(value);
196
+ const keys = allKeys.slice(0, FULL_MAX_ENTRIES);
197
+
198
+ for (const key of keys) {
199
+ out[key] = describeFull((value as Record<string, unknown>)[key], depth + 1, seen, budget);
200
+ }
201
+
202
+ // An array that gets truncated pushes a marker; an object has to carry one
203
+ // as a key, and a silently short key list is the failure this whole encoder
204
+ // is written against — it reads as "the object had 256 keys", which is a lie
205
+ // the consumer has no way to detect.
206
+ //
207
+ // A real key named `_elided` loses to the marker. Preferred over a mangled
208
+ // name: the collision is vanishingly rare, and a marker under a name nobody
209
+ // reads is the same as no marker.
210
+ if (allKeys.length > keys.length) {
211
+ out["_elided"] = {
212
+ _: "elided",
213
+ by: "entries",
214
+ length: allKeys.length,
215
+ } satisfies ShapeDescriptor;
216
+ }
217
+
218
+ const prototype = Object.getPrototypeOf(value) as unknown;
219
+
220
+ // Class instances keep their type name alongside their fields: knowing a
221
+ // value is a `HubServerResult` and not a bag of keys is most of what makes
222
+ // a graph result readable.
223
+ if (prototype !== null && prototype !== Object.prototype) {
224
+ out["_type"] =
225
+ (value.constructor as { readonly name?: string } | undefined)?.name ?? "object";
226
+ }
227
+
228
+ return out;
229
+ } finally {
230
+ seen.delete(value);
231
+ }
232
+ }
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Client half of the Frond devtools hub.
3
+ *
4
+ * Platform-free by construction: the transport is a global `WebSocket` carrying
5
+ * ndjson, and nothing reachable from this entry point imports `node:` anything.
6
+ * The same build attaches from a browser, from Bun, and from React Native.
7
+ * Filesystem discovery lives in `@frondruntime/devtools/node`, kept behind its
8
+ * own export so a browser bundler never has to resolve it.
9
+ */
10
+ export { type AttachOptions, attachLayer, attachRuntime } from "./attach.ts";
11
+ export { attachDevtools, type DevtoolsOptions } from "./attachDevtools.ts";
12
+ export { createValueEncoder, encodeRecord, type ValueEncoder } from "./encode.ts";
13
+ export { type EncodePolicy, resolvePolicy } from "./policy.ts";
14
+ export * from "./protocol.ts";
15
+ export { encodeGraphSnapshot, type SnapshotRequest } from "./snapshot.ts";
package/src/node.ts ADDED
@@ -0,0 +1,110 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, join, parse } from "node:path";
3
+ import { HUB_DEFAULT_PORT } from "./protocol.ts";
4
+
5
+ /**
6
+ * Filesystem discovery for hosts that have a filesystem.
7
+ *
8
+ * Deliberately a separate export from the package root. A browser bundle must
9
+ * never have to resolve `node:fs`, and the reliable way to guarantee that is
10
+ * for the module graph a browser reaches to not contain it — not a runtime
11
+ * guard, which bundlers still follow.
12
+ */
13
+
14
+ /** What a running hub writes to `.frond/hub-<port>.json`. */
15
+ export type HubLock = {
16
+ readonly protocolVersion: number;
17
+ readonly attachUrl: string;
18
+ readonly host: string;
19
+ readonly port: number;
20
+ readonly pid: number;
21
+ };
22
+
23
+ export type ReadHubLockOptions = {
24
+ /** Which hub to look for. Defaults to the default port. */
25
+ readonly port?: number | undefined;
26
+ /** Where to start searching. Defaults to the process's working directory. */
27
+ readonly cwd?: string | undefined;
28
+ };
29
+
30
+ /**
31
+ * Finds the lockfile of a hub running for this project.
32
+ *
33
+ * Walks up from `cwd` rather than looking only in it, because the hub is
34
+ * started from the repository root and the app that wants to attach usually is
35
+ * not — a monorepo package running its own dev server is the normal case, not
36
+ * the exception.
37
+ *
38
+ * Returns `undefined` rather than throwing for every way the file can fail to
39
+ * be a lock: absent, unreadable, or malformed. Not finding a hub is the
40
+ * ordinary state of a machine where nobody started one, and the caller's
41
+ * response to all three is identical anyway.
42
+ *
43
+ * What it does *not* do is decide whether the hub named by a well-formed lock
44
+ * is still there. A hub that died without running its finalizer leaves a file
45
+ * that parses, and this returns it. Liveness is the caller's call and the
46
+ * fields to make it are on the result: `pid` for a signal probe, `port` for a
47
+ * dial, and `protocolVersion` to compare against the one this build speaks. A
48
+ * reader that guessed on the caller's behalf would be guessing wrong for the
49
+ * scripts that only want the address.
50
+ */
51
+ export function readHubLock(options: ReadHubLockOptions = {}): HubLock | undefined {
52
+ const port = options.port ?? HUB_DEFAULT_PORT;
53
+ const relative = join(".frond", `hub-${port}.json`);
54
+
55
+ let directory = options.cwd ?? process.cwd();
56
+ const root = parse(directory).root;
57
+
58
+ for (;;) {
59
+ const found = readLock(join(directory, relative));
60
+
61
+ if (found !== undefined) {
62
+ return found;
63
+ }
64
+
65
+ if (directory === root) {
66
+ return undefined;
67
+ }
68
+
69
+ const parent = dirname(directory);
70
+
71
+ // `dirname` is a fixed point at the root on every platform, and on some
72
+ // inputs it reaches one that is not `parse().root`. Without this the loop
73
+ // above would spin forever on exactly the paths nobody tests with.
74
+ if (parent === directory) {
75
+ return undefined;
76
+ }
77
+
78
+ directory = parent;
79
+ }
80
+ }
81
+
82
+ function readLock(path: string): HubLock | undefined {
83
+ let parsed: unknown;
84
+
85
+ try {
86
+ parsed = JSON.parse(readFileSync(path, "utf8"));
87
+ } catch {
88
+ return undefined;
89
+ }
90
+
91
+ if (typeof parsed !== "object" || parsed === null) {
92
+ return undefined;
93
+ }
94
+
95
+ const lock = parsed as Partial<HubLock>;
96
+
97
+ // Every field checked rather than cast, because this file outlives the process
98
+ // that wrote it if that process died badly — so what is on disk may have been
99
+ // written by a build that is no longer installed. A shape check is all this
100
+ // does: it says the five fields are there and are the right types, not that
101
+ // the hub behind them is alive or speaks the protocol this build speaks.
102
+ // Those are the caller's to decide, from `pid` and `protocolVersion`.
103
+ return typeof lock.attachUrl === "string" &&
104
+ typeof lock.host === "string" &&
105
+ typeof lock.port === "number" &&
106
+ typeof lock.pid === "number" &&
107
+ typeof lock.protocolVersion === "number"
108
+ ? (lock as HubLock)
109
+ : undefined;
110
+ }
package/src/policy.ts ADDED
@@ -0,0 +1,37 @@
1
+ import type { ValuePolicy } from "./protocol.ts";
2
+
3
+ /**
4
+ * What this encoder can produce. All three policies are implemented.
5
+ *
6
+ * `"full"` is a stub in the sense that it has no per-field allowlist and no
7
+ * redaction — it sends what it finds. It is not a stub in its bounds: cycles,
8
+ * depth, and breadth are enforced, because those three are not polish. A cyclic
9
+ * or unboundedly deep graph result would hang the observed app inside its own
10
+ * devtools, on its own event loop.
11
+ *
12
+ * What those bounds are not is a size budget. This socket is loopback and the
13
+ * eventual reader is an agent's context window, so the scarce resource is the
14
+ * reader's attention rather than the wire — which is why `"shape"` spends real
15
+ * effort being terse and `"full"` spends none.
16
+ */
17
+ export type EncodePolicy = ValuePolicy;
18
+
19
+ /** Increasing disclosure. The only ordering the clamp below depends on. */
20
+ const POLICY_RANK: Record<ValuePolicy, number> = { none: 0, shape: 1, full: 2 };
21
+
22
+ /**
23
+ * Clamps what the hub asked for to what this app is willing to send.
24
+ *
25
+ * The whole negotiation lives here, in one expression, rather than as a policy
26
+ * check threaded through the encoder: a sender may always answer with less than
27
+ * it was asked for and may never answer with more, and that rule is only
28
+ * trustworthy if there is exactly one place it can be got wrong.
29
+ *
30
+ * Its own module for the same reason. This is the one function in the package
31
+ * whose failure mode is disclosure rather than a bad rendering, and it should be
32
+ * readable — and testable — without the several hundred lines of walking that
33
+ * depend on it.
34
+ */
35
+ export function resolvePolicy(requested: ValuePolicy, ceiling: ValuePolicy): EncodePolicy {
36
+ return POLICY_RANK[requested] <= POLICY_RANK[ceiling] ? requested : ceiling;
37
+ }