Introducing The Sweep: OX’s New Live Security Research Series
Register Now
Breaking: The 2026 Vulnpocalypse Hits PHP: Four Critical RCEs, but How Dangerous Are They?
Read the Report
Are you exposed? Connect your apps in minutes.
Scan your apps free

sh-codemod

Latest version: v0.2.0

Overview

Last scanned
29 Nov 2026
Published
29 Nov 2026
npm package Publisher: northm
0 Stars
0 Forks
6 Versions
991 Downloads
TypeScript Repo language

Scan summary

sh-codemod was last scanned on 29 Nov 2026 at version 0.2.0. Risk score 0 of 100. No malicious behavior was detected.

  • Releases: 6 versions; the latest was published on 29 Nov 2026.
  • Findings: No rules fired in version 0.2.0.
  • Downloads: 991 downloads.

Versions

6 versions published
Versions and the rules that fired in each
VersionPublishedStatus
0.2.0 LATEST 29 Nov 2026 No rules fired
0.1.3 13 Nov 2026 No rules fired
0.1.2 11 Nov 2026 No rules fired
0.1.1 8 Nov 2026 Not shown
0.0.0-development.0 7 Nov 2026 Not shown

No rules fired in 0.2.0

Findings

Findings for v0.2.0. The score is a capped sum of the weights of the rules that fired — not CVSS, not exploitability, and not a probability. It is not comparable across packages with different scan coverage.

The score describes 0.2.0; other versions have their own rules, not their own score.

README

The publisher’s own README, as collected from the registry.

sh-codemod

npm version CI license

Whole-file shell formatting and source-preserving AST edits for JavaScript and TypeScript, built on the sh-ast shell parser:

  • format rewrites a whole shell script into the canonical text of mvdan/sh's printer (the shfmt style).
  • createEditor makes AST-aware edits (a codemod) that leave every other byte of the file alone.

When to use it

Use sh-codemod when a program needs to change shell source. Use eslint-sh when you need to check it.

ESLint fixes are text-range replacements that run inside a lint pass. They cannot reformat a whole file, and they are not available to a script that is not running ESLint. sh-codemod covers those cases: reformatting an entire script, and codemods that rewrite one construct (every which becomes command -v, a line is added to the top of every script) without disturbing the comments, spacing and line endings around it. It does not parse (that is sh-ast), lint, or analyze shell.

Installation

npm install sh-codemod

Requires Node 24 or later. The package ships ESM and CommonJS builds with TypeScript declarations; the CommonJS build loads the ESM-only sh-ast with require, using Node's synchronous ESM loading support. The package is on the 0.x line, so its surface may change between minor releases.

import { format } from 'sh-codemod'; // or: const { format } = require('sh-codemod');

Quickstart

import { createEditor, format } from 'sh-codemod';

console.log(
  format('if [ -f a ];then\n    echo   hi # greet\nfi\n', { Indent: 2 }),
);
// if [ -f a ]; then
//   echo hi # greet
// fi

const editor = createEditor('which   git  # where?\n');
editor.replaceNode(editor.ast.Stmts[0].Cmd.Args[0], 'command -v');
console.log(JSON.stringify(editor.apply()));
// "command -v   git  # where?\n"

format re-prints the whole script. createEditor changed only the one word, so the extra spaces and the comment survive. The sections below cover each function in full.

Documentation

  • API reference, generated from the package's declarations and checked in CI.
  • CHANGELOG, maintained by Changesets from the changes in each release.
  • Repository tooling, for how the package is built, checked and released.
  • Contributing, for development and pull request guidance.
  • Security policy, for reporting vulnerabilities.
  • LICENSE, MIT.

format(text, options?)

import { format } from 'sh-codemod';

format('if true;then\n    echo   hi # greet\nfi');
// 'if true; then\n\techo hi # greet\nfi\n'

format parses text and prints the syntax tree, so the result depends only on the tree:

  • Indentation, spacing and runs of blank lines are normalized (a single blank line is kept).
  • Comments and here-document bodies are kept verbatim; \r\n line endings come out as \n.
  • The result ends in a newline. An empty input formats to "\n".
  • Formatting is idempotent, format(format(x)) === format(x), for every option except the two listed under Known exceptions.
Options

FormatOptions combines the producer-native dialect and diagnostic filename with sh-ast's PrintOptions. Printer knobs retain the pinned mvdan/sh spellings and meanings.

