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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -3
  3. package/data/module-replacements.LICENSE +21 -0
  4. package/data/module-replacements.json +947 -0
  5. package/dist/src/anticheat/constants.js +105 -0
  6. package/dist/src/anticheat/imports.js +419 -0
  7. package/dist/src/anticheat/tokens.js +177 -0
  8. package/dist/src/anticheat.js +189 -0
  9. package/dist/src/card/format.js +113 -0
  10. package/dist/src/card/svg.js +137 -0
  11. package/dist/src/card.js +364 -0
  12. package/dist/src/check.js +139 -0
  13. package/dist/src/cli.js +333 -0
  14. package/dist/src/gate/holdout.js +78 -0
  15. package/dist/src/gate/process.js +78 -0
  16. package/dist/src/gate.js +532 -0
  17. package/dist/src/graph.js +148 -0
  18. package/dist/src/holdout/perturb.js +108 -0
  19. package/dist/src/holdout/snapshot.js +113 -0
  20. package/dist/src/init.js +76 -0
  21. package/dist/src/inputs/generate.js +282 -0
  22. package/dist/src/inputs.js +273 -0
  23. package/dist/src/measure.js +149 -0
  24. package/dist/src/project.js +72 -0
  25. package/dist/src/record.js +180 -0
  26. package/dist/src/registry.js +78 -0
  27. package/dist/src/replacement.js +146 -0
  28. package/dist/src/runner.js +227 -0
  29. package/dist/src/runtime/agent-inputs.js +36 -0
  30. package/dist/src/runtime/child.js +260 -0
  31. package/dist/src/runtime/esm-hooks.js +44 -0
  32. package/dist/src/runtime/fsguard.js +264 -0
  33. package/dist/src/runtime/inspect.js +115 -0
  34. package/dist/src/runtime/lockdown.js +157 -0
  35. package/dist/src/runtime/protocol.js +16 -0
  36. package/dist/src/scan.js +210 -0
  37. package/dist/src/serialize.js +399 -0
  38. package/dist/src/tooling.js +88 -0
  39. package/dist/src/types.js +9 -0
  40. package/dist/src/usage/common.js +36 -0
  41. package/dist/src/usage/fallback.js +227 -0
  42. package/dist/src/usage/ts.js +142 -0
  43. package/dist/src/usage.js +97 -0
  44. package/dist/src/util/exports.js +86 -0
  45. package/dist/src/util/fs.js +64 -0
  46. package/dist/src/util/term.js +61 -0
  47. package/package.json +54 -6
  48. package/skills/AGENTS.section.md +52 -0
  49. package/skills/depkill/SKILL.md +148 -0
