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,915 @@
1
+ // oxlint-disable triple-slash-reference
2
+ /// <reference path="./metrics.d.ts" />
3
+
4
+ /**
5
+ * In a workflow, as in Node.js: where the workflow file is, also inside its
6
+ * steps and `forEachFile` callbacks.
7
+ */
8
+ interface ImportMeta {
9
+ /** The directory the workflow file is in. */
10
+ dirname: string;
11
+ /** The workflow file. */
12
+ filename: string;
13
+ /** The workflow file, as a `file:` URL. */
14
+ url: string;
15
+ }
16
+
17
+ declare module "codemod:workflow" {
18
+ /**
19
+ * Workflow Step Outputs Module
20
+ *
21
+ * This module provides functions to store and retrieve step outputs
22
+ * across workflow executions, similar to GitHub Actions.
23
+ */
24
+
25
+ /**
26
+ * Sets a step output value.
27
+ *
28
+ * Step outputs allow you to share data between steps in a workflow.
29
+ * Similar to GitHub Actions, you can reference outputs like:
30
+ * ${{ steps.my_step.outputs.my_output }}
31
+ *
32
+ * In native mode, outputs are appended to the file specified by
33
+ * the STEP_OUTPUTS environment variable.
34
+ *
35
+ * In WASM mode, outputs are stored in memory.
36
+ *
37
+ * @param stepId - The unique identifier of the step
38
+ * @param outputName - The name of the output variable
39
+ * @param value - The value to store (as a string)
40
+ *
41
+ * @deprecated Use `setState` instead for structured state that doesn't require manual JSON serialization.
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * import { setStepOutput } from 'codemod/workflow';
46
+ *
47
+ * // In a step with id="build"
48
+ * setStepOutput('build', 'version', '1.2.3');
49
+ * setStepOutput('build', 'artifact_path', '/tmp/build/app.zip');
50
+ *
51
+ * // Later steps can access these via:
52
+ * // ${{ steps.build.outputs.version }}
53
+ * // ${{ steps.build.outputs.artifact_path }}
54
+ * ```
55
+ */
56
+ export function setStepOutput(outputName: string, value: string): void;
57
+
58
+ /**
59
+ * Gets a step output value.
60
+ *
61
+ * Returns the value as a string if found, or null if the output doesn't exist.
62
+ *
63
+ * @param stepId - The unique identifier of the step
64
+ * @param outputName - The name of the output variable
65
+ * @returns The value as a string, or null if not found
66
+ *
67
+ * @deprecated Use `getState` instead for structured state that doesn't require manual JSON parsing.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * import { getStepOutput } from 'codemod/workflow';
72
+ *
73
+ * // Get output from a previous step
74
+ * const version = getStepOutput('build', 'version');
75
+ * console.log(version); // '1.2.3'
76
+ *
77
+ * // Check if output exists
78
+ * const artifactPath = getStepOutput('build', 'artifact_path');
79
+ * if (artifactPath) {
80
+ * console.log(`Artifact ready at: ${artifactPath}`);
81
+ * }
82
+ * ```
83
+ */
84
+ export function getStepOutput(stepId: string, outputName: string): string | null;
85
+
86
+ /**
87
+ * Gets a step output value, or sets it if it doesn't exist (atomically).
88
+ *
89
+ * This function is useful in concurrent scenarios where multiple files are processed
90
+ * in parallel. The first thread to call this function will set the value if it doesn't
91
+ * exist, and subsequent calls will return the existing value.
92
+ *
93
+ * This operation is atomic, preventing race conditions when multiple threads try to
94
+ * access/set the same output simultaneously.
95
+ *
96
+ * @param stepId - The unique identifier of the step
97
+ * @param outputName - The name of the output variable
98
+ * @param defaultValue - The value to set if the output doesn't exist
99
+ * @returns The existing value (if found) or the newly set default value
100
+ *
101
+ * @deprecated Use `setState`/`getState` with `acquireLock` instead for structured state.
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * import { getOrSetStepOutput, setStepOutput } from 'codemod/workflow';
106
+ *
107
+ * // Multiple files being processed in parallel
108
+ * async function transform(root: SgRoot<JS>): Promise<string | null> {
109
+ * const source = root.root().text();
110
+ * const newFiles = source.split("\n").filter(line => line.trim() !== "");
111
+ *
112
+ * // Get existing files or initialize with empty array
113
+ * const existingFilesStr = getOrSetStepOutput("scan-files", "allFiles", "[]");
114
+ * const existingFiles = JSON.parse(existingFilesStr);
115
+ *
116
+ * // Merge with existing files
117
+ * const allFiles = [...existingFiles, ...newFiles];
118
+ *
119
+ * // Update the output
120
+ * setStepOutput("allFiles", JSON.stringify(allFiles));
121
+ *
122
+ * return null;
123
+ * }
124
+ * ```
125
+ */
126
+ export function getOrSetStepOutput(
127
+ stepId: string,
128
+ outputName: string,
129
+ defaultValue: string,
130
+ ): string;
131
+
132
+ /**
133
+ * Sets a named state value that is shared across all parallel file executions.
134
+ *
135
+ * Values are stored as native JavaScript objects internally (no JSON serialization needed).
136
+ * When `persist` is true (the default), the value will be persisted at the end of the
137
+ * execution batch and available to subsequent workflow steps.
138
+ *
139
+ * @param name - The state key
140
+ * @param value - Any JSON-serializable value
141
+ * @param persist - Whether to persist across workflow steps (default: true)
142
+ *
143
+ * @example
144
+ * ```typescript
145
+ * import { setState } from 'codemod/workflow';
146
+ *
147
+ * setState("migratedFiles", ["src/App.tsx", "src/utils.ts"]);
148
+ * setState("stats", { totalFiles: 42, modified: 5 });
149
+ * setState("tempCounter", 0, false); // transient, not persisted
150
+ * ```
151
+ */
152
+ export function setState<T>(name: string, value: T, persist?: boolean): void;
153
+
154
+ /**
155
+ * Gets a named state value, or `undefined` if it doesn't exist.
156
+ *
157
+ * @param name - The state key
158
+ * @returns The stored value, or `undefined` if not found
159
+ *
160
+ * @example
161
+ * ```typescript
162
+ * import { getState } from 'codemod/workflow';
163
+ *
164
+ * const files = getState<string[]>("migratedFiles");
165
+ * if (files) {
166
+ * console.log(`Already migrated ${files.length} files`);
167
+ * }
168
+ * ```
169
+ */
170
+ export function getState<T>(name: string): T | undefined;
171
+
172
+ /**
173
+ * Removes a named state value.
174
+ *
175
+ * If the key was previously persisted, a removal diff will be generated
176
+ * so the value is also removed from persistent storage.
177
+ *
178
+ * @param name - The state key to remove
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * import { unsetState } from 'codemod/workflow';
183
+ *
184
+ * unsetState("tempData");
185
+ * ```
186
+ */
187
+ export function unsetState(name: string): void;
188
+
189
+ /**
190
+ * Acquires a named mutex lock for coordinating concurrent access to shared state.
191
+ *
192
+ * Returns a `release` function that must be called when done. The lock blocks other
193
+ * threads trying to acquire the same named lock until it is released.
194
+ *
195
+ * @param name - The lock name
196
+ * @returns A function that releases the lock (must be called exactly once)
197
+ *
198
+ * @example
199
+ * ```typescript
200
+ * import { acquireLock, getState, setState } from 'codemod/workflow';
201
+ *
202
+ * // Safely accumulate results from parallel file processing
203
+ * const release = acquireLock("results");
204
+ * try {
205
+ * const results = getState<string[]>("allResults") ?? [];
206
+ * results.push(currentFile);
207
+ * setState("allResults", results);
208
+ * } finally {
209
+ * release();
210
+ * }
211
+ * ```
212
+ */
213
+ export function acquireLock(name: string): () => void;
214
+
215
+ // ── Shard function types ────────────────────────────────────────────────
216
+
217
+ /**
218
+ * Input passed to a custom shard function by the engine.
219
+ *
220
+ * The engine handles all file discovery (globbing + optional codemod dry-run)
221
+ * before calling the shard function. The function only needs to handle grouping.
222
+ */
223
+ export interface ShardInput {
224
+ /** Relative paths of eligible files (pre-filtered by the engine) */
225
+ files: string[];
226
+ /** Absolute path to the target directory */
227
+ targetDir: string;
228
+ /** Previous shard assignments for incremental re-evaluation */
229
+ previousShards: ShardResult[];
230
+ }
231
+
232
+ /**
233
+ * A single shard result returned by a custom shard function.
234
+ *
235
+ * The `name` and `_meta_files` fields are required. Any additional
236
+ * properties are exposed as `matrix.*` variables in downstream steps.
237
+ *
238
+ * Fields prefixed with `_meta_` are excluded from the matrix hash,
239
+ * so re-indexing shards won't invalidate existing task identity.
240
+ */
241
+ export interface ShardResult {
242
+ /** Shard identifier (used in PR titles, branch names) */
243
+ name: string;
244
+ /** Shard index — excluded from matrix hash for stability */
245
+ _meta_shard: number;
246
+ /** Files in this shard */
247
+ _meta_files: string[];
248
+ /** Arbitrary metadata exposed as matrix variables */
249
+ [key: string]: unknown;
250
+ }
251
+
252
+ // ── Workflow authoring (workflow.ts) ───────────────────────────────────
253
+ //
254
+ // Everything below is used from a workflow file. `getState`, `setState`,
255
+ // `unsetState` and `acquireLock` above also work inside function steps and
256
+ // forEachFile callbacks; the step output functions only in JSSG transforms.
257
+ //
258
+ // Code inside `step(() => ...)` and `forEachFile(...)` callbacks runs in
259
+ // its own isolate, with every module the run allows (`fs`, `fetch` and
260
+ // `child_process` behind --allow-*). The rest of the workflow, the body,
261
+ // runs again on every resume: there, `Date`, `Math.random` and
262
+ // `crypto.randomUUID` are replay-safe, and modules that read files, the
263
+ // network, the environment or the clock are build errors.
264
+
265
+ import type { MetricEntry } from "codemod:metrics";
266
+
267
+ /** A JSON value: what step results, captured variables and state may hold. */
268
+ export type JsonValue =
269
+ | string
270
+ | number
271
+ | boolean
272
+ | null
273
+ | readonly JsonValue[]
274
+ | { readonly [key: string]: JsonValue };
275
+
276
+ /** Stands in for a value that is not JSON, so the type error names the problem. */
277
+ export interface NotJson<Reason extends string> {
278
+ readonly __notJson: Reason;
279
+ }
280
+
281
+ /**
282
+ * `T` with every part that is not JSON replaced by a `NotJson` marker,
283
+ * so a value of type `T` is JSON when it is assignable to `JsonCompatible<T>`.
284
+ */
285
+ export type JsonCompatible<T> = unknown extends T
286
+ ? T
287
+ : T extends string | number | boolean | null | undefined | void
288
+ ? T
289
+ : T extends PromiseLike<unknown>
290
+ ? NotJson<"a Promise: await it first">
291
+ : T extends (...args: never[]) => unknown
292
+ ? NotJson<"a function">
293
+ : T extends ReadonlySet<unknown>
294
+ ? NotJson<"a Set: use an array">
295
+ : T extends ReadonlyMap<unknown, unknown>
296
+ ? NotJson<"a Map: use a plain object">
297
+ : T extends Date
298
+ ? NotJson<"a Date: use date.toISOString()">
299
+ : T extends RegExp
300
+ ? NotJson<"a RegExp: use its source string">
301
+ : T extends object
302
+ ? { [K in keyof T]: JsonCompatible<T[K]> }
303
+ : NotJson<"not JSON">;
304
+
305
+ /** Step results are deeply frozen. */
306
+ export type Frozen<T> = T extends (...args: never[]) => unknown
307
+ ? T
308
+ : T extends readonly (infer U)[]
309
+ ? readonly Frozen<U>[]
310
+ : T extends object
311
+ ? { readonly [K in keyof T]: Frozen<T[K]> }
312
+ : T;
313
+
314
+ const taskResult: unique symbol;
315
+
316
+ /** Work for `step()` to run, made by `forEachFile` or a task such as `shell`. */
317
+ export interface Task<Result> {
318
+ readonly [taskResult]: Result;
319
+ }
320
+
321
+ const transformResult: unique symbol;
322
+
323
+ /**
324
+ * A transform for single files, made by `jssg` or `astGrep`. Give it to
325
+ * `forEachFile` to say which files it runs on.
326
+ */
327
+ export interface Transform<Result> extends Task<Result> {
328
+ readonly [transformResult]: Result;
329
+ }
330
+
331
+ /** What the workflow's default export receives. */
332
+ export interface WorkflowContext<Params = Record<string, unknown>> {
333
+ /** `--param key=value` values (JSON when they parse as JSON, otherwise strings). */
334
+ params: Params;
335
+ /** Absolute path of the directory the workflow runs on. */
336
+ target: string;
337
+ /** Whether this is a dry run: file changes are computed but not written. */
338
+ dryRun: boolean;
339
+ }
340
+
341
+ /**
342
+ * A length of time: a number of milliseconds, or a number with a unit,
343
+ * such as `"500ms"`, `"30s"`, `"10m"`, `"1h"` or `"2d"`.
344
+ */
345
+ export type Duration = number | `${number}${"ms" | "s" | "m" | "h" | "d"}`;
346
+
347
+ /**
348
+ * How a step is run. These do not identify the step: changing them does
349
+ * not make a finished step run again on resume.
350
+ */
351
+ export interface StepOptions {
352
+ /**
353
+ * Runs the step again when it fails, up to this many more times. The
354
+ * run sees only the last failure. Default: 0.
355
+ */
356
+ retries?: number;
357
+ /** How long to wait before each retry. Default: `"1s"`. */
358
+ retryDelay?: Duration;
359
+ /**
360
+ * Stops the step, and fails it, when one attempt takes longer than
361
+ * this: commands are terminated and file changes not yet written are
362
+ * dropped.
363
+ */
364
+ timeout?: Duration;
365
+ }
366
+
367
+ /**
368
+ * Runs a task as a durable step and resolves to its frozen result.
369
+ *
370
+ * The step starts when `step()` is called, so `Promise.all` runs steps in
371
+ * parallel. Its result is recorded; on `codemod workflow resume`, finished
372
+ * steps are replayed from the record instead of running again.
373
+ *
374
+ * @example
375
+ * ```ts
376
+ * const renamed = await step("Rename stylesheets", forEachFile("src/**\/*.less", (file) => {
377
+ * file.rename(file.path.replace(/\.less$/, ".css"));
378
+ * }));
379
+ * await step("Install", shell("pnpm install"), { retries: 2, timeout: "10m" });
380
+ * ```
381
+ */
382
+ export function step<Result>(task: Task<Result>, options?: StepOptions): Promise<Frozen<Result>>;
383
+ export function step<Result>(
384
+ label: string,
385
+ task: Task<Result>,
386
+ options?: StepOptions,
387
+ ): Promise<Frozen<Result>>;
388
+ /**
389
+ * Runs a function once, in its own isolate, and records its result, which
390
+ * must be JSON. Write it inline: outside variables arrive as frozen copies,
391
+ * and assigning to them is a build error. Inside, `Date`, `fetch`, `fs` and
392
+ * so on are real (as the run's capabilities allow).
393
+ */
394
+ export function step<Result>(
395
+ run: () => PromiseLike<Checked<Result>>,
396
+ options?: StepOptions,
397
+ ): Promise<Frozen<StepValue<Result>>>;
398
+ export function step<Result>(
399
+ label: string,
400
+ run: () => PromiseLike<Checked<Result>>,
401
+ options?: StepOptions,
402
+ ): Promise<Frozen<StepValue<Result>>>;
403
+ export function step<Result>(
404
+ run: () => Checked<Result>,
405
+ options?: StepOptions,
406
+ ): Promise<Frozen<StepValue<Result>>>;
407
+ export function step<Result>(
408
+ label: string,
409
+ run: () => Checked<Result>,
410
+ options?: StepOptions,
411
+ ): Promise<Frozen<StepValue<Result>>>;
412
+
413
+ /**
414
+ * Waits, as a step. The wait counts from when it began: a run that is
415
+ * interrupted and resumed waits only for what is left. A dry run does not
416
+ * wait.
417
+ *
418
+ * @example
419
+ * ```ts
420
+ * await sleep("30s");
421
+ * ```
422
+ */
423
+ export function sleep(duration: Duration): Promise<null>;
424
+
425
+ /**
426
+ * Waits, as a step, for an event sent to the run with
427
+ * `codemod workflow send <name> --id <run-id> [--data <json>]`, and
428
+ * resolves to its data (`null` when none was given). An event sent before
429
+ * the workflow gets here is kept for it. With `timeout`, the step fails if
430
+ * no event comes in that time, counted from when the wait began.
431
+ *
432
+ * A dry run is not saved and cannot be sent events, so the step fails there.
433
+ *
434
+ * @example
435
+ * ```ts
436
+ * const ci = await waitForEvent<{ passed: boolean }>("ci-finished", { timeout: "1h" });
437
+ * ```
438
+ */
439
+ export function waitForEvent<Data = JsonValue>(
440
+ name: string,
441
+ options?: { timeout?: Duration },
442
+ ): Promise<Frozen<Data>>;
443
+
444
+ /**
445
+ * `T`, checked to be JSON: `Result` is inferred from the value, which must
446
+ * then also be assignable to its JSON-compatible form.
447
+ */
448
+ export type Checked<T> = T & NoInfer<JsonCompatible<T>>;
449
+
450
+ /** A function step that returns nothing records `null`. */
451
+ export type StepValue<T> = [T] extends [void | undefined] ? null : Exclude<T, void | undefined>;
452
+
453
+ /** One glob or several. */
454
+ export type Globs = string | readonly string[];
455
+
456
+ /** Languages `forEachFile` can select files by, through their extensions. */
457
+ export type SelectorLanguage =
458
+ | "typescript"
459
+ | "tsx"
460
+ | "javascript"
461
+ | "css"
462
+ | "json"
463
+ | "html"
464
+ | "python"
465
+ | "rust"
466
+ | "go"
467
+ | "java"
468
+ | "yaml";
469
+
470
+ /** How a `forEachFile` step runs its callback. */
471
+ export interface ForEachFileOptions {
472
+ /** Files only these globs match are skipped. */
473
+ exclude?: Globs;
474
+ /** Only files whose text contains this string. */
475
+ containing?: string;
476
+ /**
477
+ * Files each worker keeps in flight (default 1). Raise it for async
478
+ * callbacks that wait on the network or `codemod/llm`.
479
+ */
480
+ concurrency?: number;
481
+ }
482
+
483
+ /**
484
+ * Which files `forEachFile` visits, and how: a glob, a list of globs, or an
485
+ * object. Without `include` or `language`, the files of the package's
486
+ * `targets.languages` (codemod.yaml) are visited. `.gitignore` is respected.
487
+ */
488
+ export type FileSelector =
489
+ | Globs
490
+ | (ForEachFileOptions & {
491
+ include: Globs;
492
+ /** The default language for `parse(file)` and `parse(text)`. */
493
+ language?: string;
494
+ })
495
+ | (ForEachFileOptions & {
496
+ include?: undefined;
497
+ /** Selects the language's file extensions, and is the default for `parse`. */
498
+ language?: SelectorLanguage;
499
+ });
500
+
501
+ /** The file a `forEachFile` callback receives. Changes are applied when the step ends. */
502
+ export interface WorkflowFile {
503
+ /** Path relative to the target. */
504
+ readonly path: string;
505
+ /** Contents when the step started. */
506
+ readonly text: string;
507
+ /** The selector's `language`, which `parse(file)` uses; otherwise undefined. */
508
+ readonly language?: string;
509
+ /** Replace the contents. */
510
+ write(text: string): void;
511
+ /** Move the file to `path`, relative to the target. */
512
+ rename(path: string): void;
513
+ /** Remove the file. */
514
+ delete(): void;
515
+ }
516
+
517
+ /** Files a step changed. */
518
+ export interface FileChanges {
519
+ written: string[];
520
+ renamed: { from: string; to: string }[];
521
+ deleted: string[];
522
+ }
523
+
524
+ export interface FileFailure {
525
+ path: string;
526
+ error: string;
527
+ }
528
+
529
+ export interface ForEachFileResult<Output> {
530
+ /** What the callback returned, in path order. Files that returned nothing are left out. */
531
+ outputs: Output[];
532
+ changes: FileChanges;
533
+ /**
534
+ * Files whose callback threw. With some, the step is partial; when the
535
+ * callback throws on every file, the step fails instead.
536
+ */
537
+ failures: FileFailure[];
538
+ /** What callbacks recorded with `codemod/metrics`, by metric name. */
539
+ metrics: Record<string, MetricEntry[]>;
540
+ }
541
+
542
+ /**
543
+ * Runs `callback` once for every selected file, in parallel, in isolates.
544
+ * The callback may be async. Returned values are collected into `outputs`.
545
+ *
546
+ * Write the callback inline. Variables from outside it arrive as frozen
547
+ * copies and must be JSON; assigning to them is a build error. Imports
548
+ * (`codemod/ast-grep`, `codemod/metrics`, packages, files next to the
549
+ * workflow) are available inside.
550
+ *
551
+ * @example
552
+ * ```ts
553
+ * import { parse } from "codemod/ast-grep";
554
+ *
555
+ * const usages = await step(forEachFile({ language: "typescript", containing: "moment" }, (file) => {
556
+ * const found = parse(file).root().findAll({ rule: { pattern: 'import $X from "moment"' } });
557
+ * return found.length ? file.path : undefined;
558
+ * }));
559
+ * usages.outputs; // readonly string[]
560
+ * ```
561
+ */
562
+ export function forEachFile<Output = undefined>(
563
+ selector: FileSelector,
564
+ callback: (file: WorkflowFile) => PromiseLike<Checked<Output>>,
565
+ ): Task<ForEachFileResult<Exclude<Output, void | undefined>>>;
566
+ export function forEachFile<Output = undefined>(
567
+ selector: FileSelector,
568
+ callback: (file: WorkflowFile) => Checked<Output>,
569
+ ): Task<ForEachFileResult<Exclude<Output, void | undefined>>>;
570
+ /** Visits the files of the package's `targets.languages` (codemod.yaml). */
571
+ export function forEachFile<Output = undefined>(
572
+ callback: (file: WorkflowFile) => PromiseLike<Checked<Output>>,
573
+ ): Task<ForEachFileResult<Exclude<Output, void | undefined>>>;
574
+ export function forEachFile<Output = undefined>(
575
+ callback: (file: WorkflowFile) => Checked<Output>,
576
+ ): Task<ForEachFileResult<Exclude<Output, void | undefined>>>;
577
+
578
+ /**
579
+ * Which files `forEachFile` runs a `jssg` transform on: a glob, a list of
580
+ * globs, or an object. `language` is the language the files are parsed as
581
+ * and, without `include`, selects that language's file extensions. Without
582
+ * a `language`, the package's is used (`targets.languages` in codemod.yaml,
583
+ * when it lists one), and otherwise `typescript`.
584
+ */
585
+ export type JssgSelector = Globs | { include?: Globs; exclude?: Globs; language?: string };
586
+
587
+ /**
588
+ * Which files `forEachFile` applies `astGrep` rules to: a glob, a list of
589
+ * globs, or an object. Without `include`, the files of the rules' languages.
590
+ */
591
+ export type AstGrepSelector = Globs | { include?: Globs; exclude?: Globs };
592
+
593
+ /**
594
+ * Runs a JSSG transform, or applies an ast-grep rule file, on every
595
+ * selected file. The selector's fields stand for the same options of
596
+ * `jssg` and `astGrep`, so give each in one place.
597
+ *
598
+ * @example
599
+ * ```ts
600
+ * await step("Migrate imports", forEachFile(jssg("scripts/codemod.ts")));
601
+ * await step("Apply rules", forEachFile("src/**\/*.ts", astGrep("rules/config.yml")));
602
+ * await step("Migrate components", forEachFile(
603
+ * { include: "src/**\/*.tsx", exclude: "**\/*.test.tsx", language: "tsx" },
604
+ * jssg("scripts/components.ts", { params: { strict: true } }),
605
+ * ));
606
+ * ```
607
+ */
608
+ export function forEachFile(transform: Transform<JssgResult>): Task<JssgResult>;
609
+ export function forEachFile(
610
+ selector: JssgSelector,
611
+ transform: Transform<JssgResult>,
612
+ ): Task<JssgResult>;
613
+ export function forEachFile(transform: Transform<AstGrepResult>): Task<AstGrepResult>;
614
+ export function forEachFile(
615
+ selector: AstGrepSelector,
616
+ transform: Transform<AstGrepResult>,
617
+ ): Task<AstGrepResult>;
618
+
619
+ /**
620
+ * Returns the whole workflow state as a frozen object.
621
+ * (With a key, see the `getState(name)` overload above.)
622
+ */
623
+ export function getState(): Readonly<Record<string, JsonValue>>;
624
+
625
+ /**
626
+ * A result for tasks that do nothing in some runs: shell commands, agents
627
+ * and skill installs in a dry run, git tasks without `--managed-git`.
628
+ */
629
+ export type Skippable<T> =
630
+ | (T & { skipped?: false })
631
+ | ({ skipped: true } & { [K in keyof T]?: undefined });
632
+
633
+ export interface ShellOptions {
634
+ /** Extra environment variables. */
635
+ env?: Readonly<Record<string, string>>;
636
+ /** Directory to run in, relative to the target (or absolute). Defaults to the current directory. */
637
+ cwd?: string;
638
+ }
639
+
640
+ /** A value in a `shell` template: quoted as one word, or one word per item. */
641
+ export type ShellValue = string | number | boolean | readonly (string | number | boolean)[];
642
+
643
+ export type ShellTask = Task<Skippable<{ output: string }>>;
644
+
645
+ /**
646
+ * Runs a shell command. It can read the workflow state from `$CODEMOD_STATE`
647
+ * (a JSON file) or `$CODEMOD_STATE_<KEY>`, and set state by writing
648
+ * `key=value` (or `key@=value` to append) lines to `$STATE_OUTPUTS`.
649
+ *
650
+ * @example
651
+ * await step("Install", shell("npm install"));
652
+ * await step("Setup", shell`${import.meta.dirname}/scripts/setup.sh`);
653
+ */
654
+ export function shell(command: string, options?: ShellOptions): ShellTask;
655
+ /**
656
+ * Runs a shell command written as a template. Each value is quoted for the
657
+ * shell, so a path with spaces stays one argument; the text around them is
658
+ * taken as written, backslashes included.
659
+ *
660
+ * @example
661
+ * await step("Find uses", shell`grep -rn ${name} src`);
662
+ */
663
+ export function shell(strings: TemplateStringsArray, ...values: ShellValue[]): ShellTask;
664
+ /**
665
+ * Options for a command written as a template.
666
+ *
667
+ * @example
668
+ * await step("Build", shell({ cwd: "packages/app" })`npm run build`);
669
+ */
670
+ export function shell(
671
+ options: ShellOptions,
672
+ ): (strings: TemplateStringsArray, ...values: ShellValue[]) => ShellTask;
673
+
674
+ export type Capability = "fs" | "fetch" | "child_process";
675
+
676
+ export interface JssgOptions {
677
+ include?: Globs;
678
+ exclude?: Globs;
679
+ /** Directory under the target to restrict the run to. */
680
+ basePath?: string;
681
+ /** Process exactly these files, relative to the target. */
682
+ files?: readonly string[];
683
+ /** Defaults to `typescript`. */
684
+ language?: string;
685
+ /** Merged over the run's params; the transform reads them as `options.params`. */
686
+ params?: Readonly<Record<string, unknown>>;
687
+ /** The transform reads these as `options.matrixValues`. */
688
+ matrix?: Readonly<Record<string, unknown>>;
689
+ capabilities?: readonly Capability[];
690
+ /**
691
+ * Semantic analysis for `definition()` and `references()`: `"file"` (the default)
692
+ * analyses each file on its own, `"workspace"` the whole target (or `root`), and
693
+ * `"none"` turns it off.
694
+ */
695
+ semanticAnalysis?:
696
+ | "file"
697
+ | "workspace"
698
+ | "none"
699
+ | { mode: "file" | "workspace"; root?: string };
700
+ threads?: number;
701
+ /** Run the transform without applying its changes. */
702
+ dryRun?: boolean;
703
+ }
704
+
705
+ export interface JssgResult {
706
+ changes: FileChanges;
707
+ unmodified: number;
708
+ failures: FileFailure[];
709
+ }
710
+
711
+ /**
712
+ * A JSSG transform file; `path` is relative to the workflow file. Run it
713
+ * with `forEachFile(selector, jssg(path))`, which says which files it is
714
+ * for. As a step on its own it runs on the files its options select.
715
+ */
716
+ export function jssg(path: string, options?: JssgOptions): Transform<JssgResult>;
717
+
718
+ export interface AstGrepOptions {
719
+ include?: Globs;
720
+ exclude?: Globs;
721
+ basePath?: string;
722
+ threads?: number;
723
+ }
724
+
725
+ export interface AstGrepResult {
726
+ changes: FileChanges;
727
+ matches: number;
728
+ failures: FileFailure[];
729
+ }
730
+
731
+ /**
732
+ * An ast-grep YAML rule file; `path` is relative to the workflow file.
733
+ * Apply it with `forEachFile(selector, astGrep(path))`, which says which
734
+ * files it is for. As a step on its own it runs on the files its options
735
+ * select.
736
+ */
737
+ export function astGrep(path: string, options?: AstGrepOptions): Transform<AstGrepResult>;
738
+
739
+ export type ShardMethod =
740
+ | {
741
+ type: "directory" | "codeowner";
742
+ /** Target number of files per shard. */
743
+ maxFilesPerShard: number;
744
+ /** Trailing shards smaller than this are merged into the previous one. */
745
+ minShardSize?: number;
746
+ }
747
+ | {
748
+ /** A JS/TS file whose default export receives a `ShardInput` and returns `ShardResult[]`. */
749
+ function: string;
750
+ };
751
+
752
+ export interface ShardOptions {
753
+ method: ShardMethod;
754
+ /** Directory to scan, relative to the target. */
755
+ target?: string;
756
+ /** Glob for eligible files when `jssg` is not set. */
757
+ filePattern?: string;
758
+ /** Keep only the files this transform would change. */
759
+ jssg?: JssgOptions & { path: string };
760
+ /** An earlier result of this step, so existing assignments are kept. */
761
+ previous?: readonly ShardResult[];
762
+ }
763
+
764
+ /** Splits files into groups ("shards"), for example one per directory or code owner. */
765
+ export function shard(options: ShardOptions): Task<ShardResult[]>;
766
+
767
+ /** Runs another codemod package (registry name or local path) as part of this step. */
768
+ export function codemod(
769
+ source: string,
770
+ options?: { params?: Readonly<Record<string, unknown>> },
771
+ ): Task<{ output: JsonValue }>;
772
+
773
+ /** Coding agents `agent(...)` can run, by id. Aliases such as `"claude"` work too. */
774
+ export type CodingAgent =
775
+ | "claude-code"
776
+ | "codex"
777
+ | "cursor"
778
+ | "gemini"
779
+ | "antigravity"
780
+ | "opencode"
781
+ | "copilot"
782
+ | "amp"
783
+ | "qwen-code"
784
+ | "goose"
785
+ | "droid"
786
+ | "kimi"
787
+ | "crush"
788
+ | "openclaw"
789
+ | "aider"
790
+ | "kiro"
791
+ | "auggie"
792
+ | "cline";
793
+
794
+ export interface AgentOptions {
795
+ /**
796
+ * The coding agent to run, which must be installed. Without one: the run's
797
+ * agent (`--agent`, `LLM_AGENT`); the agent the workflow itself runs
798
+ * inside, which gets the prompt back; one the person picks; or the
799
+ * built-in agent when `LLM_API_KEY` is set.
800
+ */
801
+ agent?: CodingAgent | (string & {});
802
+ /** Extra instructions for the agent. */
803
+ systemPrompt?: string;
804
+ /** A model name the agent understands. */
805
+ model?: string;
806
+ /**
807
+ * `"full"` (default): edit files and run commands without asking.
808
+ * `"read-only"`: the agent may look but not change anything. Agents that
809
+ * cannot be held to that (see the agent table in the docs) fail the step
810
+ * instead of running.
811
+ */
812
+ autonomy?: "full" | "read-only";
813
+ /** Stop the agent after this many seconds. */
814
+ timeoutSeconds?: number;
815
+ /** Built-in agent only: the most tool-using steps it may take. */
816
+ maxSteps?: number;
817
+ /** Built-in agent only. */
818
+ tools?: readonly string[];
819
+ /** Built-in agent only. */
820
+ endpoint?: string;
821
+ /** Built-in agent only. */
822
+ apiKey?: string;
823
+ /** Built-in agent only. */
824
+ llmProtocol?: string;
825
+ }
826
+
827
+ export interface AgentUsage {
828
+ inputTokens?: number;
829
+ outputTokens?: number;
830
+ costUsd?: number;
831
+ }
832
+
833
+ export interface AgentResult {
834
+ skipped?: true;
835
+ /** The prompt went back to the coding agent this workflow runs inside (`true`), or nowhere (`false`). */
836
+ handedOff?: boolean;
837
+ /** The agent that ran the prompt (`"built-in"` for the built-in agent). */
838
+ agent?: string;
839
+ /** The agent's final answer. */
840
+ result?: string | null;
841
+ /** The agent's session, to continue it there. */
842
+ sessionId?: string | null;
843
+ model?: string | null;
844
+ /** Tokens and cost, as far as the agent reports them. */
845
+ usage?: AgentUsage | null;
846
+ /** Structured output from the built-in agent. */
847
+ data?: JsonValue;
848
+ }
849
+
850
+ /** Hands a prompt to a coding agent. */
851
+ export function agent(prompt: string, options?: AgentOptions): Task<AgentResult>;
852
+
853
+ export interface InstallSkillOptions {
854
+ /** Package to install, for example `@codemod/jest-to-vitest`. */
855
+ package: string;
856
+ /** Skill source path inside the package. */
857
+ path?: string;
858
+ harness?: "auto" | "claude" | "goose" | "opencode" | "cursor" | "codex" | "antigravity";
859
+ scope?: "project" | "user";
860
+ force?: boolean;
861
+ }
862
+
863
+ /** Installs a package's agent skill into a coding-agent harness. */
864
+ export function installSkill(options: InstallSkillOptions): Task<Skippable<{ output: string }>>;
865
+
866
+ /**
867
+ * Waits for a person to approve. Interactive runs ask; with `--no-interactive`
868
+ * the run pauses here until `codemod workflow resume --id <id> --approve`.
869
+ */
870
+ export function approval(message: string): Task<{ approved: true }>;
871
+
872
+ /** Checks out a branch for the following changes. Only with `--managed-git`. */
873
+ export function branch(name: string): Task<Skippable<{ branch: string }>>;
874
+
875
+ /** Commits changes. Only with `--managed-git`. */
876
+ export function commit(
877
+ message: string,
878
+ options?: { add?: readonly string[]; allowEmpty?: boolean },
879
+ ): Task<Skippable<{ committed: boolean }>>;
880
+
881
+ export interface PullRequestOptions {
882
+ title: string;
883
+ body?: string;
884
+ draft?: boolean;
885
+ base?: string;
886
+ /** Defaults to the current branch. */
887
+ branch?: string;
888
+ }
889
+
890
+ /** Pushes the branch and opens a pull request. Only with `--managed-git`. */
891
+ export function pullRequest(
892
+ options: PullRequestOptions,
893
+ ): Task<Skippable<{ branch: string; url: string | null }>>;
894
+
895
+ /** A step failed. */
896
+ export class StepError extends Error {
897
+ readonly label: string;
898
+ }
899
+
900
+ /** The run was canceled. */
901
+ export class CanceledError extends Error {}
902
+
903
+ /** The run is paused at an approval. */
904
+ export class AwaitingApprovalError extends Error {}
905
+
906
+ /**
907
+ * Evaluates a workflow.yaml `${{ }}` expression.
908
+ * @internal Emitted by `codemod workflow upgrade`; not for hand-written workflows.
909
+ */
910
+ export function __evaluate(
911
+ kind: "condition" | "string" | "list",
912
+ expression: string,
913
+ scope: Readonly<Record<string, unknown>>,
914
+ ): any;
915
+ }