Option Type Default Effect
Indent number \| bigint 0 (tabs) Spaces per indentation level; 0 indents with tabs.
BinaryNextLine boolean false Put a multiline binary operator such as \| on the next line, after a \.
SwitchCaseIndent boolean false Indent case alternatives; their bodies go two levels below the case.
SpaceRedirects boolean false Space after redirection operators (> out), except >&, <&, >( and <(.
FunctionNextLine boolean false Put a function's opening brace on the next line.
Minify boolean false Drop comments, indentation and optional whitespace. Not allowed with SingleLine.
SingleLine boolean false Print on one line where possible (newlines after comments and around here-documents remain).
KeepPadding boolean false Best-effort column preservation. Deprecated upstream, which plans to remove it.
dialect LangVariant LangBash Numeric language value imported from sh-ast; the parser decides operation validity.
filename string none Name used in syntax-error messages and on FormatSyntaxError.filename.
import { LangPOSIX } from 'sh-ast';
import { format } from 'sh-codemod';

format(script, {
  Indent: 2,
  SwitchCaseIndent: true,
  dialect: LangPOSIX,
  filename: 'deploy.sh',
});

LangVariant is re-exported directly from sh-ast. This extraction deliberately replaces string grammar labels with producer-native numeric values. Import constants such as LangPOSIX from sh-ast; there are no string aliases or local language membership lists. The type describes known language values, not a promise that every parser operation accepts each member: the pinned sh-ast@0.10.0 parser treats zero as legacy Bash and rejects LangAuto with SH_AST_SYNTAX_INPUT. Numeric validation remains the parser's responsibility. Non-numeric dialects, invalid filenames and removed option names retain service-option errors.

Not exposed, on purpose: RecoverErrors would let malformed input through as a repaired tree, and StopAt would silently drop the rest of the file. Both would break the rule that format never loses or invents code. KeepComments is always on (a Minify print omits comments by definition).

Known exceptions

Both come from the upstream printer. format reports its output as is and does not work around them.

  • KeepPadding: true is not idempotent. The printer keeps padding "best-effort", so a second pass can change spacing the first kept. For example echo x # d inside a function body prints as echo x # d, and formatting that prints echo x # d; echo b in a case body shrinks the same way. Upstream deprecates the option and plans to remove it.
  • SingleLine: true can print invalid shell. A statement after a case is joined without a ;, so case $x in a) :;; esac followed by if a; then b; fi prints case $x in a) : ;; esac if a; then b; fi, which does not parse. format does not re-parse its output, so it returns that text. Check SingleLine output on your scripts before relying on it.

Idempotence was checked for every other printer option alone and in combinations (Indent 2, 4 and 8, BinaryNextLine, SwitchCaseIndent, SpaceRedirects, FunctionNextLine, Minify) on sources with here-documents, comments, multibyte text and CRLF.

Errors

A syntax error, including a construct the selected dialect does not allow, throws FormatSyntaxError. format never returns partial output.

import { format, FormatSyntaxError } from 'sh-codemod';

try {
  format('echo ok\necho "never closed\n', { filename: 'a.sh' });
} catch (error) {
  if (error instanceof FormatSyntaxError) {
    error.message; // 'a.sh:2:6: reached EOF without closing quote `"`'
    error.line; // 2
    error.column; // 6
    error.offset; // 13
  }
}
Property Meaning
code 'SH_CODEMOD_FORMAT_SYNTAX', stable across releases.
offset Zero-based UTF-16 index into the string you passed (text[offset] is the position).
line One-based line; a \r\n pair is one line break.
column One-based UTF-16 column, as ESLint reports it.
byteOffset The parser's zero-based UTF-8 offset, for tools that address bytes.
filename The filename option, if given.
cause The underlying sh-ast ParseError or LangError.

Other sh-ast failures are thrown as they are: PrintError for incompatible printer options (Minify together with SingleLine), and InputError for text that is not well-formed Unicode or a rejected upstream printer option. Invalid project options throw TypeError with SH_CODEMOD_SERVICE_OPTION before parsing. Variant and Filename are not accepted.

createEditor(text, options?)

createEditor parses text once and lets you queue edits against the nodes of that parse. apply() splices the edits into the original text. Nothing is reprinted, so everything outside the edited node ranges (comments, odd spacing, \r\n line endings, multibyte characters) comes back exactly as it went in.

import { createEditor } from 'sh-codemod';
import { walk } from 'sh-ast';

// Codemod: replace the non-portable `which` with `command -v`, and add `set -eu` on top.
const source =
  '#!/bin/sh\n# find 🎉 tools\nwhich   git  # where?\nwhich 你好\n';

const editor = createEditor(source);