@@ -0,0 +1,86 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { basename, dirname, join } from 'node:path';
3
+ /** Conditions Node's ESM loader matches for `import` (plus `default`). */
4
+ export const IMPORT_CONDITIONS = new Set(['node', 'import', 'default']);
5
+ /** Conditions for locating type declarations. */
6
+ export const TYPES_CONDITIONS = new Set(['types', 'typings']);
7
+ /** `exports` sugar (a string, array, or conditions object) means the `"."` entry only. */
8
+ function normalize(field) {
9
+ if (typeof field === 'string' || Array.isArray(field))
10
+ return { '.': field };
11
+ if (field === null || typeof field !== 'object')
12
+ return null;
13
+ const keys = Object.keys(field);
14
+ return keys.some((key) => key.startsWith('.')) ? field : { '.': field };
15
+ }
16
+ /** A package-relative target (`./x.js`) without `..` or `node_modules` segments, else null. */
17
+ function safeTarget(target, match) {
18
+ if (!target.startsWith('./'))
19
+ return null;
20
+ const resolved = match === null ? target : target.replaceAll('*', match);
21
+ const segments = resolved.split(/[\\/]/);
22
+ return segments.includes('..') || segments.includes('node_modules') ? null : resolved;
23
+ }
24
+ function resolveTarget(target, conditions, match) {
25
+ if (typeof target === 'string')
26
+ return safeTarget(target, match);
27
+ if (Array.isArray(target)) {
28
+ for (const candidate of target) {
29
+ const resolved = resolveTarget(candidate, conditions, match);
30
+ if (resolved !== null)
31
+ return resolved;
32
+ }
33
+ return null;
34
+ }
35
+ if (target !== null && typeof target === 'object') {
36
+ // Object key order decides, as in Node: the first matching condition wins.
37
+ for (const [condition, value] of Object.entries(target)) {
38
+ if (!conditions.has(condition))
39
+ continue;
40
+ const resolved = resolveTarget(value, conditions, match);
41
+ if (resolved !== null)
42
+ return resolved;
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+ /**
48
+ * Package-relative target (`./dist/x.mjs`) of `key` (`"."` or `"./sub"`) in a package.json `exports` field
49
+ * under `conditions`, or null when not exported. Supports exact keys and single-`*` patterns (longest prefix wins).
50
+ */
51
+ export function resolveExports(field, key, conditions) {
52
+ const map = normalize(field);
53
+ if (map === null)
54
+ return null;
55
+ if (Object.hasOwn(map, key) && !key.includes('*'))
56
+ return resolveTarget(map[key], conditions, null);
57
+ let best = null;
58
+ for (const pattern of Object.keys(map)) {
59
+ const star = pattern.indexOf('*');
60
+ if (star === -1 || star !== pattern.lastIndexOf('*'))
61
+ continue;
62
+ const prefix = pattern.slice(0, star);
63
+ const suffix = pattern.slice(star + 1);
64
+ if (key.length < pattern.length - 1 || !key.startsWith(prefix) || !key.endsWith(suffix))
65
+ continue;
66
+ if (best === null || prefix.length > best.prefix) {
67
+ best = { key: pattern, prefix: prefix.length, match: key.slice(prefix.length, key.length - suffix.length) };
68
+ }
69
+ }
70
+ return best === null ? null : resolveTarget(map[best.key], conditions, best.match);
71
+ }
72
+ /**
73
+ * Directory of installed package `name` as Node would find it from `fromDir`
74
+ * (`<ancestor>/node_modules/<name>`, skipping `node_modules` directories themselves), or null.
75
+ */
76
+ export function findPackageDir(name, fromDir) {
77
+ for (let dir = fromDir;; dir = dirname(dir)) {
78
+ if (basename(dir) !== 'node_modules') {
79
+ const candidate = join(dir, 'node_modules', ...name.split('/'));
80
+ if (existsSync(join(candidate, 'package.json')))
81
+ return candidate;
82
+ }
83
+ if (dirname(dir) === dir)
84
+ return null;
85
+ }
86
+ }
@@ -0,0 +1,64 @@
1
+ import { lstatSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { DepkillError } from '../types.js';
4
+ const STATE_DIR_NAME = '.depkill';
5
+ // Uppercase letters are allowed: legacy npm names such as `JSONStream` still exist.
6
+ const PACKAGE_NAME = /^(@[A-Za-z0-9-~][A-Za-z0-9-._~]*\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*$/;
7
+ function isValidPackageName(name) {
8
+ return name !== '.' && name !== '..' && !name.includes('\\')
9
+ && !name.split('/').includes('..') && PACKAGE_NAME.test(name);
10
+ }
11
+ /**
12
+ * Filesystem-safe package name: `@scope/name` -> `@scope__name`.
13
+ * Throws DepkillError (exit 2) for anything that is not a valid npm name, so it cannot escape `.depkill/`.
14
+ */
15
+ export function pkgSafe(name) {
16
+ if (!isValidPackageName(name))
17
+ throw new DepkillError(`Invalid package name: ${JSON.stringify(name)}`);
18
+ return name.replaceAll('/', '__');
19
+ }
20
+ /** `<root>/.depkill`, or `<root>/.depkill/<pkg-safe>` when a package is given. */
21
+ export function stateDir(root, pkg) {
22
+ return pkg === undefined ? join(root, STATE_DIR_NAME) : join(root, STATE_DIR_NAME, pkgSafe(pkg));
23
+ }
24
+ export function readJson(p) {
25
+ const text = readFileSync(p, 'utf8').replace(/^\uFEFF/, '');
26
+ try {
27
+ return JSON.parse(text);
28
+ }
29
+ catch (error) {
30
+ const reason = error instanceof Error ? error.message : String(error);
31
+ throw new Error(`Invalid JSON in ${p}: ${reason}`, { cause: error });
32
+ }
33
+ }
34
+ /** Writes 2-space indented JSON with a trailing newline, creating parent directories. */
35
+ export function writeJson(p, v) {
36
+ mkdirSync(dirname(p), { recursive: true });
37
+ writeFileSync(p, `${JSON.stringify(v, null, 2)}\n`);
38
+ }
39
+ /**
40
+ * Total size in bytes of regular files under `dir`, recursively.
41
+ * Symlinks are not followed; entries whose name matches `skip` are ignored.
42
+ * A missing directory has size 0.
43
+ */
44
+ export function dirSize(dir, skip = () => false) {
45
+ let entries;
46
+ try {
47
+ entries = readdirSync(dir, { withFileTypes: true });
48
+ }
49
+ catch (error) {
50
+ if (error.code === 'ENOENT')
51
+ return 0;
52
+ throw error;
53
+ }
54
+ return entries
55
+ .filter((entry) => !skip(entry.name))
56
+ .reduce((total, entry) => {
57
+ const full = join(dir, entry.name);
58
+ if (entry.isDirectory())
59
+ return total + dirSize(full, skip);
60
+ if (entry.isFile())
61
+ return total + lstatSync(full).size;
62
+ return total;
63
+ }, 0);
64
+ }
@@ -0,0 +1,61 @@
1
+ /** Terminal helpers: color decisions, ANSI styling, byte formatting and plain-text tables. */
2
+ const ANSI = /\u001b\[[0-9;]*m/g;
3
+ const STYLES = { bold: [1, 22], dim: [2, 22], red: [31, 39], green: [32, 39], yellow: [33, 39], cyan: [36, 39] };
4
+ /** Color only when writing to a TTY and `NO_COLOR` is not set (any value disables it). */
5
+ export function colorEnabled(stream = process.stdout) {
6
+ return stream.isTTY === true && process.env.NO_COLOR === undefined;
7
+ }
8
+ /** Terminal width for layout: the TTY's columns, else `fallback`. */
9
+ export function terminalWidth(fallback = 100) {
10
+ const columns = process.stdout.isTTY ? process.stdout.columns : undefined;
11
+ return typeof columns === 'number' && columns > 0 ? columns : fallback;
12
+ }
13
+ /** Wraps `text` in an ANSI style when `enabled`. */
14
+ export function paint(style, text, enabled) {
15
+ if (!enabled)
16
+ return text;
17
+ const [open, close] = STYLES[style];
18
+ return `\u001b[${open}m${text}\u001b[${close}m`;
19
+ }
20
+ export function stripAnsi(text) {
21
+ return text.replace(ANSI, '');
22
+ }
23
+ /** Display width ignoring ANSI escapes (one column per code point). */
24
+ export function visibleWidth(text) {
25
+ return [...stripAnsi(text)].length;
26
+ }
27
+ /** Cuts plain `text` to at most `max` columns, marking the cut with `…`. */
28
+ export function truncate(text, max) {
29
+ const chars = [...text];
30
+ if (chars.length <= max)
31
+ return text;
32
+ return max <= 1 ? chars.slice(0, max).join('') : `${chars.slice(0, max - 1).join('')}…`;
33
+ }
34
+ /** `999 B`, `2.0 KB`, `5.0 MB`, `1.2 GB` (1024-based). */
35
+ export function formatBytes(bytes) {
36
+ if (bytes < 1024)
37
+ return `${bytes} B`;
38
+ const units = ['KB', 'MB', 'GB', 'TB'];
39
+ let value = bytes / 1024;
40
+ let unit = 0;
41
+ while (value >= 1024 && unit < units.length - 1) {
42
+ value /= 1024;
43
+ unit += 1;
44
+ }
45
+ return `${value.toFixed(1)} ${units[unit]}`;
46
+ }
47
+ /**
48
+ * Lays out `rows` under `columns`, two spaces between columns, no trailing spaces.
49
+ * Cells may contain ANSI styling; widths are measured on visible text.
50
+ */
51
+ export function renderTable(columns, rows) {
52
+ const widths = columns.map((col, i) => Math.max(visibleWidth(col.header), ...rows.map((row) => visibleWidth(row[i] ?? ''))));
53
+ const line = (cells) => cells
54
+ .map((cell, i) => {
55
+ const pad = ' '.repeat(widths[i] - visibleWidth(cell));
56
+ return columns[i].align === 'right' ? pad + cell : cell + pad;
57
+ })
58
+ .join(' ')
59
+ .trimEnd();
60
+ return [line(columns.map((col) => col.header)), ...rows.map(line)];
61
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
- {
2
- "name": "depkill",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "depkill",
3
+ "version": "0.1.0",
4
+ "description": "Delete your dependencies. Prove nothing broke. Record how an npm package behaves, replay it against your local replacement, gate the removal.",
5
+ "keywords": [
6
+ "dependencies",
7
+ "npm",
8
+ "supply-chain",
9
+ "security",
10
+ "node_modules",
11
+ "cli",
12
+ "ai-agents",
13
+ "claude-code",
14
+ "agents-md",
15
+ "e18e",
16
+ "debloat"
17
+ ],
18
+ "homepage": "https://github.com/feritcemkahraman/depkill#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/feritcemkahraman/depkill/issues"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/feritcemkahraman/depkill.git"
25
+ },
26
+ "type": "module",
27
+ "bin": {
28
+ "depkill": "dist/src/cli.js"
29
+ },
30
+ "files": [
31
+ "dist/src",
32
+ "skills",
33
+ "data",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "engines": {
38
+ "node": ">=20"
39
+ },
40
+ "scripts": {
41
+ "build": "tsc -p .",
42
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
43
+ "test": "tsc -p . && node scripts/run-tests.mjs",
44
+ "prepack": "npm run clean && npm run build",
45
+ "prepublishOnly": "npm test"
46
+ },
47
+ "author": "Ferit Cem (https://github.com/feritcemkahraman)",
48
+ "license": "MIT",
49
+ "dependencies": {},
50
+ "devDependencies": {
51
+ "@types/node": "^20",
52
+ "typescript": "^5"
53
+ }
54
+ }
@@ -0,0 +1,52 @@
1
+ ## Removing npm dependencies (depkill)
2
+
3
+ When asked to remove, replace, inline or kill a dependency, use depkill and follow this loop. A dependency is
4
+ removed only when `npx depkill gate <pkg>` passes. `<pkg-safe>` = package name with `/` replaced by `__`.
5
+
6
+ 1. `npx depkill scan`: take the top `candidate` that is a plain utility function (or the package the user named). Skip
7
+ packages whose exports return functions or objects with behavior (middleware factories, plugins, clients) and
8
+ never pick `unsupported`. `unused` packages are simply uninstalled (if uninstalled after the first `depkill record`,
9
+ the card names them as removals without a gate). Prefer a platform API listed under `Alternatives`.
10
+ 2. `npx depkill record <pkg>` (package still installed). Read the call sites and `.depkill/<pkg-safe>/cases.jsonl`.
11
+ If cases are thin or record says `no inputs for <id>`, write realistic argument lists to
12
+ `.depkill/<pkg-safe>/inputs.mjs` and record again:
13
+ `export default { '#default': [['5', 3, '0']], '#name': [['foo-bar']], '/sub#default': [[{ a: 1 }, 'a']] };`
14
+ (export ids: `#default`, `#name`, `/sub#name`; the used ones are in `.depkill/<pkg-safe>/meta.json`).
15
+ Record before rewiring imports (or restore them first): record reads the current imports.
16
+ 3. Write the smallest self-contained replacement in `src/vendor/<pkg-safe>.ts` (`.js` in JS projects; in a project
17
+ whose code lives elsewhere, such as `lib/`, put it in `lib/vendor/` so it ships with the code that imports it) and
18
+ set `.depkill/<pkg-safe>/config.json` to `{ "replacement": "src/vendor/<pkg-safe>.ts" }` (add
19
+ `"subpaths": { "/sub": "<file>" }` for `pkg/sub` imports). Exports are looked up strictly. ESM (`.ts`, `.mts`,
20
+ `.mjs`, or `.js` with `"type": "module"`): `export default function f() {}` serves `#default`,
21
+ `export function name() {}` serves `#name`. CommonJS (`.cjs`, or `.js` without `"type": "module"`):
22
+ `module.exports = function f() {}` serves `#default`; `module.exports = { padLeft, padRight }` (shorthand or
23
+ `key: identifier` entries only) or `exports.name = ...` serves `#name`. In a `.cts` file write
24
+ `module.exports = ...`, not `export default` (or simply use `.js`/`.ts`). Prefer platform APIs.
25
+ 4. `npx depkill check <pkg>` until every real (`callsite`/`agent`) case passes; zero comparable cases is a failure.
26
+ Outcomes compare return values, thrown errors and argument mutations, including non-enumerable string properties,
27
+ property descriptors (`writable`, `enumerable`, `configurable`, getters/setters) and null prototypes.
28
+ Fix mismatching `generated` cases, or list one in `.depkill/<pkg-safe>/accepted.json` as
29
+ `[{ "caseId": "<generated case id>", "reason": "<honest, specific reason>" }]` only when the input is
30
+ impossible in this codebase (at most 10% of the compared generated cases).
31
+ 5. Rewire every import of `<pkg>` to the replacement (keep each file's `require` or `import` style), uninstall it
32
+ with the project's package manager, then
33
+ `npx depkill gate <pkg>` until it passes (checks: cases-real, cases-generated, holdout, removed, no-new-deps,
34
+ no-imports-left, wired, ships, self-contained, not-copied, no-embedded-outputs, typecheck, tests). If `holdout` fails, make
35
+ the replacement correct in general; never special-case those inputs. Use `--skip-tests` only when the user
36
+ explicitly asks, never to get past a failing test (the card discloses skipped tests or holdout).
37
+ 6. Repeat if asked; finish with `npx depkill card` (needs at least one passed gate) and show the user
38
+ `.depkill/card.svg` and `.depkill/report.md`. If the project's linter or test runner scans dot-folders (e.g.
39
+ ESLint flat config), add `.depkill/` to its ignores.
40
+
41
+ Hard rules for replacements: never copy the package source; never import the package, other packages or relative
42
+ files; never read or mention `.depkill/` or `node_modules`; never hardcode recorded outputs; import only these
43
+ Node builtins: assert, assert/strict, buffer, crypto, events, fs, fs/promises, os, path, path/posix, path/win32,
44
+ punycode, querystring, stream, stream/promises, stream/web, string_decoder, timers, timers/promises, url, util,
45
+ util/types, zlib (no `node:process` import, no `eval`/`new Function`, no network). Also avoid: `process` /
46
+ `globalThis` / `global` / `module` used as values, `.constructor` outside comparisons, the strings `'constructor'`,
47
+ `'require'`, `'Function'`, `'eval'`, and module-level `arguments` (all fail `self-contained`). Without
48
+ TypeScript in the project (or when it cannot parse the file) the scan is stricter: any `arguments`, a bare
49
+ `constructor`, and the words `require`, `eval` and `Function` are flagged even in comments and strings. Never edit
50
+ `.depkill/baseline/`, `cases.jsonl` or other depkill state; change evidence only through `inputs.mjs` + record.
51
+ Never add dependencies or weaken tests to pass the gate. If a package cannot be replaced honestly, restore it and
52
+ tell the user why.
@@ -0,0 +1,148 @@
1
+ ---
2
+ name: depkill
3
+ description: Remove an npm dependency by rewriting it locally and proving behavior is unchanged. Use when asked to remove, replace, inline or kill a dependency, or reduce node_modules / supply-chain surface.
4
+ ---
5
+
6
+ # depkill: remove a dependency, prove nothing broke
7
+
8
+ depkill records how an npm package behaves in this project, replays those cases against your local
9
+ replacement, and gates the removal. You write the replacement; depkill decides whether the removal passes.
10
+ A dependency is removed only when `npx depkill gate <pkg>` passes. Never claim success before that.
11
+
12
+ `<pkg-safe>` below is the package name with `/` replaced by `__` (`@scope/name` -> `@scope__name`).
13
+ All depkill state lives in `.depkill/` at the project root.
14
+
15
+ ## The loop
16
+
17
+ 1. **Pick a package.** Run `npx depkill scan` (add `--offline` to skip registry lookups).
18
+ - Take the top `candidate` that is a plain utility function, or the package the user named. Skip packages
19
+ whose exports return functions or objects with behavior (middleware factories, plugins, clients): record
20
+ marks those cases unsupported and warns that the export cannot be proven.
21
+ - `unused` means no source file imports it: uninstall it and run the project's tests, because some packages
22
+ are loaded by name at runtime (view engines, plugins, presets); reinstall it if they fail. No proof is
23
+ involved; if it is uninstalled after the first `depkill record`, `card` names it as a removal without a gate.
24
+ - Never pick `unsupported` (native module, too large, more than 8 used exports, tooling/CLI/types-only use).
25
+ - The scan's `Alternatives (module-replacements)` list names a platform API or lighter option when one
26
+ exists: prefer it.
27
+
28
+ 2. **Record.** `npx depkill record <pkg>` (the package must still be installed).
29
+ - Read the call sites and `.depkill/<pkg-safe>/cases.jsonl`: one case per line,
30
+ `{ "id", "exportId", "source": "callsite" | "agent" | "generated", "args", "outcome" }`.
31
+ - Export ids: `#default` (default export or the CommonJS `module.exports` function), `#name` (named export or
32
+ member), `/sub#default` / `/sub#name` (subpath imports such as `pkg/sub`). The used ids are in
33
+ `.depkill/<pkg-safe>/meta.json` (`exportIds`).
34
+ - Call-site and type-generated inputs need the project's own `typescript`. Without it, or when the record
35
+ output says `no inputs for <id>` or the cases do not cover how the code really calls the package, write
36
+ realistic inputs to `.depkill/<pkg-safe>/inputs.mjs` and run `npx depkill record <pkg>` again:
37
+
38
+ ```js
39
+ // .depkill/<pkg-safe>/inputs.mjs: each export id maps to a list of argument lists
40
+ export default {
41
+ '#default': [['5', 3, '0'], ['abc', 6]],
42
+ '#camelCase': [['foo-bar'], ['Foo Bar'], ['']],
43
+ '/get#default': [[{ a: { b: 1 } }, 'a.b']],
44
+ };
45
+ ```
46
+
47
+ Use the values the project actually passes (read the call sites), plus their edge cases. These become
48
+ `agent` cases, which count as real usage.
49
+ - Re-record before you rewire the imports (or restore them first): `record` takes the export ids and call-site
50
+ inputs from the imports that exist right now.
51
+
52
+ 3. **Replace.** Write the smallest self-contained replacement in `src/vendor/<pkg-safe>.ts` (or `.js` in a
53
+ JavaScript project; in a project whose code lives elsewhere, such as `lib/`, use `lib/vendor/`, so the file
54
+ ships with the code that imports it) and point depkill at it in `.depkill/<pkg-safe>/config.json`:
55
+
56
+ ```json
57
+ { "replacement": "src/vendor/<pkg-safe>.ts" }
58
+ ```
59
+
60
+ Add `"subpaths": { "/sub": "src/vendor/<pkg-safe>-sub.ts" }` when the project imports `pkg/sub`. Paths are
61
+ relative to the project root and must be project files (not under `node_modules` or `.depkill`).
62
+ - Export what the ids need, in the module system of the replacement file. Exports are looked up strictly.
63
+ ESM (`.ts`, `.mts`, `.mjs`, or `.js` in a project with `"type": "module"`): `export default` serves
64
+ `#default`, a named export serves each `#name`:
65
+
66
+ ```ts
67
+ export default function padLeft(value: string, width: number, fill = ' '): string { /* ... */ }
68
+ export function camelCase(text: string): string { /* ... */ }
69
+ ```
70
+
71
+ CommonJS (`.cjs`, or `.js` in a project without `"type": "module"`): `module.exports = fn` serves `#default`;
72
+ `module.exports = { name, other }` (shorthand or `key: identifier` entries only, e.g.
73
+ `module.exports = { padLeft, padRight }`) or `exports.name = ...` serves each `#name`:
74
+
75
+ ```js
76
+ module.exports = function padLeft(value, width, fill) { /* ... */ }; // #default
77
+ // or, for named ids:
78
+ module.exports = { camelCase, kebabCase }; // #camelCase, #kebabCase
79
+ ```
80
+
81
+ A `.cts` file is CommonJS too: write `module.exports = ...` there, not `export default` (or simply use
82
+ `.js` / `.ts`).
83
+ - One file per entry point; it may import only these Node builtins (with or without `node:`): assert,
84
+ assert/strict, buffer, crypto, events, fs, fs/promises, os, path, path/posix, path/win32, punycode,
85
+ querystring, stream, stream/promises, stream/web, string_decoder, timers, timers/promises, url, util,
86
+ util/types, zlib. No relative imports, no other packages, no `node:process` import (use the global
87
+ `process.x` directly), no `fetch`/network.
88
+ - Prefer platform APIs (`String.prototype.padStart`, `structuredClone`, `Array.prototype.flat`, ...).
89
+
90
+ 4. **Check.** `npx depkill check <pkg>` and fix the replacement until every real case (`callsite`, `agent`)
91
+ matches. It prints each failing case with args, expected and actual outcome (full list in
92
+ `.depkill/<pkg-safe>/check.json`). Outcomes compare return values, thrown error name + message, and argument
93
+ mutations, including own non-enumerable string properties, property descriptors (`writable`, `enumerable`,
94
+ `configurable`, getter/setter presence and read value), and null prototypes. Symbol properties and class prototype
95
+ chains are not compared.
96
+ `No comparable cases — nothing was proven` is a failure: add inputs (step 2).
97
+ - Mismatching `generated` cases: fix them. Only when an input is impossible in this codebase (for example a
98
+ type the code never passes) may you accept it, in `.depkill/<pkg-safe>/accepted.json`:
99
+
100
+ ```json
101
+ [{ "caseId": "generated-#default-17", "reason": "pad length is always a positive literal in this project" }]
102
+ ```
103
+
104
+ Only `generated` case ids, each with an honest, specific reason. Accepted mismatches may not exceed 10% of
105
+ the compared generated cases, and the card shows how many were accepted.
106
+
107
+ 5. **Remove.** Rewire every import and require of `<pkg>` (including `pkg/sub`) to your replacement, using the
108
+ module system the importing file already uses (`require('<pkg>')` becomes `require('./vendor/<pkg-safe>.js')`,
109
+ `import x from '<pkg>'` becomes `import x from './vendor/<pkg-safe>.js'`), uninstall
110
+ it with the project's package manager (`npm uninstall <pkg>`, `pnpm remove <pkg>`, `yarn remove <pkg>`), then
111
+ run `npx depkill gate <pkg>` until it passes. The gate checks, in order:
112
+ `cases-real`, `cases-generated`, `holdout`, `removed`, `no-new-deps`, `no-imports-left`, `wired`, `ships`,
113
+ `self-contained`, `not-copied`, `no-embedded-outputs`, `typecheck`, `tests` (typecheck and tests run once the others pass;
114
+ `--test-cmd "<cmd>"` sets the test command). Use `--skip-tests` only when the user explicitly asks for it,
115
+ never to get past a failing test; a skipped `tests` or `holdout` check is shown on the card.
116
+ - `holdout` fails: depkill ran fresh inputs near the real usage against the original package and your
117
+ replacement and they differed. Fix the replacement so it is correct in general. Never special-case those
118
+ inputs; a different replacement gets a different holdout set.
119
+ - `cases-real` says there is no real-usage evidence: add `inputs.mjs` (step 2). Recording needs the package
120
+ installed and reads the current imports, so reinstall it and restore its imports, record, then rewire and
121
+ uninstall again.
122
+
123
+ 6. **Report.** Repeat for the next candidate if the user asked for more. Finish with `npx depkill card` (it needs
124
+ at least one package whose gate passed) and show the user `.depkill/card.svg` and `.depkill/report.md` (it also
125
+ writes `.depkill/badge.svg`). If the project's linter or test runner scans dot-folders (for example ESLint flat
126
+ config), add `.depkill/` to its ignores.
127
+
128
+ ## Hard rules
129
+
130
+ - Never copy the package source (the `not-copied` check compares your code with the recorded original, also with
131
+ local names normalized). Write your own implementation.
132
+ - Never import or require the package, any other package, or relative files from the replacement.
133
+ - Never read `.depkill/` or `node_modules` from the replacement (the strings themselves fail the gate).
134
+ - Never hardcode recorded outputs or build a lookup table of them; compute the result.
135
+ - Only the allowed Node builtins above; no `eval`, `new Function`, computed access on `globalThis` / `process` /
136
+ `module` / `require`, or long encoded blobs.
137
+ - These also fail `self-contained`, so avoid them even in honest code: `process`, `globalThis`, `global` or
138
+ `module` used as a value (write `process.env.X`, not `const p = process`), `.constructor` outside a comparison,
139
+ the strings `'constructor'`, `'require'`, `'Function'`, `'eval'` (also in destructuring), and `arguments` at
140
+ module level.
141
+ - Without TypeScript in the project (or when it cannot parse the file) the scan is stricter: any `arguments`, a
142
+ bare `constructor`, and the words `require`, `eval` and `Function` are flagged even in comments and strings.
143
+ - Never edit `.depkill/baseline/`, `cases.jsonl`, `meta.json`, `original/`, `runtime/` or `gate.json`. Change
144
+ evidence only by changing `inputs.mjs` and re-recording.
145
+ - Do not add dependencies; do not weaken the project's tests or typecheck to make the gate pass, and do not use
146
+ `--skip-tests` unless the user asked for it.
147
+ - If a package cannot be replaced honestly (the gate keeps failing for a real behavior you cannot reproduce),
148
+ stop, restore it, and tell the user why.