depkill 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +179 -3
- package/data/module-replacements.LICENSE +21 -0
- package/data/module-replacements.json +947 -0
- package/dist/src/anticheat/constants.js +105 -0
- package/dist/src/anticheat/imports.js +419 -0
- package/dist/src/anticheat/tokens.js +177 -0
- package/dist/src/anticheat.js +189 -0
- package/dist/src/card/format.js +113 -0
- package/dist/src/card/svg.js +137 -0
- package/dist/src/card.js +364 -0
- package/dist/src/check.js +139 -0
- package/dist/src/cli.js +333 -0
- package/dist/src/gate/holdout.js +78 -0
- package/dist/src/gate/process.js +78 -0
- package/dist/src/gate.js +532 -0
- package/dist/src/graph.js +148 -0
- package/dist/src/holdout/perturb.js +108 -0
- package/dist/src/holdout/snapshot.js +113 -0
- package/dist/src/init.js +76 -0
- package/dist/src/inputs/generate.js +282 -0
- package/dist/src/inputs.js +273 -0
- package/dist/src/measure.js +149 -0
- package/dist/src/project.js +72 -0
- package/dist/src/record.js +180 -0
- package/dist/src/registry.js +78 -0
- package/dist/src/replacement.js +146 -0
- package/dist/src/runner.js +227 -0
- package/dist/src/runtime/agent-inputs.js +36 -0
- package/dist/src/runtime/child.js +260 -0
- package/dist/src/runtime/esm-hooks.js +44 -0
- package/dist/src/runtime/fsguard.js +264 -0
- package/dist/src/runtime/inspect.js +115 -0
- package/dist/src/runtime/lockdown.js +157 -0
- package/dist/src/runtime/protocol.js +16 -0
- package/dist/src/scan.js +210 -0
- package/dist/src/serialize.js +399 -0
- package/dist/src/tooling.js +88 -0
- package/dist/src/types.js +9 -0
- package/dist/src/usage/common.js +36 -0
- package/dist/src/usage/fallback.js +227 -0
- package/dist/src/usage/ts.js +142 -0
- package/dist/src/usage.js +97 -0
- package/dist/src/util/exports.js +86 -0
- package/dist/src/util/fs.js +64 -0
- package/dist/src/util/term.js +61 -0
- package/package.json +54 -6
- package/skills/AGENTS.section.md +52 -0
- package/skills/depkill/SKILL.md +148 -0
package/dist/src/scan.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { buildGraph, dependencyClosure, exclusiveClosure } from './graph.js';
|
|
3
|
+
import { defaultReturnsFunction } from './inputs/generate.js';
|
|
4
|
+
import { fetchMaintainers, mapPool } from './registry.js';
|
|
5
|
+
import { isRootConfigFile, loadToolingContext, toolingReason } from './tooling.js';
|
|
6
|
+
import { scanUsage } from './usage.js';
|
|
7
|
+
import { formatBytes, paint, renderTable, truncate } from './util/term.js';
|
|
8
|
+
const MAX_EXCLUSIVE_BYTES = 5 * 1024 * 1024;
|
|
9
|
+
const MAX_EXPORT_IDS = 8;
|
|
10
|
+
/** Direct dependencies processed at once; each fetchMaintainers call has its own request pool. */
|
|
11
|
+
const ENTRY_CONCURRENCY = 4;
|
|
12
|
+
/** Resolved from the compiled module (`dist/src/scan.js`), so it works from a git checkout and an npm install. */
|
|
13
|
+
const DEFAULT_REPLACEMENTS = new URL('../../data/module-replacements.json', import.meta.url);
|
|
14
|
+
const NON_PROD_PATH = /^(?:examples?|tests?|__tests__|bench|benchmarks)\//i;
|
|
15
|
+
const STATUS_ORDER = { candidate: 0, unused: 1, unsupported: 2 };
|
|
16
|
+
/**
|
|
17
|
+
* Package -> human hint for a native/lighter alternative. Keys starting with `_` (metadata) and
|
|
18
|
+
* non-string values are skipped. A missing, unreadable or malformed file means no hints.
|
|
19
|
+
*/
|
|
20
|
+
export function loadReplacements(file = DEFAULT_REPLACEMENTS) {
|
|
21
|
+
let data;
|
|
22
|
+
try {
|
|
23
|
+
data = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return {};
|
|
27
|
+
}
|
|
28
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data))
|
|
29
|
+
return {};
|
|
30
|
+
return Object.fromEntries(Object.entries(data).filter((pair) => !pair[0].startsWith('_') && typeof pair[1] === 'string'));
|
|
31
|
+
}
|
|
32
|
+
/** payoff / effort, rounded to 2 decimals. */
|
|
33
|
+
export function score(e) {
|
|
34
|
+
const payoff = e.exclusivePackages * 3 + e.exclusiveBytes / 102400 + e.installScripts * 10 + (e.maintainers ?? 0);
|
|
35
|
+
const effort = 1 + e.exportIds.length * 2 + e.usageSites * 0.5;
|
|
36
|
+
return Math.round((payoff / effort) * 100) / 100;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Status rules in order. A dependency nobody imports is only "unused" when no tooling use is detected (R21);
|
|
40
|
+
* one imported only by root tooling config is unsupported (R22).
|
|
41
|
+
*/
|
|
42
|
+
function classify(facts) {
|
|
43
|
+
if (facts.isNative)
|
|
44
|
+
return { status: 'unsupported', reason: 'native module' };
|
|
45
|
+
if (facts.bytes > MAX_EXCLUSIVE_BYTES)
|
|
46
|
+
return { status: 'unsupported', reason: 'too large for v1' };
|
|
47
|
+
if (facts.exportIds.length > MAX_EXPORT_IDS)
|
|
48
|
+
return { status: 'unsupported', reason: 'too many used exports for v1' };
|
|
49
|
+
if (facts.usageSites === 0) {
|
|
50
|
+
const tooling = facts.tooling();
|
|
51
|
+
return tooling === null
|
|
52
|
+
? { status: 'unused', reason: 'not imported anywhere — uninstall it, then run your tests (it may be loaded by name at runtime)' }
|
|
53
|
+
: { status: 'unsupported', reason: tooling };
|
|
54
|
+
}
|
|
55
|
+
if (facts.configOnly)
|
|
56
|
+
return { status: 'unsupported', reason: 'used only by tooling config' };
|
|
57
|
+
return { status: 'candidate', reason: null };
|
|
58
|
+
}
|
|
59
|
+
function sharedBy(graph, name) {
|
|
60
|
+
const targetId = directId(graph, name);
|
|
61
|
+
for (const [other] of [...graph.direct.prod, ...graph.direct.dev]) {
|
|
62
|
+
if (other === name)
|
|
63
|
+
continue;
|
|
64
|
+
if (dependencyClosure(graph, other).some((node) => node.id === targetId || node.name === name))
|
|
65
|
+
return other;
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
async function scanEntry(project, graph, tooling, name, kind, sites, hint, offline) {
|
|
70
|
+
const closure = exclusiveClosure(graph, name);
|
|
71
|
+
const exclusiveBytes = closure.reduce((total, node) => total + node.sizeBytes, 0);
|
|
72
|
+
const exportIds = [...new Set(sites.flatMap((site) => site.exportIds))].sort();
|
|
73
|
+
const pkgDir = graph.nodes.get(directId(graph, name)).dir;
|
|
74
|
+
const classified = classify({
|
|
75
|
+
isNative: closure.some((node) => node.isNative),
|
|
76
|
+
bytes: exclusiveBytes,
|
|
77
|
+
exportIds,
|
|
78
|
+
usageSites: sites.length,
|
|
79
|
+
configOnly: sites.length > 0 && sites.every((site) => isRootConfigFile(site.file)),
|
|
80
|
+
tooling: () => toolingReason(tooling, name, pkgDir),
|
|
81
|
+
});
|
|
82
|
+
let reason = classified.reason;
|
|
83
|
+
if (classified.status === 'candidate') {
|
|
84
|
+
const notes = [];
|
|
85
|
+
if (closure.length === 0) {
|
|
86
|
+
notes.push(`shared: still required by ${sharedBy(graph, name) ?? 'another dependency'} — removing it saves nothing`);
|
|
87
|
+
}
|
|
88
|
+
if (sites.length > 0 && sites.every((site) => NON_PROD_PATH.test(site.file))) {
|
|
89
|
+
notes.push('used only in examples/tests');
|
|
90
|
+
}
|
|
91
|
+
if (project.ts !== null && exportIds.length === 1 && exportIds[0] === '#default'
|
|
92
|
+
&& defaultReturnsFunction(project.ts, pkgDir, name, project.root)) {
|
|
93
|
+
notes.push('factory — likely unsupported');
|
|
94
|
+
}
|
|
95
|
+
reason = notes.length > 0 ? notes.join('; ') : null;
|
|
96
|
+
}
|
|
97
|
+
const base = {
|
|
98
|
+
name,
|
|
99
|
+
kind,
|
|
100
|
+
exclusivePackages: closure.length,
|
|
101
|
+
exclusiveBytes,
|
|
102
|
+
installScripts: closure.filter((node) => node.hasInstallScript).length,
|
|
103
|
+
// Offline: the registry module is not touched at all.
|
|
104
|
+
maintainers: offline ? null : await fetchMaintainers(closure, { offline: false }),
|
|
105
|
+
usageSites: sites.length,
|
|
106
|
+
exportIds,
|
|
107
|
+
nativeAlternative: hint ?? null,
|
|
108
|
+
status: classified.status,
|
|
109
|
+
reason,
|
|
110
|
+
};
|
|
111
|
+
return { ...base, score: score(base) };
|
|
112
|
+
}
|
|
113
|
+
function directId(graph, name) {
|
|
114
|
+
return graph.direct.prod.get(name) ?? graph.direct.dev.get(name);
|
|
115
|
+
}
|
|
116
|
+
function compareEntries(a, b) {
|
|
117
|
+
return STATUS_ORDER[a.status] - STATUS_ORDER[b.status]
|
|
118
|
+
|| (a.status === 'candidate' ? (b.exclusivePackages > 0 ? 1 : 0) - (a.exclusivePackages > 0 ? 1 : 0) || b.score - a.score : 0)
|
|
119
|
+
|| (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* One entry per direct prod and dev dependency (excluding `depkill` itself), ranked by how worthwhile and easy
|
|
123
|
+
* removal is: candidates with positive exclusive savings by score (desc), then 0-exclusive candidates, then unused,
|
|
124
|
+
* then unsupported. With `offline`, the registry is never contacted and `maintainers` is null.
|
|
125
|
+
*/
|
|
126
|
+
export async function runScan(project, opts) {
|
|
127
|
+
const graph = buildGraph(project.root, project.pkg);
|
|
128
|
+
const direct = [
|
|
129
|
+
...[...graph.direct.prod.keys()].filter((name) => name !== 'depkill').map((name) => [name, 'prod']),
|
|
130
|
+
...[...graph.direct.dev.keys()].filter((name) => name !== 'depkill').map((name) => [name, 'dev']),
|
|
131
|
+
];
|
|
132
|
+
const sitesByPkg = new Map();
|
|
133
|
+
for (const site of scanUsage(project, new Set(direct.map(([name]) => name)))) {
|
|
134
|
+
sitesByPkg.set(site.pkg, [...(sitesByPkg.get(site.pkg) ?? []), site]);
|
|
135
|
+
}
|
|
136
|
+
const hints = loadReplacements(opts.replacementsFile);
|
|
137
|
+
const tooling = loadToolingContext(project);
|
|
138
|
+
const hintFor = (name) => (Object.hasOwn(hints, name) ? hints[name] : undefined);
|
|
139
|
+
const entries = await mapPool(direct, ENTRY_CONCURRENCY, ([name, kind]) => scanEntry(project, graph, tooling, name, kind, sitesByPkg.get(name) ?? [], hintFor(name), opts.offline));
|
|
140
|
+
return entries.sort(compareEntries);
|
|
141
|
+
}
|
|
142
|
+
const COLUMNS = [
|
|
143
|
+
{ header: '#', align: 'right' },
|
|
144
|
+
{ header: 'package' },
|
|
145
|
+
{ header: 'kind' },
|
|
146
|
+
{ header: 'status' },
|
|
147
|
+
{ header: 'removes(pkgs)', align: 'right' },
|
|
148
|
+
{ header: 'size', align: 'right' },
|
|
149
|
+
{ header: 'scripts', align: 'right' },
|
|
150
|
+
{ header: 'maint', align: 'right' },
|
|
151
|
+
{ header: 'exports', align: 'right' },
|
|
152
|
+
{ header: 'score', align: 'right' },
|
|
153
|
+
];
|
|
154
|
+
const PACKAGE_COLUMN = 1;
|
|
155
|
+
const STATUS_COLUMN = 3;
|
|
156
|
+
const COLUMN_GAP = 2;
|
|
157
|
+
const MIN_PACKAGE_WIDTH = 12;
|
|
158
|
+
const STATUS_STYLE = { candidate: 'green', unused: 'yellow', unsupported: 'dim' };
|
|
159
|
+
/** Plain cells for each entry (package name untruncated). */
|
|
160
|
+
function plainRows(entries) {
|
|
161
|
+
return entries.map((e, i) => [
|
|
162
|
+
String(i + 1), e.name, e.kind, e.status, String(e.exclusivePackages), formatBytes(e.exclusiveBytes),
|
|
163
|
+
String(e.installScripts), e.maintainers === null ? '-' : String(e.maintainers), String(e.exportIds.length), e.score.toFixed(2),
|
|
164
|
+
]);
|
|
165
|
+
}
|
|
166
|
+
/** Widest the package column may be so the table fits in `width` columns. */
|
|
167
|
+
function packageWidth(rows, width) {
|
|
168
|
+
const others = COLUMNS.reduce((total, col, i) => (i === PACKAGE_COLUMN ? total : total + Math.max(col.header.length, ...rows.map((row) => row[i].length))), 0);
|
|
169
|
+
return Math.max(MIN_PACKAGE_WIDTH, width - others - COLUMN_GAP * (COLUMNS.length - 1));
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Human-readable scan result: the ranked table, alternative hints, reasons for non-candidates and the next step.
|
|
173
|
+
* `width` bounds the table (long package names are truncated in the table only).
|
|
174
|
+
*/
|
|
175
|
+
export function renderScan(entries, opts) {
|
|
176
|
+
if (entries.length === 0)
|
|
177
|
+
return 'No dependencies found in package.json.\n';
|
|
178
|
+
const { color } = opts;
|
|
179
|
+
const rows = plainRows(entries);
|
|
180
|
+
const maxName = packageWidth(rows, opts.width);
|
|
181
|
+
const styled = rows.map((row, i) => row.map((cell, col) => {
|
|
182
|
+
if (col === PACKAGE_COLUMN)
|
|
183
|
+
return paint('bold', truncate(cell, maxName), color);
|
|
184
|
+
if (col === STATUS_COLUMN)
|
|
185
|
+
return paint(STATUS_STYLE[entries[i].status], cell, color);
|
|
186
|
+
return cell;
|
|
187
|
+
}));
|
|
188
|
+
const [header, ...body] = renderTable(COLUMNS, styled);
|
|
189
|
+
const lines = [paint('dim', header, color), ...body];
|
|
190
|
+
const hinted = entries.filter((e) => e.nativeAlternative !== null);
|
|
191
|
+
if (hinted.length > 0) {
|
|
192
|
+
lines.push('', 'Alternatives (module-replacements):');
|
|
193
|
+
for (const e of hinted)
|
|
194
|
+
lines.push(` ${e.name}: ${e.nativeAlternative}`);
|
|
195
|
+
}
|
|
196
|
+
const notes = entries.filter((e) => e.reason !== null);
|
|
197
|
+
if (notes.length > 0) {
|
|
198
|
+
lines.push('', 'Notes:');
|
|
199
|
+
for (const e of notes)
|
|
200
|
+
lines.push(` ${e.name}: ${e.reason}`);
|
|
201
|
+
}
|
|
202
|
+
const candidates = entries.filter((e) => e.status === 'candidate');
|
|
203
|
+
const next = candidates.find((e) => e.exclusivePackages > 0 && !(e.reason?.includes('used only in examples/tests') ?? false))
|
|
204
|
+
?? candidates.find((e) => e.exclusivePackages > 0)
|
|
205
|
+
?? candidates[0];
|
|
206
|
+
lines.push('', next !== undefined
|
|
207
|
+
? `Next: depkill record ${paint('cyan', next.name, color)}`
|
|
208
|
+
: 'No removal candidates found.');
|
|
209
|
+
return `${lines.join('\n')}\n`;
|
|
210
|
+
}
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import { types } from 'node:util';
|
|
3
|
+
const ROOT = '$';
|
|
4
|
+
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
5
|
+
const ERROR_CTORS = {
|
|
6
|
+
Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError,
|
|
7
|
+
};
|
|
8
|
+
const TYPED_ARRAY_PROTO = Object.getPrototypeOf(Uint8Array.prototype);
|
|
9
|
+
// ---------- paths (shared by encode and decode so $ref targets line up) ----------
|
|
10
|
+
function propPath(parent, key) {
|
|
11
|
+
return IDENTIFIER.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;
|
|
12
|
+
}
|
|
13
|
+
const indexPath = (parent, i) => `${parent}[${i}]`;
|
|
14
|
+
const mapKeyPath = (parent, i) => `${parent}[map:${i}:key]`;
|
|
15
|
+
const mapValuePath = (parent, i) => `${parent}[map:${i}:value]`;
|
|
16
|
+
const setItemPath = (parent, i) => `${parent}[set:${i}]`;
|
|
17
|
+
// ---------- encode ----------
|
|
18
|
+
export function encode(value) {
|
|
19
|
+
return encodeAt(value, ROOT, new Map());
|
|
20
|
+
}
|
|
21
|
+
function encodeAt(value, path, ancestors) {
|
|
22
|
+
switch (typeof value) {
|
|
23
|
+
case 'string':
|
|
24
|
+
case 'boolean':
|
|
25
|
+
return value;
|
|
26
|
+
case 'number':
|
|
27
|
+
return encodeNumber(value);
|
|
28
|
+
case 'undefined':
|
|
29
|
+
return { $u: 1 };
|
|
30
|
+
case 'bigint':
|
|
31
|
+
return { $big: value.toString() };
|
|
32
|
+
case 'symbol':
|
|
33
|
+
return { $sym: value.description ?? '' };
|
|
34
|
+
case 'function':
|
|
35
|
+
return { $fn: value.name || 'anonymous' };
|
|
36
|
+
default:
|
|
37
|
+
return value === null ? null : encodeObject(value, path, ancestors);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function encodeNumber(n) {
|
|
41
|
+
if (Number.isNaN(n))
|
|
42
|
+
return { $n: 'NaN' };
|
|
43
|
+
if (n === Infinity)
|
|
44
|
+
return { $n: 'Infinity' };
|
|
45
|
+
if (n === -Infinity)
|
|
46
|
+
return { $n: '-Infinity' };
|
|
47
|
+
if (Object.is(n, -0))
|
|
48
|
+
return { $n: '-0' };
|
|
49
|
+
return n;
|
|
50
|
+
}
|
|
51
|
+
function encodeObject(obj, path, ancestors) {
|
|
52
|
+
const ancestorPath = ancestors.get(obj);
|
|
53
|
+
if (ancestorPath !== undefined)
|
|
54
|
+
return { $ref: ancestorPath };
|
|
55
|
+
ancestors.set(obj, path);
|
|
56
|
+
try {
|
|
57
|
+
return encodeContainer(obj, path, ancestors);
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
return encodeThrown(error); // e.g. a Proxy whose traps throw
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
ancestors.delete(obj);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function encodeContainer(obj, path, ancestors) {
|
|
67
|
+
if (Array.isArray(obj))
|
|
68
|
+
return encodeArray(obj, path, ancestors);
|
|
69
|
+
if (obj instanceof Date)
|
|
70
|
+
return { $date: Number.isNaN(obj.getTime()) ? 'Invalid' : obj.toISOString() };
|
|
71
|
+
if (obj instanceof RegExp)
|
|
72
|
+
return { $re: obj.source, flags: obj.flags };
|
|
73
|
+
if (obj instanceof Map)
|
|
74
|
+
return encodeMap(obj, path, ancestors);
|
|
75
|
+
if (obj instanceof Set)
|
|
76
|
+
return encodeSet(obj, path, ancestors);
|
|
77
|
+
if (ArrayBuffer.isView(obj))
|
|
78
|
+
return encodeBytes(Buffer.from(obj.buffer, obj.byteOffset, obj.byteLength), ctorName(obj));
|
|
79
|
+
if (obj instanceof ArrayBuffer)
|
|
80
|
+
return encodeBytes(Buffer.from(obj), 'ArrayBuffer');
|
|
81
|
+
if (isError(obj))
|
|
82
|
+
return encodeError(obj);
|
|
83
|
+
if (types.isModuleNamespaceObject(obj))
|
|
84
|
+
return encodeNamespace(obj, path, ancestors);
|
|
85
|
+
if (isPlainObject(obj))
|
|
86
|
+
return encodePlain(obj, path, ancestors);
|
|
87
|
+
if (obj instanceof URL)
|
|
88
|
+
return { $class: 'URL', props: { href: obj.href } };
|
|
89
|
+
if (obj instanceof URLSearchParams)
|
|
90
|
+
return { $class: 'URLSearchParams', props: { value: obj.toString() } };
|
|
91
|
+
if (isBoxedPrimitive(obj))
|
|
92
|
+
return { $boxed: encodeAt(obj.valueOf(), path, ancestors) };
|
|
93
|
+
if (isOpaque(obj))
|
|
94
|
+
return { $opaque: ctorName(obj) };
|
|
95
|
+
const { props, desc } = encodePropsWithDesc(obj, path, ancestors);
|
|
96
|
+
return Object.keys(desc).length > 0
|
|
97
|
+
? { $class: ctorName(obj), props, $desc: desc }
|
|
98
|
+
: { $class: ctorName(obj), props };
|
|
99
|
+
}
|
|
100
|
+
function isBoxedPrimitive(obj) {
|
|
101
|
+
return obj instanceof Number || obj instanceof String || obj instanceof Boolean
|
|
102
|
+
|| obj instanceof BigInt || obj instanceof Symbol;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Instances whose state is invisible to own string props (Promise, Weak*, or classes exposing
|
|
106
|
+
* state only through prototype getters). Encoding them as empty `$class` would make different
|
|
107
|
+
* values compare equal, so they get an explicit opaque tag instead.
|
|
108
|
+
*/
|
|
109
|
+
function isOpaque(obj) {
|
|
110
|
+
if (obj instanceof Promise || obj instanceof WeakMap || obj instanceof WeakSet || obj instanceof WeakRef)
|
|
111
|
+
return true;
|
|
112
|
+
return Object.getOwnPropertyNames(obj).length === 0 && prototypeChainHasGetters(obj);
|
|
113
|
+
}
|
|
114
|
+
function prototypeChainHasGetters(obj) {
|
|
115
|
+
for (let proto = Object.getPrototypeOf(obj); proto !== null && !isObjectPrototype(proto); proto = Object.getPrototypeOf(proto)) {
|
|
116
|
+
if (Object.values(Object.getOwnPropertyDescriptors(proto)).some((d) => d.get !== undefined))
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
/** `Object.prototype` from any realm (it is the only prototype-less prototype in a normal chain). */
|
|
122
|
+
function isObjectPrototype(proto) {
|
|
123
|
+
return proto === Object.prototype || Object.getPrototypeOf(proto) === null;
|
|
124
|
+
}
|
|
125
|
+
function encodeArray(arr, path, ancestors) {
|
|
126
|
+
return Array.from({ length: arr.length }, (_, i) => i in arr ? encodeProp(arr, String(i), indexPath(path, i), ancestors) : { $hole: 1 });
|
|
127
|
+
}
|
|
128
|
+
function encodeMap(map, path, ancestors) {
|
|
129
|
+
const entries = [...map].map(([k, v], i) => [
|
|
130
|
+
encodeAt(k, mapKeyPath(path, i), ancestors),
|
|
131
|
+
encodeAt(v, mapValuePath(path, i), ancestors),
|
|
132
|
+
]);
|
|
133
|
+
return { $map: entries };
|
|
134
|
+
}
|
|
135
|
+
function encodeSet(set, path, ancestors) {
|
|
136
|
+
return { $set: [...set].map((item, i) => encodeAt(item, setItemPath(path, i), ancestors)) };
|
|
137
|
+
}
|
|
138
|
+
function encodeBytes(bytes, type) {
|
|
139
|
+
return { $bytes: bytes.toString('base64'), type };
|
|
140
|
+
}
|
|
141
|
+
const UNREADABLE = '<unreadable>';
|
|
142
|
+
function encodeError(error) {
|
|
143
|
+
return { $err: readString(() => error.name, 'Error'), message: readString(() => error.message, UNREADABLE) };
|
|
144
|
+
}
|
|
145
|
+
/** Encodes a value caught from a throwing getter/trap; must itself never throw. */
|
|
146
|
+
function encodeThrown(thrown) {
|
|
147
|
+
try {
|
|
148
|
+
return isError(thrown) ? encodeError(thrown) : { $err: 'Error', message: readString(() => thrown, UNREADABLE) };
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return { $err: 'Error', message: UNREADABLE };
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** `String(read())`, or `fallback` if reading or stringifying throws. */
|
|
155
|
+
function readString(read, fallback) {
|
|
156
|
+
try {
|
|
157
|
+
return String(read());
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return fallback;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function defineOwn(target, key, value) {
|
|
164
|
+
Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
|
|
165
|
+
}
|
|
166
|
+
function encodeNamespace(obj, path, ancestors) {
|
|
167
|
+
const props = {};
|
|
168
|
+
for (const key of Object.keys(obj))
|
|
169
|
+
defineOwn(props, key, encodeProp(obj, key, propPath(path, key), ancestors));
|
|
170
|
+
return Object.keys(props).some((k) => k.startsWith('$')) ? { $obj: props } : props;
|
|
171
|
+
}
|
|
172
|
+
function encodePlain(obj, path, ancestors) {
|
|
173
|
+
const nullProto = Object.getPrototypeOf(obj) === null;
|
|
174
|
+
const { props, desc } = encodePropsWithDesc(obj, path, ancestors);
|
|
175
|
+
const hasDollar = Object.keys(props).some((k) => k.startsWith('$'));
|
|
176
|
+
const hasDesc = Object.keys(desc).length > 0;
|
|
177
|
+
if (!hasDollar && !hasDesc && !nullProto)
|
|
178
|
+
return props;
|
|
179
|
+
return {
|
|
180
|
+
$obj: props,
|
|
181
|
+
...(hasDesc ? { $desc: desc } : {}),
|
|
182
|
+
...(nullProto ? { $nullproto: 1 } : {}),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
/** Own string-keyed properties (including non-enumerable) and any non-default descriptors, in property order. */
|
|
186
|
+
function encodePropsWithDesc(obj, path, ancestors) {
|
|
187
|
+
const props = {};
|
|
188
|
+
const desc = {};
|
|
189
|
+
for (const key of Object.getOwnPropertyNames(obj)) {
|
|
190
|
+
defineOwn(props, key, encodeProp(obj, key, propPath(path, key), ancestors));
|
|
191
|
+
let d;
|
|
192
|
+
try {
|
|
193
|
+
d = Object.getOwnPropertyDescriptor(obj, key);
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
// Proxy trap threw; keep default descriptor
|
|
197
|
+
}
|
|
198
|
+
if (d === undefined)
|
|
199
|
+
continue;
|
|
200
|
+
if (!('value' in d)) {
|
|
201
|
+
defineOwn(desc, key, {
|
|
202
|
+
e: Boolean(d.enumerable),
|
|
203
|
+
c: Boolean(d.configurable),
|
|
204
|
+
get: typeof d.get === 'function',
|
|
205
|
+
set: typeof d.set === 'function',
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
else if (!d.enumerable || !d.writable || !d.configurable) {
|
|
209
|
+
defineOwn(desc, key, { e: Boolean(d.enumerable), w: Boolean(d.writable), c: Boolean(d.configurable) });
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return { props, desc };
|
|
213
|
+
}
|
|
214
|
+
function encodeProp(obj, key, path, ancestors) {
|
|
215
|
+
let value;
|
|
216
|
+
try {
|
|
217
|
+
value = obj[key];
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
return encodeThrown(error);
|
|
221
|
+
}
|
|
222
|
+
return encodeAt(value, path, ancestors);
|
|
223
|
+
}
|
|
224
|
+
function isError(value) {
|
|
225
|
+
return value instanceof Error || Object.prototype.toString.call(value) === '[object Error]';
|
|
226
|
+
}
|
|
227
|
+
/** Prototype is null or an `Object.prototype` (from any realm). */
|
|
228
|
+
function isPlainObject(obj) {
|
|
229
|
+
const proto = Object.getPrototypeOf(obj);
|
|
230
|
+
return proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null;
|
|
231
|
+
}
|
|
232
|
+
function ctorName(obj) {
|
|
233
|
+
const proto = Object.getPrototypeOf(obj);
|
|
234
|
+
const ctor = proto?.constructor;
|
|
235
|
+
return typeof ctor === 'function' && ctor.name ? ctor.name : 'anonymous';
|
|
236
|
+
}
|
|
237
|
+
// ---------- decode ----------
|
|
238
|
+
/** Rebuilds a JS value from its encoding. Functions become named no-op stubs; class instances become plain objects. */
|
|
239
|
+
export function decode(e) {
|
|
240
|
+
return decodeAt(e, ROOT, new Map());
|
|
241
|
+
}
|
|
242
|
+
function decodeAt(e, path, refs) {
|
|
243
|
+
if (e === null || typeof e !== 'object')
|
|
244
|
+
return e;
|
|
245
|
+
if (Array.isArray(e))
|
|
246
|
+
return decodeArray(e, path, refs);
|
|
247
|
+
return decodeObject(e, path, refs);
|
|
248
|
+
}
|
|
249
|
+
function decodeArray(items, path, refs) {
|
|
250
|
+
const out = new Array(items.length);
|
|
251
|
+
refs.set(path, out);
|
|
252
|
+
items.forEach((item, i) => {
|
|
253
|
+
if (!isHole(item))
|
|
254
|
+
out[i] = decodeAt(item, indexPath(path, i), refs);
|
|
255
|
+
});
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
function isHole(item) {
|
|
259
|
+
return item !== null && typeof item === 'object' && !Array.isArray(item) && Object.hasOwn(item, '$hole');
|
|
260
|
+
}
|
|
261
|
+
function decodeObject(o, path, refs) {
|
|
262
|
+
if (Object.hasOwn(o, '$obj'))
|
|
263
|
+
return decodePlain(asObject(o.$obj), path, refs, asDesc(o.$desc), o.$nullproto === 1);
|
|
264
|
+
if (Object.hasOwn(o, '$class'))
|
|
265
|
+
return decodePlain(asObject(o.props), path, refs, asDesc(o.$desc), false);
|
|
266
|
+
const tag = Object.keys(o).find((k) => k.startsWith('$'));
|
|
267
|
+
switch (tag) {
|
|
268
|
+
case '$u':
|
|
269
|
+
case '$hole': return undefined;
|
|
270
|
+
case '$n': return Number(o.$n);
|
|
271
|
+
case '$big': return BigInt(text(o.$big));
|
|
272
|
+
case '$date': return o.$date === 'Invalid' ? new Date(NaN) : new Date(text(o.$date));
|
|
273
|
+
case '$re': return new RegExp(text(o.$re), text(o.flags));
|
|
274
|
+
case '$map': return decodeMap(o.$map, path, refs);
|
|
275
|
+
case '$set': return decodeSet(o.$set, path, refs);
|
|
276
|
+
case '$bytes': return decodeBytes(text(o.$bytes), text(o.type));
|
|
277
|
+
case '$err': return decodeError(text(o.$err), text(o.message));
|
|
278
|
+
case '$fn': return namedStub(text(o.$fn));
|
|
279
|
+
case '$sym': return Symbol(text(o.$sym));
|
|
280
|
+
case '$ref': return refs.get(text(o.$ref));
|
|
281
|
+
case '$boxed': return Object(decodeAt(o.$boxed ?? null, path, refs));
|
|
282
|
+
case '$opaque': return {};
|
|
283
|
+
default: return decodePlain(o, path, refs);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function asDesc(e) {
|
|
287
|
+
if (e === null || typeof e !== 'object' || Array.isArray(e))
|
|
288
|
+
return {};
|
|
289
|
+
const out = {};
|
|
290
|
+
for (const key of Object.keys(e)) {
|
|
291
|
+
const entry = e[key];
|
|
292
|
+
if (entry !== null && typeof entry === 'object' && !Array.isArray(entry))
|
|
293
|
+
defineOwn(out, key, entry);
|
|
294
|
+
}
|
|
295
|
+
return out;
|
|
296
|
+
}
|
|
297
|
+
function decodePlain(o, path, refs, desc = {}, nullProto = false) {
|
|
298
|
+
const out = nullProto ? Object.create(null) : {};
|
|
299
|
+
refs.set(path, out);
|
|
300
|
+
for (const key of Object.keys(o)) {
|
|
301
|
+
const val = decodeAt(o[key], propPath(path, key), refs);
|
|
302
|
+
const d = Object.hasOwn(desc, key) ? desc[key] : undefined;
|
|
303
|
+
if (d !== undefined && ('get' in d || 'set' in d)) {
|
|
304
|
+
Object.defineProperty(out, key, {
|
|
305
|
+
enumerable: Boolean(d.e),
|
|
306
|
+
configurable: Boolean(d.c),
|
|
307
|
+
get: d.get ? () => val : undefined,
|
|
308
|
+
set: d.set ? () => { } : undefined,
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
else if (d !== undefined) {
|
|
312
|
+
Object.defineProperty(out, key, {
|
|
313
|
+
value: val,
|
|
314
|
+
writable: Boolean(d.w),
|
|
315
|
+
enumerable: Boolean(d.e),
|
|
316
|
+
configurable: Boolean(d.c),
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
else {
|
|
320
|
+
// defineProperty so a "__proto__" key stays an own property instead of setting the prototype
|
|
321
|
+
defineOwn(out, key, val);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
return out;
|
|
325
|
+
}
|
|
326
|
+
function decodeMap(entries, path, refs) {
|
|
327
|
+
const out = new Map();
|
|
328
|
+
refs.set(path, out);
|
|
329
|
+
asArray(entries).forEach((entry, i) => {
|
|
330
|
+
const [k = null, v = null] = asArray(entry);
|
|
331
|
+
out.set(decodeAt(k, mapKeyPath(path, i), refs), decodeAt(v, mapValuePath(path, i), refs));
|
|
332
|
+
});
|
|
333
|
+
return out;
|
|
334
|
+
}
|
|
335
|
+
function decodeSet(items, path, refs) {
|
|
336
|
+
const out = new Set();
|
|
337
|
+
refs.set(path, out);
|
|
338
|
+
asArray(items).forEach((item, i) => out.add(decodeAt(item, setItemPath(path, i), refs)));
|
|
339
|
+
return out;
|
|
340
|
+
}
|
|
341
|
+
function decodeBytes(base64, type) {
|
|
342
|
+
const buf = Buffer.from(base64, 'base64');
|
|
343
|
+
if (type === 'Buffer')
|
|
344
|
+
return buf;
|
|
345
|
+
const bytes = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
346
|
+
if (type === 'ArrayBuffer')
|
|
347
|
+
return bytes;
|
|
348
|
+
if (type === 'DataView')
|
|
349
|
+
return new DataView(bytes);
|
|
350
|
+
const ctor = globalThis[type];
|
|
351
|
+
if (typeof ctor === 'function' && Object.getPrototypeOf(ctor.prototype) === TYPED_ARRAY_PROTO) {
|
|
352
|
+
return new ctor(bytes);
|
|
353
|
+
}
|
|
354
|
+
return new Uint8Array(bytes);
|
|
355
|
+
}
|
|
356
|
+
function decodeError(name, message) {
|
|
357
|
+
const Ctor = Object.hasOwn(ERROR_CTORS, name) ? ERROR_CTORS[name] : Error;
|
|
358
|
+
const error = new Ctor(message);
|
|
359
|
+
if (error.name !== name)
|
|
360
|
+
error.name = name;
|
|
361
|
+
return error;
|
|
362
|
+
}
|
|
363
|
+
function namedStub(name) {
|
|
364
|
+
return Object.defineProperty(() => undefined, 'name', { value: name });
|
|
365
|
+
}
|
|
366
|
+
function text(e) {
|
|
367
|
+
return typeof e === 'string' ? e : String(e ?? '');
|
|
368
|
+
}
|
|
369
|
+
function asArray(e) {
|
|
370
|
+
return Array.isArray(e) ? e : [];
|
|
371
|
+
}
|
|
372
|
+
function asObject(e) {
|
|
373
|
+
return e !== null && typeof e === 'object' && !Array.isArray(e) ? e : {};
|
|
374
|
+
}
|
|
375
|
+
// ---------- comparison ----------
|
|
376
|
+
/** Structural equality; object keys compare order-insensitively, arrays in order. */
|
|
377
|
+
export function equalEncoded(a, b) {
|
|
378
|
+
if (a === b)
|
|
379
|
+
return true;
|
|
380
|
+
if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object')
|
|
381
|
+
return false;
|
|
382
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
383
|
+
return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => equalEncoded(x, b[i]));
|
|
384
|
+
}
|
|
385
|
+
const keys = Object.keys(a);
|
|
386
|
+
return keys.length === Object.keys(b).length && keys.every((k) => Object.hasOwn(b, k) && equalEncoded(a[k], b[k]));
|
|
387
|
+
}
|
|
388
|
+
export function outcomesEqual(a, b) {
|
|
389
|
+
switch (a.kind) {
|
|
390
|
+
case 'return':
|
|
391
|
+
return b.kind === 'return' && equalEncoded(a.value, b.value) && equalEncoded(a.argsAfter, b.argsAfter);
|
|
392
|
+
case 'throw':
|
|
393
|
+
return b.kind === 'throw' && a.name === b.name && a.message === b.message;
|
|
394
|
+
case 'unsupported':
|
|
395
|
+
return b.kind === 'unsupported' && a.reason === b.reason;
|
|
396
|
+
case 'nondeterministic':
|
|
397
|
+
return b.kind === 'nondeterministic';
|
|
398
|
+
}
|
|
399
|
+
}
|