> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codemod.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Migrate from workflow.yaml

> workflow.yaml codemods keep running unchanged. Convert one to workflow.ts with a single command when you want to.

Codemods written as `workflow.yaml` keep working: the CLI translates them into the equivalent [`workflow.ts`](https://docs.codemod.com/community/workflows/reference) when they run. You don't need to change anything to keep using or publishing them.

For everything else that changed since 1.x (commands, flags, exit codes, metrics, callbacks), see [Upgrade from 1.x](https://docs.codemod.com/community/workflows/upgrade-from-1x.md). To try a conversion end to end, follow [Upgrade a 1.x package](https://docs.codemod.com/community/workflows/tutorials/upgrade-a-1x-package.md).

Convert a codemod to `workflow.ts` when you want what TypeScript workflows add: inline `forEachFile` callbacks, ordinary control flow instead of `depends_on` and `if:`, step results you can use in later steps, and [tests that run the whole workflow](https://docs.codemod.com/community/workflows/testing.md).

## Convert a codemod

In the package directory, preview the result, then convert:

```bash theme={null}
npx codemod@next workflow upgrade --dry-run
npx codemod@next workflow upgrade
```

You can also pass a single workflow file, for example `npx codemod@next workflow upgrade workflows/main.yaml`. If the package manifest points to that file, upgrade updates the entry to the new TypeScript file.

`upgrade` writes `workflow.ts` next to `workflow.yaml`, points `codemod.yaml` at it, and removes the YAML file. Keep the YAML file with `--keep-yaml`. In a repository with many packages, run it once at the root to convert them all.

### What else upgrade changes

Some codemod 1.x transforms use what 2.0 removed. `upgrade` rewrites what has a 2.0 equivalent and lists each change:

* **`codemod:metrics`.** The transform's import points at `__codemod_v1/metrics.ts`, a small module `upgrade` adds to the package, and the workflow calls the transform through a wrapper that returns each file's counts as its data (`{ edit, data: { metrics } }`). The counts are in the step's `outputs`. Port the transform to return `{ edit, data }` itself when you can, then delete `__codemod_v1/`.
* **Transforms that import `fs`.** `upgrade` rewrites simple reads (`readFileSync(path, "utf8")`, `existsSync`) to `codemod/files`. For any other `fs` use it names the file and leaves the import in place: the upgraded workflow's transforms keep 1.x `fs`, inside the target. They read files, write them (replacing a file that is there, as 1.x did) and delete them with `unlinkSync`, and those changes are part of the step's diff. This lasts while the line `upgrade` writes (``// Generated from workflow.yaml by `codemod workflow upgrade`.``) is among the comments `workflow.ts` starts with, so you can add a license comment above it. Moving to `codemod/files` and `file.write()` is optional; once no transform imports `fs`, you can delete the line.
* **Transforms that would not load.** Before writing, `upgrade` loads each transform once, as the upgraded workflow will. If one fails, for example because it imports a Node.js module 2.0 workflows don't provide, the package stays on `workflow.yaml` and `upgrade` names the transform and the import. Imports of packages that aren't installed can't be checked: `upgrade` notes them and goes on.

`upgrade --dry-run` shows every file it would add, change or remove as a diff, and writes nothing.

`upgrade` stops with an error, and changes nothing, when the workflow has:

* a transform that uses workflow state: `getState`, `setState`, `unsetState`, `acquireLock` or the step-output functions from `codemod:workflow`. Port it to return what it finds as `{ edit, data }`, and read that from the step's result;
* a node or template with `runtime: docker` or `runtime: podman`;
* a transform (or a file of the package it imports) that imports `child_process`. An upgraded workflow's transforms can't start processes, so its calls would fail only when they run. Move the commands to a `shell()` step, then upgrade;
* an `install-skill` step. workflow\.ts has no function to install a package's skill, so keep the workflow as `workflow.yaml`: it runs as before;
* a workflow file or a transform that is a symbolic link, or two workflows whose `.ts` files would differ only in letter case;
* a file it would change that its steps don't select, such as one a `.gitignore` ignores.

It exits with code `2` and lists the problems of every package it checked.

Fields that never had an effect, such as a `codemod` step's `args`, `env` and `working_dir`, are dropped with a warning.

For example, this `workflow.yaml`:

```yaml workflow.yaml theme={null}
version: "1"
nodes:
  - id: apply-transforms
    name: Apply AST Transformations
    type: automatic
    steps:
      - name: Replace deprecated header fields
        js-ast-grep:
          js_file: scripts/codemod.ts
          language: typescript
          include: ["**/*.ts", "**/*.js"]
          exclude: ["**/node_modules/**"]
```

becomes:

```ts workflow.ts theme={null}
// Generated from workflow.yaml by `codemod workflow upgrade`.
import { parse } from "codemod/ast-grep";
import { forEachFile, step } from "codemod/workflow";
import transform from "./scripts/codemod.ts";

type JssgResult = string | { edit?: unknown, data?: unknown } | null | void;

export default async function main() {
  // Apply AST Transformations
  await step(
    "Replace deprecated header fields",
    forEachFile(
      {
        include: ["**/*.ts", "**/*.js"],
        exclude: ["**/node_modules/**"],
        language: "typescript",
      },
      (file) => {
        const result = transform(parse(file)) as JssgResult;
        if (typeof result === "string") return file.write(result);
        if (typeof result?.edit === "string") file.write(result.edit);
        return result?.data;
      },
    ),
  );
}
```

Your transform files don't change. The workflow imports each one and calls it from a `forEachFile` callback, as the YAML step did: `parse(file)` gives the root, with the step's semantic analysis, and the text it returns is written with `file.write`. When the transform reads its options, it gets them (`params`, `language`, `targetDir`, and `matrixValues` in a matrix); with a `getSelector`, files without a match are skipped and the matches are `options.matches`; and when it returns `{ edit, data }` (even one built by a helper it imports), the callback writes `edit` and returns `data`, which the step collects into its `outputs`. `JssgResult` types what a transform returns when its own type doesn't say. A selector several steps share becomes one `const`.

Two things a plain callback cannot do: `root.rename()` (in a callback, that is `file.rename()`) and `jssgTransform` on other files. A transform that uses either (or a file of the package it imports does), runs as a dry run, or takes a templated `base_path` runs through `jssgFile` from `codemod/compat`, a compatibility adapter that runs it as workflow\.yaml's `js-ast-grep` step did; `upgrade` says which transform and why. `codemod/compat` is part of the `codemod` package you already have, with its types, and is only for migrating 1.x packages: see [1.x compatibility APIs](#1x-compatibility-apis).

Your fixture tests keep working when you do. Make the transform file's default export a callback, and add `--callback` to its test command; the fixture folders stay as they are:

```ts scripts/codemod.ts theme={null}
import { parse } from "codemod/ast-grep";
import type { FileCallback } from "codemod/workflow";

// Before: export default function transform(root) { ...; return text; }
const migrate: FileCallback = (file) => {
  const root = parse(file);
  // ... the transform's body, unchanged ...
  if (text) file.write(text);
};
export default migrate;
```

```diff package.json theme={null}
- "test": "codemod jssg test -l typescript ./scripts/codemod.ts"
+ "test": "codemod jssg test --callback -l typescript ./scripts/codemod.ts"
```

The workflow then imports it (`import migrate from "./scripts/codemod.ts"`) and gives it to `forEachFile`. A transform that read `options.params` reads them in the workflow instead; see [Test a forEachFile callback](https://docs.codemod.com/community/jssg/testing.md#test-a-foreachfile-callback).

If `upgrade` suggests it, add the `codemod` package as a dev dependency, so your editor type-checks `workflow.ts`:

```bash theme={null}
npm install --save-dev codemod@next
```

## How YAML maps to TypeScript

| `workflow.yaml` | `workflow.ts` |
| - | - |
| A node | An `async` function. A workflow with one plain node runs its steps in `main` |
| `depends_on` | Functions called in order; independent nodes run at the same time |
| A step | `await step("<step name>", <task>)` |
| `js-ast-grep` | `import transform from "./<js_file>"` and `forEachFile({ include, exclude, language, semanticAnalysis }, (file) => { const result = transform(parse(file)) as JssgResult; ... })`. A transform that calls `root.rename()` or `jssgTransform` runs through the compatibility adapter, `jssgFile` from `codemod/compat` |
| `ast-grep` | `import rules from "./<config_file>"` and `forEachFile({ include, exclude }, astGrep(rules))`, with `astGrep` imported from `codemod/ast-grep`. A `base_path` is joined to the globs (`base_path: app` with `include: ["src/**"]` gives `include: ["app/src/**"]`); `max_threads` is dropped |
| `run` | `shell(command, { env })` |
| `codemod` | `codemod(source, { params })` |
| `ai` | `agent(prompt, { ... })`, with `agent` imported from `codemod/ai` |
| `install-skill` | No workflow\.ts equivalent: keep the workflow as `workflow.yaml`, where the step keeps running. `upgrade` stops with an error |
| `matrix` (`values` or `from_state`) | One call per value, run at the same time; one at a time when the node uses git (`branch_name`, `pull_request`, step `commit`) |
| `shard` | `shard({ method, target, files, filter, previous })`, its result passed to the steps that use it. A shard `function` is imported; the shard's `js-ast-grep` transform becomes a `filter` that keeps the files it would change |
| `if:` | An `if` statement whose condition runs through `__evaluate(...)`, the YAML engine's own evaluator, so it means exactly what it did |
| `${{ params.name }}` | `params.name`. In a list field, such as `include` or a commit's `add`, a value that is an array expands into one entry per item, as before. Inside any other text it becomes `asText(params.name, "params.name")`, which prints arrays and objects as JSON and null as nothing, and fails if the value is not set, as workflow\.yaml did. Strings are printed as written (workflow\.yaml printed `"007"` as `7`), and an object's integer-like keys such as `"10"` come first, in numeric order, as in JavaScript |
| `${{ state.name }}` | `state.name`, a local object. Shell steps get it as `CODEMOD_STATE_<KEY>` variables, and the lines they write to `$STATE_OUTPUTS` are printed at the end of their stdout and copied into it by `applyStateOutputs`. JSSG transforms that call `getState` or `setState` cannot be translated; `upgrade` stops with an error that names them |
| `codemod:metrics` in a transform | An import of `__codemod_v1/metrics.ts`, a module `upgrade` adds, and a wrapper that returns the counts as the file's data. Port the transform to return `{ edit, data }` when you can |
| `trigger: manual` | `await step(approval("<node name>"))` |
| `branch_name`, `pull_request`, step `commit` | `branch`, `pullRequest` and `commit` steps, imported from `codemod/git` |
| `templates` and `use:` | Functions |

Fields that never had an effect, such as `codemod.args` or template `outputs`, are left out. `upgrade` and `codemod workflow validate` list them, and `upgrade` leaves a `// codemod upgrade:` comment where each one was.

## Check the converted codemod

Run your fixtures through the whole workflow from a test file, `tests/workflow.test.ts`:

```ts tests/workflow.test.ts theme={null}
import { describe, test } from "node:test";
import { assertTree, fixtures, runWorkflow } from "codemod/testing";

const workflow = new URL("../workflow.ts", import.meta.url);

describe("my-codemod", () => {
  for (const fixture of fixtures(new URL("./fixtures", import.meta.url))) {
    test(fixture.name, async () => {
      const run = await runWorkflow(workflow, { target: fixture.input, params: fixture.params });
      assertTree(run, fixture.expected);
    });
  }
});
```

```bash theme={null}
node --test "tests/**/*.test.ts"
```

`fixtures` reads the same layouts as `codemod jssg test`; point it at the directory that holds your fixtures. See [Testing workflows](https://docs.codemod.com/community/workflows/testing.md).

## Running a package with codemod 1.x

`codemod run` runs 1.x packages on this version. If one doesn't run here, for example because it uses `runtime: docker` steps, you can run it with codemod 1.18.7, the last 1.x release, until you convert it:

```bash theme={null}
codemod run --v1 <package>
```

In CI, set `CODEMOD_V1=on` instead of passing the flag. Each such run starts with:

```text theme={null}
--v1 runs codemod 1.18.7 and will be removed in a future release.
```

> [!WARNING]
>
> `--v1` is deprecated and will be removed. Convert the package with `codemod workflow upgrade` so it runs on this version.

`--v1` only runs packages written for 1.x: the workflow it runs is a `.yaml` or `.yml` file, and none of its scripts import a module spelled `codemod/<name>` (1.x knows only `codemod:<name>`). For any other package it stops with an error that says why. With `CODEMOD_V1=on`, other packages run on this version as usual. `--v1` can't be combined with `--control`.

codemod 1.x runs a package's shell steps without asking. So a registry package (not a local directory) is handed to it with nobody to ask, as in CI or with `--no-interactive`, only with `--approve`, the flag this version needs to run such a package's steps unattended. Without it the command stops with an error and runs nothing.

The first such run downloads the codemod 1.18.7 binary for your platform from npm (about 135–160 MB), checks it against a hash built into this CLI, and keeps it in the codemod cache with its own hash. Before each run the cached binary is checked against that hash, and downloaded again if it has changed. Set `CODEMOD_V1_BIN` to use a binary you already have, for example on a machine without network access. That binary is run as it is, without any check, so point it only at a codemod 1.18.7 you trust.

`--target`, `--param`, `--dry-run`, `--allow-dirty`, `--no-interactive`, the `--allow-*` capability flags, `--agent`, `--format jsonl` and `--workflow` are passed on, and the command exits with codemod 1.x's exit code. Options 1.x doesn't have (`--approve`, `--managed-git`, `--allow-ai`, `--model`) are not passed on. Runs made this way are kept by codemod 1.x, so `codemod workflow list`, `status` and `resume` don't see them.

## 1.x compatibility APIs

Two APIs exist only so code written for codemod 1.x keeps running. Don't use them in new code.

| API | Where it works | Where it doesn't |
| - | - | - |
| `jssgFile` and `jssgWouldChange` from `codemod/compat` | `forEachFile` callbacks (and `shard`'s `filter`, for `jssgWouldChange`) in a `workflow.ts`, on the CLI and on the [Node.js host](https://docs.codemod.com/community/workflows/node.md) | The workflow body, where using it is a build error: it runs on the `file` a callback gets |
| `jssgTransform` from `codemod/ast-grep` (or `codemod:ast-grep`) | Inside a 1.x jssg transform: under `codemod jssg run`, in a `workflow.yaml` `js-ast-grep` step, or in a transform a workflow calls with `jssgFile`. Under `codemod jssg test` it does nothing and returns `null` | Anywhere else in a `workflow.ts`: importing it in the workflow file is a build error, and calling it from a step, callback or the body throws. The Node.js host never runs it, not even through `jssgFile` |

`codemod workflow upgrade` writes `codemod/compat` only for the transforms that need it, and leaves your transform files as they are. Workflows upgraded by a 2.0 prerelease import the same functions from `codemod-internal:jssg-compat`; that keeps working, but has no types, so change the import to `codemod/compat`.

What `codemod/compat` runs gets nothing a callback doesn't have. In a `workflow.ts`, a transform gets no workflow state (`getState`) and no `codemod:metrics`, whatever options you pass: those stay with `workflow.yaml` runs. It gets `fs` only in a workflow `upgrade` wrote, with the same reads and new files as a `workflow.yaml` run. `jssgTransform` changes other files of the target only, and only in a step that runs one file at a time per worker (no `concurrency`). Approvals and trust work as for any other callback.

In a `workflow.ts`, "a transform" means the module you pass to `jssgFile` or `jssgWouldChange` as a namespace import, as `upgrade` writes it (`import * as transform from "./scripts/codemod.ts"`, then `jssgFile(transform, file)`), and the files it imports. They load apart from the workflow's own code: a helper file that both import is two copies that don't share state, and only the transform's copy can call `jssgTransform`. It runs only while `jssgFile` runs the transform; once the transform is done, or in a step with `concurrency`, it throws before it reads the other file.

Types: importing `codemod/compat` also declares `jssgTransform` on `codemod/ast-grep`, so the transforms an upgraded workflow calls keep type-checking. A standalone jssg transform that calls `jssgTransform` adds `"codemod/compat"` to `compilerOptions.types` (next to `"codemod"`) in its `tsconfig.json`; `@codemod.com/jssg-types` still declares it.

## What behaves differently

Most codemods run exactly as before. These are the differences, for both `workflow.yaml` and `workflow.ts`:

* **Modules are imported as `codemod/workflow`, `codemod/ast-grep`, and so on.** `upgrade` writes the new spelling. Imports of the older `codemod:workflow` spelling, in workflows and in transforms, keep working and name the same modules.
* **Semantic analysis is on by default for `jssg` steps.** Transforms get file-scope semantic analysis, as they do with `codemod jssg run` and `codemod jssg test`, so `definition()` and `references()` work in workflows too. Before, they returned nothing in workflows. Turn it off with `semantic_analysis: none` (YAML) or `semanticAnalysis: "none"` (TypeScript).
* **`definition()` follows re-exports to the declaring file.** Through `export { x } from "./x"` or `export * from`, it now returns the file that declares the symbol, where 1.x stopped at the re-export (or returned nothing in a workflow). A transform that rewrites imports from what `definition()` returns, such as a debarrel codemod, can write different (more accurate) imports than it did on 1.x.
* **Shell steps run in the target.** A `run:` step's commands start in the `--target` directory. 1.x started them in the directory the CLI was run from, so a command such as `npm install` now changes the target's `package.json` and lockfile, not the current directory's.
* **An `ast-grep` rule runs on every file its language can parse.** A `language: TypeScript` rule also runs on `.js`, `.mjs` and `.cjs` files that the step's `include` globs select, parsed as TypeScript, and a `Tsx` rule on `.jsx`, `.ts` and `.js`. 1.x parsed each file as the language of its extension, so a TypeScript rule never matched a `.js` file even when `include` listed it. Narrow `include` to the extensions the rule was written for to keep the 1.x result.
* **Two changes to the same path in one step are refused.** When a step would rename two files to one path, or write a file another change also writes, the step fails before writing anything and names both. 1.x applied both, and the second overwrote the first.
* **Files that aren't UTF-8 text are left out.** A selected file that can't be read as UTF-8 (a binary, or a Latin-1 source file) is skipped, and the step's log names it. 1.x reported each one as an error.
* **A step `if:` that fails to evaluate is reported.** The step is still skipped, as before, and the run's log says why.
* **`runtime: docker` and `runtime: podman` are not supported.** Runs and upgrades refuse the whole workflow before any steps run. Use the [opt-in 1.x fallback](#running-a-package-with-codemod-1x) for packages that still need these runtimes.
* **Shell state output requires a POSIX shell.** On Windows, a translated workflow that needs `$STATE_OUTPUTS` fails before any step runs. Run it on a POSIX system, or port the workflow so steps pass results directly.
* **Transforms only change files through recorded edits.** YAML packages, and workflows `upgrade` wrote, keep their supported target-local `fs` operations through the 1.x compatibility layer, including writing a new file. In a `workflow.ts` you write and its transforms, import `codemod/files` instead. Move network requests to `http()` and commands to `shell()` steps; `--allow-*` flags do not grant callbacks those capabilities. See [Callbacks are pure](https://docs.codemod.com/community/workflows/reference.md#callbacks-are-pure).
* **`state.schema` is accepted but not checked.**
* **Runs are resumed by id:** `codemod workflow resume --id <run-id>`. A manual node waits as an approval step; resume it with `--approve`. 2.0 cannot resume 1.x runs. See [Resuming runs](https://docs.codemod.com/community/workflows/upgrade-from-1x.md#resuming-runs) for changes across 2.0 versions.
* **`codemod workflow tui` was removed.** Runs show their progress in the terminal.

## Publishing workflow\.ts codemods

Older CLI versions run `workflow.yaml` only. People who run a `workflow.ts` codemod need a CLI version that runs TypeScript workflows, which `npx codemod@next` always fetches.

Publishing includes every callback and shard function the workflow imports, and every YAML rule file it imports. That is why file paths are build errors: a path, especially one computed at run time, could be missing from the published package.

## Updating a workflow\.ts written before 2.0.0

A `workflow.ts` written for a 2.0 prerelease may need these changes. Each fails to build with a message that says what to write instead. `workflow.yaml` files need none: the translation does it for them.

* **Replace `fs` imports with `codemod/files`.** Change UTF-8 `readFile` or `readFileSync` calls to `files.read(path)`, existence checks to `files.exists(path)`, and file discovery to `files.list(glob)`. To write a new file, use `files.create(path, text)`. It never overwrites an existing file. `workflow upgrade` rewrites straightforward calls and warns by filename when you need to make the change yourself.

* **`jssg(...)` was removed: per-file logic is a `forEachFile` callback.** Write it inline, or keep it in a file as that file's default export and import it:

  ```ts theme={null}
  // Before
  await step(forEachFile({ language: "tsx" }, jssg("./scripts/codemod.ts", { params: { strict: true } })));

  // After
  import migrate from "./scripts/migrate.ts"; // export default (file) => { ... }
  await step(forEachFile({ language: "tsx" }, migrate));
  ```

  In the callback, `parse(file)` (from `codemod/ast-grep`) gives the root a transform got, `file.write(text)` replaces returning the text, `file.rename(path)` replaces `root.rename()`, and the value it returns is collected into `outputs` (where a transform returned `{ edit, data }`). Values a transform read from `options.params` become variables the callback captures. `semanticAnalysis` is a selector option of `forEachFile`; capabilities are not granted in callbacks. `jssg(path, { reduce, initial })` becomes `forEachFile(selector, callback, reduce, initial)`: the reducer now gets `(result, output, path)` where it got `(result, { file, data })`, and the step's result has the folded value as `reduced` (see [Reducing outputs](https://docs.codemod.com/community/workflows/reference.md#reducing-outputs)). It folds outputs in path order as files finish, so the outputs of a large target are never all held in memory. `codemod jssg run` and `codemod jssg test` still run jssg transform files on their own, and `codemod jssg test --callback` runs a callback file on the same fixtures.

* **File paths were removed.** `forEachFile`, `shard` and `astGrep` take functions and rules, not paths:
  * `astGrep("./rules/config.yml")` → `import rules from "./rules/config.yml"` and `astGrep(rules)`, or rules written as objects: `astGrep({ id: "no-var", language: "javascript", rule: { pattern: "var $A = $B" }, fix: "let $A = $B;" })`;
  * `shard({ method: { function: "./scripts/shard.ts" } })` → an imported (or inline) shard function, `method: { function: shardFiles }`;
  * `shard({ jssg: { path, ... } })` → `filter: (file) => ...`, a callback that keeps the files it returns `true` for; `filePattern` → `files`.

* **Import `astGrep` from `codemod/ast-grep`**, next to `parse`, not from `codemod/workflow`:

  ```ts theme={null}
  // Before
  import { step, forEachFile, astGrep } from "codemod/workflow";

  // After
  import { step, forEachFile } from "codemod/workflow";
  import { astGrep } from "codemod/ast-grep";
  ```

* **`astGrep(rules)` runs only inside `forEachFile`.** It is no longer a step on its own, and its options are `repeat` and `findings`; the selector says which files:

  ```ts theme={null}
  // Before
  await step(astGrep(rules, { include: ["src/**"], basePath: "app", threads: 4 }));

  // After
  await step(forEachFile({ include: ["app/src/**"] }, astGrep(rules)));
  ```

If your editor flags `.ts` in an import, add `"allowImportingTsExtensions": true` to `tsconfig.json`, as packages from `codemod init` have.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.