walk(editor.ast, (node) => {
  if (node?.Type === 'CallExpr') {
    const command = node.Args?.[0];
    const first = command?.Parts?.[0];
    if (command && first?.Type === 'Lit' && first.Value === 'which') {
      editor.replaceNode(command, 'command -v');
    }
  }
  return true;
});

const firstStatement = editor.ast.Stmts?.[0];
if (firstStatement) editor.insertBefore(firstStatement, 'set -eu\n');

export const result = editor.apply();
// '#!/bin/sh\n# find 🎉 tools\nset -eu\ncommand -v   git  # where?\ncommand -v 你好\n'

The editor is { ast, replaceNode, insertBefore, apply }:

Member Meaning
ast The parsed File, typed by sh-ast. Walk it with sh-ast's walk to find nodes.
replaceNode(node, newText) Queue replacing the node's source text.
insertBefore(node, text) Queue inserting text immediately before the node's first character.
apply() Return the original text with all queued edits applied. May be called again after queuing more.

options are { dialect?: LangVariant, filename?: string }, with Bash as the default. Comments are always kept. Removed parser-option spellings are rejected. A parse failure throws the sh-ast error unchanged. Numeric variant refusals also pass through unchanged.

Edit rules

Edits are placed by their position in the original text, not by the order you queued them.

  • Adjacent edits (one ends exactly where the next begins) are both applied.
  • Insertions at one position appear in the order insertBefore was called.
  • An insertion at the start of a replaced node comes before the replacement, whichever you queued first. An insertion at the end of a replaced node (that is, before the node that follows it) comes after the replacement.
  • Overlapping edits throw. Two replacements of the same node, a node and its ancestor, or an insertion strictly inside a replaced node make apply() throw EditOverlapError, with the conflicting pair on first and second and the stable code 'SH_CODEMOD_EDIT_OVERLAP'. No partial text is returned.
  • Foreign nodes are rejected. replaceNode and insertBefore throw ForeignNodeError (code 'SH_CODEMOD_EDIT_FOREIGN_NODE') for a node that did not come from this editor's own parse, including one from another createEditor call over the same text, and a structuredClone of a node. A value that is not a node at all (for example undefined) throws InvalidNodeError ('SH_CODEMOD_EDIT_INVALID_NODE').
Ranges

Ranges are UTF-16 indices into the string you passed, the same units as ESLint ranges and String#slice, so they are correct after emoji, CJK text and combining marks. A File spans from its first to its last token. A Stmt replacement starts after its leading comments and preserves its terminator (;, &, or the dialect equivalent). When replacement text ends in the same parsed terminator, it supplies that terminator once. If its here-document body follows that terminator, keep the redirect in the replacement header to retain the association.

A word that ends a \r\n line is edited without its \r. A here-document body replacement ends before its verified closing delimiter. When the parser's positions do not give a safe bound, replaceNode throws RangeError with code SH_CODEMOD_EDIT_RANGE. A replacement of the whole redirect uses its full parser range, including its closing delimiter.

Limits
  • The result is not re-parsed. If you need to know a codemod produced valid shell, parse the output (for example with createEditor(result)).
  • For comments on statements, case items and array elements, use the original objects in their Comments arrays. sh-ast's walk returns copies of those comments, which produce ForeignNodeError if passed to the editor.

Differences from prettier-plugin-sh

prettier-plugin-sh formats shell through the same mvdan/sh printer, behind Prettier. This package calls the printer directly, so there is no Prettier dependency and the printer options version-lock to the sh-ast this package pins. Compared with its documented options (v0.20):

OX Radar and Response Center

Find threats in your stack.

OX Radar can check high-priority threats, like critical package CVEs, against your context.

Each incident is marked Detected or Not Detected with a remediation plan and proof all tracked in the Response Center.

Where it’s listed

The probe returned only these fields for this server — auth requirement, protocol and tool list weren’t observed, so they’re not shown (never guessed).

  • npm sh-codemod

References

The publisher’s own links, as the registry reports them. These are not sources for the assessment on this page.

Powered by Read the latest findings

Scan your whole stack

Group 1261154050 1
Group 1261154050
 

From OX Research Newsroom

Plug and Pray: Your AI Agents Are Taking Orders From Strangers
Research

Plug and Pray: Your AI Agents Are Taking Orders From Strangers

Cry2Wolf: How to Tell a Real Bug from a Nothingburger
AI & VibeSec

Cry2Wolf: Not Every Branded Bug Deserves a Fire Drill

CVE

Java4Shell (CVE-2026-114938): Easy to Crash, Hard to Exploit — Less Than 0.12% of JVMs Estimated at Risk of RCE

Frame 2085668439 (1)
Group 1261154229