codemod 2.0.0-alpha.1 → 2.0.0-alpha.3

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 (102) hide show
  1. package/README.md +56 -2
  2. package/codemod +17 -30
  3. package/package.json +80 -10
  4. package/register.d.mts +2 -0
  5. package/register.mjs +67 -0
  6. package/runtime/addon.d.mts +114 -0
  7. package/runtime/addon.mjs +55 -0
  8. package/runtime/ast-grep.d.mts +20 -0
  9. package/runtime/ast-grep.mjs +82 -0
  10. package/runtime/context.d.mts +49 -0
  11. package/runtime/context.mjs +59 -0
  12. package/runtime/hooks.d.mts +2 -0
  13. package/runtime/hooks.mjs +7 -0
  14. package/runtime/host.d.mts +121 -0
  15. package/runtime/host.mjs +450 -0
  16. package/runtime/llm.d.mts +2 -0
  17. package/runtime/llm.mjs +5 -0
  18. package/runtime/metrics.d.mts +9 -0
  19. package/runtime/metrics.mjs +42 -0
  20. package/runtime/modules.d.mts +3 -0
  21. package/runtime/modules.mjs +17 -0
  22. package/runtime/orchestrator-version.d.mts +2 -0
  23. package/runtime/orchestrator-version.mjs +3 -0
  24. package/runtime/orchestrator.d.mts +261 -0
  25. package/runtime/orchestrator.mjs +879 -0
  26. package/runtime/runtime.d.mts +15 -0
  27. package/runtime/runtime.mjs +40 -0
  28. package/runtime/workflow.d.mts +19 -0
  29. package/runtime/workflow.mjs +126 -0
  30. package/testing/index.d.mts +157 -0
  31. package/testing/index.mjs +648 -0
  32. package/types/index.d.ts +8 -0
  33. package/types/langs/angular.d.ts +5 -0
  34. package/types/langs/c.d.ts +5 -0
  35. package/types/langs/c_sharp.d.ts +5 -0
  36. package/types/langs/cpp.d.ts +5 -0
  37. package/types/langs/css.d.ts +5 -0
  38. package/types/langs/elixir.d.ts +5 -0
  39. package/types/langs/go.d.ts +5 -0
  40. package/types/langs/html.d.ts +5 -0
  41. package/types/langs/java.d.ts +5 -0
  42. package/types/langs/javascript.d.ts +5 -0
  43. package/types/langs/json.d.ts +5 -0
  44. package/types/langs/kotlin.d.ts +5 -0
  45. package/types/langs/package.json +3 -0
  46. package/types/langs/php.d.ts +5 -0
  47. package/types/langs/python.d.ts +5 -0
  48. package/types/langs/ruby.d.ts +5 -0
  49. package/types/langs/rust.d.ts +5 -0
  50. package/types/langs/scala.d.ts +5 -0
  51. package/types/langs/toml.d.ts +5 -0
  52. package/types/langs/tsx.d.ts +5 -0
  53. package/types/langs/typescript.d.ts +5 -0
  54. package/types/langs/xml.d.ts +5 -0
  55. package/types/langs/yaml.d.ts +5 -0
  56. package/types/llm.d.ts +6 -0
  57. package/types/llrt/abort.d.ts +69 -0
  58. package/types/llrt/assert.d.ts +39 -0
  59. package/types/llrt/async_hooks.d.ts +210 -0
  60. package/types/llrt/buffer.d.ts +1186 -0
  61. package/types/llrt/child_process.d.ts +447 -0
  62. package/types/llrt/console.d.ts +210 -0
  63. package/types/llrt/crypto.d.ts +854 -0
  64. package/types/llrt/dgram.d.ts +381 -0
  65. package/types/llrt/dns.d.ts +124 -0
  66. package/types/llrt/dom-events.d.ts +51 -0
  67. package/types/llrt/events.d.ts +245 -0
  68. package/types/llrt/exceptions.d.ts +26 -0
  69. package/types/llrt/fetch.d.ts +332 -0
  70. package/types/llrt/fs/promises.d.ts +554 -0
  71. package/types/llrt/fs.d.ts +360 -0
  72. package/types/llrt/globals.d.ts +23 -0
  73. package/types/llrt/https.d.ts +27 -0
  74. package/types/llrt/index.d.ts +33 -0
  75. package/types/llrt/module.d.ts +285 -0
  76. package/types/llrt/navigator.d.ts +9 -0
  77. package/types/llrt/net.d.ts +488 -0
  78. package/types/llrt/os.d.ts +293 -0
  79. package/types/llrt/path.d.ts +150 -0
  80. package/types/llrt/perf_hooks.d.ts +23 -0
  81. package/types/llrt/process.d.ts +502 -0
  82. package/types/llrt/stream/web.d.ts +526 -0
  83. package/types/llrt/stream.d.ts +366 -0
  84. package/types/llrt/string_decoder.d.ts +63 -0
  85. package/types/llrt/timers.d.ts +72 -0
  86. package/types/llrt/timezone.d.ts +101 -0
  87. package/types/llrt/tty.d.ts +11 -0
  88. package/types/llrt/url.d.ts +774 -0
  89. package/types/llrt/util.d.ts +240 -0
  90. package/types/llrt/zlib.d.ts +177 -0
  91. package/types/main.d.ts +5 -0
  92. package/types/metrics.d.ts +5 -0
  93. package/types/modules/ast-grep.d.ts +634 -0
  94. package/types/modules/langs.d.ts +87 -0
  95. package/types/modules/llm.d.ts +23 -0
  96. package/types/modules/metrics.d.ts +107 -0
  97. package/types/modules/runtime.d.ts +66 -0
  98. package/types/modules/workflow.d.ts +915 -0
  99. package/types/runtime.d.ts +6 -0
  100. package/types/workflow.d.ts +5 -0
  101. package/vite.d.mts +7 -0
  102. package/vite.mjs +32 -0
