typescript-script
Skill0 starsChanged 3 months agoMITView on GitHub
Write self-contained, portable, testable TypeScript command-line tools on Deno — pure-logic/side-effect separation (boundaries as interfaces) that `deno test` can drive with fakes, a Cliffy CLI, and a check/test/lint/fmt gate. Use as soon as the user wants a TypeScript (or JavaScript) script, CLI utility, automation tool, or "glue" code (orchestrating git, curl/fetch, file manipulation, parsing) in TS, even if they never say "Deno". Also triggers on adding tests to an existing TS tool, making one portable/testable, or porting a shell/Python script to TypeScript.
In this repository7 other files it gives its agents.
- go-scriptSkill
- kotlin-scriptSkill
- python-scriptSkill
- rust-scriptSkill
- scripteratopsSkill
- shell-scriptSkill
- swift-scriptSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 53
Prefer JSR (jsr:) packages.
- Very specific: line 205
Every tool ships co-located *_test.ts files, run by deno test.
- Distinctive: line 243
Delete what it doesn't earn.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
TypeScript script
Standard for all TypeScript command-line tools: a small Deno project whose
logic lives in testable src/ modules, driven by a thin Cliffy CLI in
main.ts, verified by deno check + deno test + deno lint + deno fmt.
The goal is a self-contained tool (no node_modules, one runtime that runs,
tests, lints, formats, and compiles) — the TypeScript counterpart of the
python-script, swift-script, and kotlin-script skills.
Three decisions are already settled. Don't second-guess them, apply them:
- Runtime → Deno. It runs
.tsdirectly (likeuv runruns.py), ships the test runner, linter, formatter, type-checker, and a single-binary compiler in the box, and needs nonode_modules. Bun and Node are viable but pull the batteries back apart (a separate formatter/linter, a bundler for a binary). - Interface → Cliffy (
@cliffy/command). - Tests →
deno test(Deno.test+@std/assert), made easy by an architecture that isolates side effects behind interfaces.
This file carries the decisions; the code implementing them is a complete,
gate-passing project in assets/template/. Copy and adapt that project — don't
retype it from here. Then delete what your tool doesn't earn.
1. Project layout
tool/
├── deno.json # tasks, imports (pinned), fmt/lint config, strict TS
├── deno.lock # integrity-pinned dependency graph (commit it)
├── main.ts # Cliffy CLI → thin entry point
├── src/
│ ├── errors.ts # ToolError subclasses (each carries its exit code)
│ ├── logic.ts # pure transform
│ ├── boundaries.ts # CommandRunner / HttpFetcher / EnvironmentReading interfaces
│ ├── config.ts # Config + precedence + JSON file read
│ ├── color.ts # ColorMode + shouldColor (pure)
│ ├── log.ts # net-verbosity → level; stderr logger
│ ├── runner.ts # Deno.Command subprocess boundary
│ ├── http.ts # fetch boundary
│ ├── work.ts # orchestration (doWork)
│ ├── signals.ts # SIGTERM → 143
│ └── *_test.ts # co-located deno tests
└── README.md- Pin every dependency in
deno.jsonimports(jsr:@cliffy/command@1.2.1,jsr:@std/assert@1.0.19) and commitdeno.lock(it records integrity hashes). Prefer JSR (jsr:) packages;npm:specifiers work when you need one. fetch, subprocess (Deno.Command), files, and env are built in — reach for a dependency only for a real gain. Cliffy is usually the only one.- JSON is the "free" config format (
JSON.parse); no dependency needed.
2. Structure
The structure is designed to make tests trivial: pure logic never touches the outside world directly. Everything that leaves the process (subprocess, network, filesystem, environment) sits behind an interface boundary, injected into the orchestration. Tests pass a fake implementation; production passes the real one.
- Boundaries are interfaces —
CommandRunner,HttpFetcher,EnvironmentReading. These are the single mock hooks. A fake is a small class. - Pure logic (
transform) — input → output, no I/O, tested withassertEquals. - Config is an
interface; precedence is one pure function,resolveConfig(cli, environment, file), tested without any fake. - Orchestration (
doWork) assembles boundary calls + pure logic: data positional, behaviour flags with defaults, returns a count. It takes the boundaries as interfaces, so a test drives it with no process and no socket. main.tsis thin: parse arguments, build the real boundaries, calldoWork, map errors to an exit code. Nothing worth testing lives here.
2.1 Async is the norm
Deno's I/O is promise-based, so the subprocess boundary, HTTP boundary, config
read, and doWork are all async. Keep pure logic synchronous — only the
boundaries and the orchestration that awaits them are async.
2.2 Subprocess boundary
ProcessRunner routes all subprocess calls through Deno.Command:
- Never a shell. Pass the program + an args array — no
sh -c, so no injection from a filename or argument. - Always a timeout. Pass
signal: AbortSignal.timeout(ms); on deadline Deno kills the child and.output()resolves (success: false,signal: "SIGTERM") — it does not throw. Checksignal.abortedafter the call (keep a reference to the signal) and throwTimeoutError(exit 124) yourself; otherwise a timeout falls through to the non-zero-exit path and surfaces as a generic exit 1. - On non-zero exit, throw
CommandError(command, code, stderr).
2.3 Config and precedence
Resolve settings with an explicit, documented precedence — higher wins:
CLI flags > environment variables > config file > built-in defaultsresolveConfig is pure (??-chains the layers so an absent value never clobbers
a lower layer). Each source is read by one boundary — readConfigFile (JSON),
configFromEnvironment (through the EnvironmentReading hook). Secrets get no
CLI flag (argv is world-readable via ps); a token comes from the environment
or config file. Never log a raw Config — route it through redacted(…).
2.4 HTTP requests
FetchClient wraps the global fetch in one boundary:
- Set an explicit timeout with
AbortSignal.timeout(ms). - Raise on non-2xx yourself.
fetchonly rejects on transport failure, not on 4xx/5xx, so checkresponse.okand throwHttpError; cancel the body first to avoid a leak. - Inject a fake
HttpFetcherto test offline.
2.5 Colorized logging
Logging uses the template's own Log, constructed once in main.ts and
writing to stderr (never stdout — stdout is for program data). Color:
shouldColor(mode, isTty, env)is a pure decision — precedence--color=always/never>NO_COLOR/FORCE_COLOR> TTY (and notTERM=dumb).- TTY detection in
main.tsusesDeno.stderr.isTerminal().
2.6 Robustness, signals & permissions
- Bound every subprocess and HTTP call with a timeout (§2.2, §2.4).
- Signals:
SIGTERM → Deno.exit(143)(installed insignals.ts); SIGINT keeps Deno's default (130). Deno surfaces a closed downstream pipe as a write error, not a SIGPIPE kill — no handler needed. - Permissions are the Deno-specific bit. Deno is deny-by-default: the tool
needs
--allow-run(subprocess),--allow-net(fetch),--allow-env, and--allow-read(config +ls). Thedeno.jsontasksencode these, anddeno compilebakes them into the binary. Grant only what the tool earns. - Preflight external tools for glue scripts (a
which-style check up front), throwingConfigErrorlisting every missing tool.
2.7 Subcommands (if needed)
Cliffy handles this natively: a root Command with .command("name", subCmd),
each its own Command. No manual dispatch.
2.8 Man page (optional)
Cliffy has no built-in man generator. Generate one from the CLI's own --help
with help2man:
help2man --no-info --name "tool" "./tool" > tool.1
sudo install -m 644 tool.1 /usr/local/share/man/man1/tool.1(Compile the binary first — §2.9 — so help2man can invoke it.)
2.9 Build & install (optional, for tools you distribute)
The README carries the environment set-up, not just the gates: a
Prerequisites section with per-platform install of Deno (macOS/Linux/Windows)
and the dependency list, pointing to deno.json + deno.lock as the pinned
source. For a distributed binary (deno compile), an optional --dependencies
flag printing the pinned versions is a nice touch — skip it for source-run tools.
- Single binary:
deno task compilerunsdeno compile … -o tool main.ts→ one self-contained executable with the permissions baked in; no runtime needed afterwards. Install it onto PATH (install -m 755 tool ~/.local/bin/). - Run from source:
deno task run <args>(no build step, likeuv run). - Limits: the compiled binary is per-OS — compile on each platform (or use
deno compile --targetto cross-compile).
3. CLI contract
Cliffy gives most of the baseline for free:
-h/--helpand-V/--versionare automatic (.version("…")).- Verbosity:
.option("-v, --verbose", …, { collect: true })collects occurrences into an array;.lengthis the count (same forquiet). Map the net count to a level withlogLevelForVerbosity(verbose - quiet). --coloris anEnumType(["auto","always","never"])option with a default.--dry-runshort-circuits before output, announced at warning level.- Group the help once flags pile up (the same rule as the other skills):
.group("Config sources")/.group("Behaviour")/.group("General")before each block; Cliffy renders each as its own--helpheading. - Stream discipline: program data → stdout (
console.log); logs, progress, diagnostics → stderr (theLog).
Exit codes
Map typed errors to a code in main.ts's catch (Deno.exit(e.exitCode)):
| Code | Meaning |
0 | Success (also --help/--version) |
1 | Runtime error (a ToolError); Cliffy also uses non-zero for usage errors |
124 | A subprocess exceeded its timeout (TimeoutError) |
130 | Interrupted — SIGINT / Ctrl-C (Deno default) |
143 | Terminated — SIGTERM / kill (signals.ts) |
ToolError.exitCode keeps the code with the failure category. As with Clikt,
Cliffy maps usage errors to its own non-zero default rather than the 2 of
argparse/ArgumentParser.
4. Tests with deno test
Every tool ships co-located *_test.ts files, run by deno test.
- Never test subprocess or network for real — inject a fake implementing the boundary interface. That's what the interface is for.
- Fakes are tiny classes (
class FakeRunner implements CommandRunner), not a mocking framework. ReturnPromise.resolve(…)— don't mark themasyncwithout anawait(deno lint'srequire-awaitflags that). - Pure logic and precedence are tested by direct call — no fakes at all.
- Assert with
@std/assert(assertEquals,assert,assertFalse).
Coverage priority: pure logic and orchestration first, then config precedence, then arg parsing.
5. Quality gates
Four gates, all one tool — no separate type checker, linter, or formatter to install:
deno check main.ts # types (uses tsc under the hood; the type gate)
deno test <perms> # deno test
deno lint # lint
deno fmt --check # format(The template wraps these as deno task check|test|lint|fmt:check.) Notes:
- A first run downloads and caches the pinned deps — slow once, then cached.
- Indentation is 2-space (
deno fmtdefault; set indeno.json). deno testtype-checks the test files too;deno check main.tscoverssrc/.
Summary of what to produce
Faced with a TypeScript tool request, produce:
- A Deno project copied from
assets/template/: logic + boundaries insrc/, a thin Cliffymain.ts, pinneddeno.json/deno.lock, the §2 structure, the §3 CLI contract and exit codes, and the robustness rules the tool's job earns (shelling out earns the timeout + preflight; the network earns the HTTP boundary + timeout; holding config/secrets earns precedence + redaction). Delete what it doesn't earn. - Co-located
*_test.tscovering pure logic, config precedence, orchestration (with fakes), and any boundary the tool ships. - In one line: how to run it (
deno task run <args>), and that the four gates —check+test+lint+fmt:check— are green (needs only Deno).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

