2026-02-12 10:21:59 -08:00
|
|
|
#!/usr/bin/env node
|
|
|
|
|
/**
|
|
|
|
|
* PostToolUse Hook: Auto-format JS/TS files with Prettier after edits
|
|
|
|
|
*
|
|
|
|
|
* Cross-platform (Windows, macOS, Linux)
|
|
|
|
|
*
|
|
|
|
|
* Runs after Edit tool use. If the edited file is a JS/TS file,
|
|
|
|
|
* formats it with Prettier. Fails silently if Prettier isn't installed.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
const { execFileSync } = require('child_process');
|
|
|
|
|
const fs = require('fs');
|
|
|
|
|
|
2026-02-12 13:40:14 -08:00
|
|
|
const MAX_STDIN = 1024 * 1024; // 1MB limit
|
2026-02-12 10:21:59 -08:00
|
|
|
let data = '';
|
|
|
|
|
|
|
|
|
|
process.stdin.on('data', chunk => {
|
2026-02-12 13:40:14 -08:00
|
|
|
if (data.length < MAX_STDIN) {
|
|
|
|
|
data += chunk;
|
|
|
|
|
}
|
2026-02-12 10:21:59 -08:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
process.stdin.on('end', () => {
|
|
|
|
|
try {
|
|
|
|
|
const input = JSON.parse(data);
|
|
|
|
|
const filePath = input.tool_input?.file_path;
|
|
|
|
|
|
2026-02-12 15:28:30 -08:00
|
|
|
if (filePath && /\.(ts|tsx|js|jsx)$/.test(filePath)) {
|
2026-02-12 10:21:59 -08:00
|
|
|
try {
|
|
|
|
|
execFileSync('npx', ['prettier', '--write', filePath], {
|
|
|
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
|
|
|
timeout: 15000
|
|
|
|
|
});
|
|
|
|
|
} catch {
|
2026-02-12 15:28:30 -08:00
|
|
|
// Prettier not installed, file missing, or failed — non-blocking
|
2026-02-12 10:21:59 -08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// Invalid input — pass through
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log(data);
|
|
|
|
|
});
|