@@ -0,0 +1,648 @@
1
+ // `codemod/testing`: run workflows from any test runner (node:test, Vitest,
2
+ // Jest, Bun) and compare the files they leave.
3
+ //
4
+ // Each run copies its target into a temporary directory first. TypeScript
5
+ // workflows run in this process (`codemod/host`), so breakpoints, coverage
6
+ // and module mocks work in the workflow's code. With `host: "quickjs"`, or
7
+ // for YAML workflows, the run goes to the installed codemod CLI instead
8
+ // (`codemod workflow harness`), in the engine's own sandboxed runtime.
9
+ // Failures are `AssertionError`s with `actual` and `expected`, which every
10
+ // runner knows how to show.
11
+ /**
12
+ * Run workflows from any test runner and compare the files they leave.
13
+ *
14
+ * ```ts
15
+ * import { test } from "node:test";
16
+ * import { runWorkflow, fixtures, assertTree } from "codemod/testing";
17
+ *
18
+ * for (const fixture of fixtures("tests")) {
19
+ * test(fixture.name, async () => {
20
+ * const run = await runWorkflow("workflow.ts", { target: fixture.input, params: fixture.params });
21
+ * assertTree(run, fixture.expected);
22
+ * });
23
+ * }
24
+ * ```
25
+ *
26
+ * Each run copies its target into a temporary directory first, so fixtures
27
+ * are never changed. Paths are resolved against the current directory;
28
+ * pass `new URL("./workflow.ts", import.meta.url)` to resolve against the
29
+ * test file instead.
30
+ *
31
+ * TypeScript workflows run in the test's own process, so breakpoints,
32
+ * coverage and mocks work in the workflow's code. `host: "quickjs"` runs them
33
+ * with the codemod CLI instead, in the sandboxed runtime `codemod run` uses.
34
+ *
35
+ * @module
36
+ */
37
+ import { spawn } from "node:child_process";
38
+ import { AssertionError } from "node:assert";
39
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, } from "node:fs";
40
+ import { createRequire } from "node:module";
41
+ import { tmpdir } from "node:os";
42
+ import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
43
+ import { fileURLToPath } from "node:url";
44
+ const require = createRequire(import.meta.url);
45
+ // ------------------------------------------------------------ running ---
46
+ /**
47
+ * Run a workflow (a workflow file, a package directory, or the workflow
48
+ * module itself, with `options.path`) on a copy of `options.target`. Resolves for every outcome; check `run.status`, or use
49
+ * `assertTree`, which fails when the run did not succeed. Rejects when the
50
+ * workflow cannot run at all (for example it does not build), or when an
51
+ * `until` or `given` label matches no step.
52
+ */
53
+ export async function runWorkflow(workflow, options) {
54
+ if (!options || options.target === undefined) {
55
+ throw new TypeError("runWorkflow(workflow, { target }): target is required");
56
+ }
57
+ const dir = mkdtempSync(join(tmpdir(), "codemod-test-"));
58
+ try {
59
+ materialize(options.target, dir);
60
+ const before = readTree(dir);
61
+ const result = (await inProcess(workflow, options))
62
+ ? await runInProcess(workflow, options, dir)
63
+ : await harness({
64
+ workflow: toPath(workflow),
65
+ workflowName: options.workflowName,
66
+ target: dir,
67
+ params: options.params ?? {},
68
+ until: options.until,
69
+ given: options.given ?? {},
70
+ approve: options.approve ?? true,
71
+ capabilities: options.capabilities ?? [],
72
+ }, options.signal);
73
+ const files = readTree(dir);
74
+ checkLabels(result, options);
75
+ return new Run(result, dir, before, files);
76
+ }
77
+ finally {
78
+ if (!options.keep)
79
+ rmSync(dir, { recursive: true, force: true });
80
+ }
81
+ }
82
+ /** Whether this run goes to `codemod/host` rather than the CLI. */
83
+ async function inProcess(workflow, options) {
84
+ const host = options.host ?? "node";
85
+ if (host === "quickjs")
86
+ return false;
87
+ if (host !== "node")
88
+ throw new TypeError(`host must be "node" or "quickjs", not ${host}`);
89
+ if (!isPath(workflow))
90
+ return true;
91
+ const { addon } = await import("../runtime/addon.mjs");
92
+ let path;
93
+ try {
94
+ path = addon().resolveWorkflow(toPath(workflow), options.workflowName ?? null);
95
+ }
96
+ catch (error) {
97
+ // Without the addon, fall back to the CLI unless Node was asked for.
98
+ if (options.host === undefined && /native addon/.test(messageOf(error)))
99
+ return false;
100
+ throw new Error(`cannot run ${toPath(workflow)}: ${messageOf(error)}`);
101
+ }
102
+ // YAML workflows run in the engine.
103
+ return /\.m?[jt]s$/.test(path);
104
+ }
105
+ async function runInProcess(workflow, options, dir) {
106
+ const { runWorkflow: run } = await import("../runtime/host.mjs");
107
+ let report;
108
+ try {
109
+ // The host calls the module's default export with the run's input.
110
+ report = await run(isPath(workflow) ? toPath(workflow) : workflow, {
111
+ target: dir,
112
+ params: options.params ?? {},
113
+ until: options.until,
114
+ given: options.until !== undefined || options.given ? (options.given ?? {}) : undefined,
115
+ approve: options.approve ?? true,
116
+ capabilities: options.capabilities ?? [],
117
+ workflowName: options.workflowName,
118
+ path: options.path === undefined ? undefined : toPath(options.path),
119
+ signal: options.signal,
120
+ captureConsole: true,
121
+ });
122
+ }
123
+ catch (error) {
124
+ throw new Error(`cannot run ${describeWorkflow(workflow, options)}: ${messageOf(error)}`, {
125
+ cause: error,
126
+ });
127
+ }
128
+ return { ...report, steps: [...report.steps], logs: logsOf(report.events) };
129
+ }
130
+ function describeWorkflow(workflow, options) {
131
+ if (isPath(workflow))
132
+ return toPath(workflow);
133
+ return options.path === undefined ? "the workflow" : toPath(options.path);
134
+ }
135
+ function messageOf(error) {
136
+ return error instanceof Error ? error.message : String(error);
137
+ }
138
+ /** Log lines from the engine's events, with the label of the step that wrote each. */
139
+ function logsOf(events) {
140
+ const labels = new Map();
141
+ const lines = [];
142
+ for (const event of events) {
143
+ if (event.event === "step_started")
144
+ labels.set(event.position, String(event.label));
145
+ else if (event.event === "step_log") {
146
+ lines.push({ step: labels.get(event.position) ?? null, line: String(event.line) });
147
+ }
148
+ else if (event.event === "run_log")
149
+ lines.push({ step: null, line: String(event.line) });
150
+ }
151
+ return lines;
152
+ }
153
+ class Run {
154
+ status;
155
+ output;
156
+ error;
157
+ awaiting;
158
+ stoppedAt;
159
+ dir;
160
+ files;
161
+ changes;
162
+ steps;
163
+ logs;
164
+ metrics;
165
+ constructor(result, dir, before, files) {
166
+ this.status = result.status;
167
+ this.output = result.output;
168
+ this.error = result.error;
169
+ this.awaiting = result.awaiting;
170
+ this.stoppedAt = result.stoppedAt;
171
+ this.dir = dir;
172
+ this.files = Object.freeze(files);
173
+ this.changes = Object.freeze(changes(before, files));
174
+ this.steps = Object.freeze(result.steps.map((step) => Object.freeze(step)));
175
+ this.logs = Object.freeze(result.logs.map((log) => Object.freeze(log)));
176
+ this.metrics = result.metrics;
177
+ Object.defineProperty(this, "before", { value: before, enumerable: false });
178
+ }
179
+ /** Whether the run finished, or stopped at its `until` step. */
180
+ get ok() {
181
+ return this.status === "succeeded" || this.status === "stopped";
182
+ }
183
+ /** The first step with this label. Throws when there is none. */
184
+ step(label) {
185
+ const found = this.steps.find((step) => step.label === label);
186
+ if (!found) {
187
+ throw new Error(`no step is labeled ${JSON.stringify(label)}; the run's steps are: ${labels(this.steps)}`);
188
+ }
189
+ return found;
190
+ }
191
+ /** A unified diff of every file the run changed. */
192
+ diff() {
193
+ return Object.keys(this.changes)
194
+ .sort()
195
+ .map((path) => unifiedDiff(path, this.before[path] ?? "", this.changes[path] ?? ""))
196
+ .join("");
197
+ }
198
+ }
199
+ function checkLabels(result, options) {
200
+ const ran = result.steps;
201
+ if (options.until !== undefined && result.status === "succeeded") {
202
+ throw new Error(`until: no step is labeled ${JSON.stringify(options.until)}; the run's steps are: ${labels(ran)}`);
203
+ }
204
+ if (result.status !== "succeeded")
205
+ return;
206
+ const unused = Object.keys(options.given ?? {}).filter((label) => !ran.some((step) => step.given && step.label === label));
207
+ if (unused.length) {
208
+ throw new Error(`given: no step is labeled ${unused.map((l) => JSON.stringify(l)).join(", ")}; the run's steps are: ${labels(ran)}`);
209
+ }
210
+ }
211
+ function labels(steps) {
212
+ return steps.length ? steps.map((step) => JSON.stringify(step.label)).join(", ") : "(none)";
213
+ }
214
+ function harness(spec, signal) {
215
+ const binary = codemodBinary();
216
+ return new Promise((resolvePromise, reject) => {
217
+ const child = spawn(binary, ["workflow", "harness"], {
218
+ stdio: ["pipe", "pipe", "pipe"],
219
+ env: { ...process.env, NO_COLOR: "1", DISABLE_ANALYTICS: "true" },
220
+ // Stopping a process takes a real signal.
221
+ signal: signal,
222
+ });
223
+ let stdout = "";
224
+ let stderr = "";
225
+ child.stdout.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
226
+ child.stderr.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
227
+ child.on("error", (error) => {
228
+ // Aborting stops the CLI; the run then ended as canceled, as it does
229
+ // when Node.js runs the workflow.
230
+ if (signal?.aborted) {
231
+ resolvePromise({
232
+ status: "canceled",
233
+ output: null,
234
+ error: null,
235
+ awaiting: null,
236
+ stoppedAt: null,
237
+ steps: [],
238
+ logs: [],
239
+ metrics: {},
240
+ });
241
+ }
242
+ else {
243
+ reject(error);
244
+ }
245
+ });
246
+ child.on("close", (code) => {
247
+ const line = stdout.trim().split("\n").pop();
248
+ if (code === 0 && line) {
249
+ try {
250
+ resolvePromise(JSON.parse(line));
251
+ return;
252
+ }
253
+ catch {
254
+ // fall through to the error below
255
+ }
256
+ }
257
+ const detail = (stderr.trim() || stdout.trim() || `exit code ${code}`).replace(/^Error:\s*/, "");
258
+ reject(new Error(`cannot run ${spec.workflow}: ${detail}`));
259
+ });
260
+ child.stdin.end(JSON.stringify(spec));
261
+ });
262
+ }
263
+ let binaryPath;
264
+ /** The codemod CLI binary: `CODEMOD_BINARY`, or the one this package installed. */
265
+ function codemodBinary() {
266
+ if (process.env.CODEMOD_BINARY)
267
+ return process.env.CODEMOD_BINARY;
268
+ if (binaryPath)
269
+ return binaryPath;
270
+ const { findBinaryPath } = require("../codemod");
271
+ const found = findBinaryPath();
272
+ if (!found.binaryPath) {
273
+ throw new Error(`cannot find the codemod binary${found.pkgName ? ` (expected the ${found.pkgName} package)` : ""}; reinstall codemod with optional dependencies, or set CODEMOD_BINARY`);
274
+ }
275
+ binaryPath = found.binaryPath;
276
+ return binaryPath;
277
+ }
278
+ // ------------------------------------------------------------ fixtures ---
279
+ /**
280
+ * The fixtures in a directory: each subdirectory with `input/` and
281
+ * `expected/` directories, or `input.<ext>` and `expected.<ext>` files (the
282
+ * layouts `codemod jssg test` reads), and optionally `params.json`. Groups of
283
+ * fixtures may be nested.
284
+ */
285
+ export function fixtures(dir) {
286
+ const root = toPath(dir);
287
+ if (!existsSync(root) || !statSync(root).isDirectory()) {
288
+ throw new Error(`no fixtures directory at ${root}`);
289
+ }
290
+ const found = [];
291
+ // The fixtures directory may itself hold `input/` and `expected/`.
292
+ if (isDir(join(root, "input"))) {
293
+ found.push(fixture(basename(root), root, join(root, "input"), join(root, "expected"), readParams(root)));
294
+ }
295
+ collect(root, root, found);
296
+ return found;
297
+ }
298
+ function isDir(path) {
299
+ return existsSync(path) && statSync(path).isDirectory();
300
+ }
301
+ function collect(root, dir, found) {
302
+ // A fixture's own input/ and expected/ are not fixtures.
303
+ const own = new Set(isDir(join(dir, "input")) ? ["input", "expected"] : []);
304
+ const subdirs = readdirSync(dir, { withFileTypes: true })
305
+ .filter((entry) => entry.isDirectory() && !own.has(entry.name))
306
+ .map((entry) => join(dir, entry.name))
307
+ .sort();
308
+ for (const sub of subdirs) {
309
+ const name = relative(root, sub).split(sep).join("/");
310
+ const params = readParams(sub);
311
+ if (isDir(join(sub, "input"))) {
312
+ found.push(fixture(name, sub, join(sub, "input"), join(sub, "expected"), params));
313
+ continue;
314
+ }
315
+ const [inputFile, ...more] = readdirSync(sub).filter((file) => basename(file, extname(file)) === "input" && statSync(join(sub, file)).isFile());
316
+ if (more.length) {
317
+ throw new Error(`${sub} has more than one input file; use input/ and expected/ directories instead`);
318
+ }
319
+ if (inputFile !== undefined) {
320
+ const input = join(sub, inputFile);
321
+ found.push(fixture(name, sub, input, join(sub, `expected${extname(input)}`), params));
322
+ continue;
323
+ }
324
+ collect(root, sub, found);
325
+ }
326
+ }
327
+ function fixture(name, dir, input, expected, params) {
328
+ return Object.freeze({ name, dir, input, expected, params });
329
+ }
330
+ function readParams(dir) {
331
+ const path = join(dir, "params.json");
332
+ if (!existsSync(path))
333
+ return {};
334
+ const params = JSON.parse(readFileSync(path, "utf8"));
335
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
336
+ throw new Error(`${path} must hold a JSON object`);
337
+ }
338
+ return params;
339
+ }
340
+ // ----------------------------------------------------------- assertions ---
341
+ /**
342
+ * Assert that `actual` holds exactly the expected files. Throws an
343
+ * `AssertionError` with `actual` and `expected` set and a diff in the
344
+ * message.
345
+ *
346
+ * - `actual`: a run (which must have succeeded or stopped), a directory, or
347
+ * files by path.
348
+ * - `expected`: a directory, files by path, or a single file, in which case
349
+ * the run must have left exactly one file.
350
+ *
351
+ * Line endings are compared as `\n`. With `CODEMOD_UPDATE_FIXTURES=1`, an
352
+ * expected directory or file is rewritten to match `actual` instead.
353
+ */
354
+ export function assertTree(actual, expected, options = {}) {
355
+ if (actual instanceof Run && !actual.ok) {
356
+ throw new AssertionError({
357
+ message: describeFailure(actual),
358
+ actual: actual.status,
359
+ expected: "succeeded",
360
+ operator: "assertTree",
361
+ });
362
+ }
363
+ const actualTree = actual instanceof Run ? actual.files : treeOf(actual);
364
+ const expectedPath = isPath(expected) ? toPath(expected) : null;
365
+ const single = expectedPath !== null && existsSync(expectedPath) && statSync(expectedPath).isFile();
366
+ if (expectedPath !== null && updating()) {
367
+ // A file (`expected.ts`) when one exists or the name has an extension;
368
+ // otherwise a directory.
369
+ const asFile = single || (!existsSync(expectedPath) && extname(expectedPath) !== "");
370
+ if (asFile) {
371
+ writeFileSync(expectedPath, soleFile(actualTree, expectedPath)[1]);
372
+ }
373
+ else {
374
+ rmSync(expectedPath, { recursive: true, force: true });
375
+ writeTree(expectedPath, actualTree);
376
+ }
377
+ return;
378
+ }
379
+ if (expectedPath !== null && single) {
380
+ const [path, text] = soleFile(actualTree, expectedPath);
381
+ const want = normalize(readFileSync(expectedPath, "utf8"));
382
+ if (!same(text, want, options)) {
383
+ fail(`${path} differs from ${expectedPath}`, text, want, unifiedDiff(path, want, text), options);
384
+ }
385
+ return;
386
+ }
387
+ const expectedTree = treeOf(expected);
388
+ const paths = [...new Set([...Object.keys(expectedTree), ...Object.keys(actualTree)])].sort();
389
+ // What one tree has at a path that the other differs at; a file is never
390
+ // missing from both.
391
+ const differing = paths.flatMap((path) => {
392
+ const [got, want] = [actualTree[path], expectedTree[path]];
393
+ return got !== undefined && want !== undefined && same(got, want, options)
394
+ ? []
395
+ : [{ path, got, want }];
396
+ });
397
+ const [first, ...rest] = differing;
398
+ if (!first)
399
+ return;
400
+ const report = differing
401
+ .map(({ path, got, want }) => {
402
+ if (got === undefined)
403
+ return `missing ${path}\n`;
404
+ if (want === undefined)
405
+ return `unexpected ${path}\n`;
406
+ return unifiedDiff(path, want, got);
407
+ })
408
+ .join("");
409
+ if (!rest.length && first.got !== undefined && first.want !== undefined) {
410
+ fail(`${first.path} differs from the expected output`, first.got, first.want, report, options);
411
+ }
412
+ const changed = differing.map(({ path }) => path);
413
+ fail(`${differing.length} ${differing.length === 1 ? "file differs" : "files differ"} from the expected output`, render(actualTree, changed), render(expectedTree, changed), report, options);
414
+ }
415
+ function fail(title, actual, expected, diff, options) {
416
+ const message = options.message ? `${options.message}\n${title}` : title;
417
+ throw new AssertionError({
418
+ message: `${message}\n\n${diff.trimEnd()}\n${updateHint()}`,
419
+ actual,
420
+ expected,
421
+ operator: "assertTree",
422
+ });
423
+ }
424
+ function describeFailure(run) {
425
+ const what = run.status === "failed"
426
+ ? `the run failed: ${run.error}`
427
+ : run.status === "canceled"
428
+ ? "the run was canceled"
429
+ : run.status === "awaiting-approval"
430
+ ? `the run is waiting for an approval: ${run.awaiting}`
431
+ : `the run ended as ${run.status}`;
432
+ const logs = run.logs.length
433
+ ? `\n\nlogs:\n${run.logs.map((log) => ` ${log.step ? `[${log.step}] ` : ""}${log.line}`).join("\n")}`
434
+ : "";
435
+ return `${what}${logs}`;
436
+ }
437
+ function updateHint() {
438
+ return "(set CODEMOD_UPDATE_FIXTURES=1 to update expected files from the run)";
439
+ }
440
+ function updating() {
441
+ const value = process.env.CODEMOD_UPDATE_FIXTURES;
442
+ return value === "1" || value === "true";
443
+ }
444
+ function same(a, b, options) {
445
+ if (options.ignoreWhitespace)
446
+ return squash(a) === squash(b);
447
+ return a === b;
448
+ }
449
+ function squash(text) {
450
+ return text
451
+ .split("\n")
452
+ .map((line) => line.trimEnd())
453
+ .join("\n")
454
+ .trimEnd();
455
+ }
456
+ function soleFile(tree, expectedPath) {
457
+ const [only, ...others] = Object.entries(tree);
458
+ if (only && !others.length)
459
+ return only;
460
+ throw new AssertionError({
461
+ message: `${expectedPath} is one file, but the run left ${Object.keys(tree).length} (${Object.keys(tree).join(", ") || "none"}); compare against a directory to test more than one file`,
462
+ actual: Object.keys(tree),
463
+ expected: [basename(expectedPath)],
464
+ operator: "assertTree",
465
+ });
466
+ }
467
+ function render(tree, paths) {
468
+ return paths
469
+ .map((path) => (path in tree ? `// ${path}\n${tree[path]}` : `// ${path} (no file)\n`))
470
+ .join("\n");
471
+ }
472
+ // --------------------------------------------------------------- trees ---
473
+ function treeOf(value) {
474
+ if (isPath(value))
475
+ return readTree(toPath(value));
476
+ if (value && typeof value === "object") {
477
+ const tree = {};
478
+ for (const [path, text] of Object.entries(value)) {
479
+ if (text === null)
480
+ continue;
481
+ if (typeof text !== "string")
482
+ throw new TypeError(`file ${path} must be a string`);
483
+ tree[path.replace(/^\.\//, "")] = normalize(text);
484
+ }
485
+ return tree;
486
+ }
487
+ throw new TypeError("expected a directory path, a URL, or files by path");
488
+ }
489
+ function materialize(target, dir) {
490
+ if (isPath(target)) {
491
+ const path = toPath(target);
492
+ if (!existsSync(path))
493
+ throw new Error(`target ${path} does not exist`);
494
+ if (statSync(path).isFile())
495
+ cpSync(path, join(dir, basename(path)));
496
+ else
497
+ cpSync(path, dir, { recursive: true });
498
+ return;
499
+ }
500
+ writeTree(dir, treeOf(target));
501
+ }
502
+ function writeTree(dir, tree) {
503
+ mkdirSync(dir, { recursive: true });
504
+ for (const [path, text] of Object.entries(tree)) {
505
+ const file = join(dir, path);
506
+ mkdirSync(dirname(file), { recursive: true });
507
+ writeFileSync(file, text);
508
+ }
509
+ }
510
+ function readTree(dir) {
511
+ const tree = {};
512
+ if (!existsSync(dir))
513
+ return tree;
514
+ const walk = (current) => {
515
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
516
+ const path = join(current, entry.name);
517
+ if (entry.isDirectory())
518
+ walk(path);
519
+ else
520
+ tree[relative(dir, path).split(sep).join("/")] = normalize(readFileSync(path, "utf8"));
521
+ }
522
+ };
523
+ walk(dir);
524
+ return Object.fromEntries(Object.entries(tree).sort(([a], [b]) => (a < b ? -1 : 1)));
525
+ }
526
+ function changes(before, after) {
527
+ const changed = {};
528
+ for (const [path, text] of Object.entries(after)) {
529
+ if (before[path] !== text)
530
+ changed[path] = text;
531
+ }
532
+ for (const path of Object.keys(before)) {
533
+ if (!(path in after))
534
+ changed[path] = null;
535
+ }
536
+ return changed;
537
+ }
538
+ function normalize(text) {
539
+ return text.replace(/\r\n/g, "\n");
540
+ }
541
+ function toPath(value) {
542
+ if (isUrl(value))
543
+ return fileURLToPath(value.href);
544
+ if (typeof value === "string" && value.startsWith("file:"))
545
+ return fileURLToPath(value);
546
+ if (typeof value === "string")
547
+ return resolve(value);
548
+ throw new TypeError("expected a path or a file URL");
549
+ }
550
+ // Not `instanceof URL`: test environments may have their own URL class.
551
+ function isUrl(value) {
552
+ return value !== null && typeof value === "object" && typeof value.href === "string";
553
+ }
554
+ function isPath(value) {
555
+ return typeof value === "string" || isUrl(value);
556
+ }
557
+ /** A unified diff of two texts, by line, with three lines of context. */
558
+ function unifiedDiff(path, from, to) {
559
+ const ops = diffLines(splitLines(from), splitLines(to));
560
+ const kept = (index) => ops[index]?.[0] === " ";
561
+ if (ops.every(([sign]) => sign === " "))
562
+ return "";
563
+ const hunks = [];
564
+ const context = 3;
565
+ let i = 0;
566
+ while (i < ops.length) {
567
+ if (kept(i)) {
568
+ i++;
569
+ continue;
570
+ }
571
+ const start = Math.max(0, i - context);
572
+ let end = i;
573
+ // Extend the hunk while changes are within 2 * context lines of each other.
574
+ while (end < ops.length) {
575
+ let next = end;
576
+ while (next < ops.length && kept(next))
577
+ next++;
578
+ if (next >= ops.length || next - end > context * 2)
579
+ break;
580
+ while (next < ops.length && !kept(next))
581
+ next++;
582
+ end = next;
583
+ }
584
+ end = Math.min(ops.length, end + context);
585
+ hunks.push([start, end]);
586
+ i = end;
587
+ }
588
+ let out = `--- expected/${path}\n+++ actual/${path}\n`;
589
+ for (const [start, end] of hunks) {
590
+ const before = ops.slice(0, start);
591
+ const aLine = 1 + before.filter(([sign]) => sign !== "+").length;
592
+ const bLine = 1 + before.filter(([sign]) => sign !== "-").length;
593
+ const slice = ops.slice(start, end);
594
+ const aCount = slice.filter(([sign]) => sign !== "+").length;
595
+ const bCount = slice.filter(([sign]) => sign !== "-").length;
596
+ out += `@@ -${aLine},${aCount} +${bLine},${bCount} @@\n`;
597
+ for (const [sign, line] of slice)
598
+ out += `${sign}${line}\n`;
599
+ }
600
+ return out;
601
+ }
602
+ function splitLines(text) {
603
+ if (text === "")
604
+ return [];
605
+ const lines = text.split("\n");
606
+ if (lines[lines.length - 1] === "")
607
+ lines.pop();
608
+ return lines;
609
+ }
610
+ /** Longest-common-subsequence line diff. */
611
+ function diffLines(a, b) {
612
+ const n = a.length;
613
+ const m = b.length;
614
+ // lengths[i * width + j]: the longest common subsequence of a[i..] and b[j..].
615
+ const width = m + 1;
616
+ const lengths = new Uint32Array((n + 1) * width);
617
+ const length = (i, j) => lengths[i * width + j] ?? 0;
618
+ for (let i = n - 1; i >= 0; i--) {
619
+ for (let j = m - 1; j >= 0; j--) {
620
+ lengths[i * width + j] =
621
+ a[i] === b[j] ? length(i + 1, j + 1) + 1 : Math.max(length(i + 1, j), length(i, j + 1));
622
+ }
623
+ }
624
+ const ops = [];
625
+ let i = 0;
626
+ let j = 0;
627
+ while (i < n && j < m) {
628
+ const [left, right] = [a[i] ?? "", b[j] ?? ""];
629
+ if (left === right) {
630
+ ops.push([" ", left]);
631
+ i++;
632
+ j++;
633
+ }
634
+ else if (length(i + 1, j) >= length(i, j + 1)) {
635
+ ops.push(["-", left]);
636
+ i++;
637
+ }
638
+ else {
639
+ ops.push(["+", right]);
640
+ j++;
641
+ }
642
+ }
643
+ for (; i < n; i++)
644
+ ops.push(["-", a[i] ?? ""]);
645
+ for (; j < m; j++)
646
+ ops.push(["+", b[j] ?? ""]);
647
+ return ops;
648
+ }
@@ -0,0 +1,8 @@
1
+ // oxlint-disable triple-slash-reference
2
+ /// <reference path="llrt/index.d.ts" />
3
+ /// <reference path="modules/ast-grep.d.ts" />
4
+ /// <reference path="modules/llm.d.ts" />
5
+ /// <reference path="modules/metrics.d.ts" />
6
+ /// <reference path="modules/runtime.d.ts" />
7
+ /// <reference path="modules/workflow.d.ts" />
8
+ /// <reference path="modules/langs.d.ts" />