mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 00:05:27 +00:00
fix(hooks): include module extensions in edit and Stop checks
This commit is contained in:
1 parent
8abdf329ec
commit
d96596b4e0
5 files changed
+182
-7
No files matched your search
@@ -36,7 +36,7 @@ function getAccumFile(rawSessionId) {
|
||||
* @param {string} rawInput - Raw JSON string from stdin
|
||||
* @returns {string} The original input (pass-through)
|
||||
*/
|
||||
const JS_TS_EXT = /\.(ts|tsx|js|jsx)$/;
|
||||
const JS_TS_EXT = /\.(?:[cm]?[jt]s|[jt]sx)$/;
|
||||
|
||||
function appendPath(filePath, sessionId) {
|
||||
if (filePath && JS_TS_EXT.test(filePath)) {
|
||||
|
||||
@@ -39,7 +39,7 @@ function run(rawInput) {
|
||||
const input = JSON.parse(rawInput);
|
||||
const filePath = input.tool_input?.file_path;
|
||||
|
||||
if (filePath && /\.(ts|tsx|js|jsx)$/.test(filePath)) {
|
||||
if (filePath && /\.(?:[cm]?[jt]s|[jt]sx)$/.test(filePath)) {
|
||||
try {
|
||||
const resolvedFilePath = path.resolve(filePath);
|
||||
const projectRoot = findProjectRoot(path.dirname(resolvedFilePath));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* PostToolUse Hook: TypeScript check after editing .ts/.tsx files
|
||||
* PostToolUse Hook: TypeScript check after editing .ts/.tsx/.mts/.cts files
|
||||
*
|
||||
* Cross-platform (Windows, macOS, Linux)
|
||||
*
|
||||
@@ -56,7 +56,7 @@ if (require.main === module) {
|
||||
const input = JSON.parse(data);
|
||||
const filePath = input.tool_input?.file_path;
|
||||
|
||||
if (filePath && /\.(ts|tsx)$/.test(filePath)) {
|
||||
if (filePath && /\.(?:[cm]?ts|tsx)$/.test(filePath)) {
|
||||
const resolvedPath = path.resolve(filePath);
|
||||
if (!fs.existsSync(resolvedPath)) {
|
||||
process.stdout.write(data, () => process.exit(0));
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* Reads the accumulator written by post-edit-accumulator.js and processes all
|
||||
* edited files in one pass: groups files by project root for a single formatter
|
||||
* invocation per root, and groups .ts/.tsx files by tsconfig dir for a single
|
||||
* invocation per root, and groups .ts/.tsx/.mts/.cts files by tsconfig dir for a single
|
||||
* tsc --noEmit per tsconfig. The accumulator is cleared on read so repeated
|
||||
* Stop calls do not double-process files.
|
||||
*
|
||||
@@ -204,7 +204,7 @@ function main(sessionId) {
|
||||
|
||||
const byProjectRoot = new Map();
|
||||
for (const filePath of files) {
|
||||
if (!/\.(ts|tsx|js|jsx)$/.test(filePath)) continue;
|
||||
if (!/\.(?:[cm]?[jt]s|[jt]sx)$/.test(filePath)) continue;
|
||||
if (isPluginClonePath(filePath)) continue;
|
||||
const resolved = path.resolve(filePath);
|
||||
if (!fs.existsSync(resolved)) continue;
|
||||
@@ -215,7 +215,7 @@ function main(sessionId) {
|
||||
|
||||
const byTsConfigDir = new Map();
|
||||
for (const filePath of files) {
|
||||
if (!/\.(ts|tsx)$/.test(filePath)) continue;
|
||||
if (!/\.(?:[cm]?ts|tsx)$/.test(filePath)) continue;
|
||||
if (isPluginClonePath(filePath)) continue;
|
||||
const resolved = path.resolve(filePath);
|
||||
if (!fs.existsSync(resolved)) continue;
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const vm = require('vm');
|
||||
const { EventEmitter } = require('events');
|
||||
const { createRequire } = require('module');
|
||||
|
||||
const extensions = ['js', 'jsx', 'ts', 'tsx', 'mjs', 'cjs', 'mts', 'cts'];
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
|
||||
function fixture() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-module-hooks-'));
|
||||
fs.writeFileSync(path.join(root, 'package.json'), '{}');
|
||||
fs.writeFileSync(path.join(root, '.prettierrc'), '{}');
|
||||
fs.writeFileSync(path.join(root, 'tsconfig.json'), '{}');
|
||||
const bin = path.join(root, 'node_modules', '.bin');
|
||||
fs.mkdirSync(bin, { recursive: true });
|
||||
fs.writeFileSync(path.join(bin, process.platform === 'win32' ? 'prettier.cmd' : 'prettier'), '');
|
||||
const files = extensions.map(extension => path.join(root, `source.${extension}`));
|
||||
for (const file of files) fs.writeFileSync(file, 'export const value = 1;\n');
|
||||
return { root, files };
|
||||
}
|
||||
|
||||
function invokeHook(name, root, input, options = {}) {
|
||||
const filename = path.resolve(__dirname, '../../scripts/hooks', `${name}.js`);
|
||||
const actualRequire = createRequire(filename);
|
||||
const module = { exports: {} };
|
||||
const calls = [];
|
||||
let output = '';
|
||||
let diagnostics = '';
|
||||
const execute = (bin, args, spawnOptions) => {
|
||||
calls.push({ bin, args: Array.from(args), cwd: spawnOptions.cwd });
|
||||
if (args[0] === 'tsc') {
|
||||
const stdout = extensions.map(extension => `source.${extension}(1,1): error TS2322: Module diagnostic`).join('\n');
|
||||
throw Object.assign(new Error('Type check failed'), { stdout, stderr: '' });
|
||||
}
|
||||
if (options.formatterFails) throw new Error('Formatter failed');
|
||||
return Buffer.alloc(0);
|
||||
};
|
||||
const requireHook = request => {
|
||||
if (request === 'child_process') return {
|
||||
execFileSync: execute,
|
||||
spawnSync: (...args) => {
|
||||
try { execute(...args); return { status: 0 }; }
|
||||
catch (error) { return { status: 2, stdout: error.stdout, stderr: error.stderr }; }
|
||||
},
|
||||
};
|
||||
if (request === 'os') return { ...os, tmpdir: () => root, homedir: () => path.join(root, 'home') };
|
||||
if (request === '../lib/resolve-formatter' && options.platform === 'win32') return {
|
||||
...actualRequire(request),
|
||||
resolveFormatterBin: () => ({ bin: 'prettier.cmd', prefix: [] }),
|
||||
};
|
||||
return actualRequire(request);
|
||||
};
|
||||
const direct = name === 'post-edit-typecheck';
|
||||
requireHook.main = direct ? module : null;
|
||||
const stdin = new EventEmitter();
|
||||
stdin.setEncoding = () => {};
|
||||
const hookProcess = {
|
||||
...process, platform: options.platform || process.platform, cwd: () => root, stdin,
|
||||
stdout: { write: (text, done) => { output += text; if (done) done(); } },
|
||||
stderr: { write: text => { diagnostics += text; } },
|
||||
exit: () => {},
|
||||
};
|
||||
vm.runInNewContext(fs.readFileSync(filename, 'utf8'), {
|
||||
require: requireHook, module, process: hookProcess, Buffer,
|
||||
__filename: filename, __dirname: path.dirname(filename),
|
||||
console: { error: (...args) => { diagnostics += `${args.join(' ')}\n`; } },
|
||||
}, { filename });
|
||||
if (direct) {
|
||||
stdin.emit('data', input);
|
||||
stdin.emit('end');
|
||||
} else {
|
||||
output = module.exports.run(input);
|
||||
}
|
||||
assert.strictEqual(output, input, `${name} preserves its input`);
|
||||
return { calls, diagnostics };
|
||||
}
|
||||
|
||||
function test(name, run) {
|
||||
const data = fixture();
|
||||
try {
|
||||
run(data);
|
||||
passed++;
|
||||
console.log(` ✓ ${name}`);
|
||||
} catch (error) {
|
||||
failed++;
|
||||
console.error(` ✗ ${name}: ${error.message}`);
|
||||
} finally {
|
||||
fs.rmSync(data.root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test('Edit and MultiEdit accumulate all JS and TS module extensions', ({ root, files }) => {
|
||||
for (const file of files) invokeHook('post-edit-accumulator', root,
|
||||
JSON.stringify({ session_id: 'single', tool_input: { file_path: file } }));
|
||||
assert.deepStrictEqual(fs.readFileSync(path.join(root, 'ecc-edited-single.txt'), 'utf8').trim().split('\n'), files);
|
||||
const ignored = ['readme.md', 'source.mjs.map', 'source.mtsx'].map(name => path.join(root, name));
|
||||
invokeHook('post-edit-accumulator', root, JSON.stringify({
|
||||
session_id: 'multi', tool_input: { edits: [...files, ...ignored].map(file_path => ({ file_path })) },
|
||||
}));
|
||||
assert.deepStrictEqual(fs.readFileSync(path.join(root, 'ecc-edited-multi.txt'), 'utf8').trim().split('\n'), files);
|
||||
});
|
||||
|
||||
test('the direct formatter receives each module file', ({ root, files }) => {
|
||||
for (const file of files) {
|
||||
const { calls } = invokeHook('post-edit-format', root, JSON.stringify({ tool_input: { file_path: file } }));
|
||||
assert.strictEqual(calls.length, 1, `formatter invocation for ${path.basename(file)}`);
|
||||
assert.deepStrictEqual(calls[0].args, ['--write', file]);
|
||||
assert.strictEqual(calls[0].cwd, root);
|
||||
}
|
||||
});
|
||||
|
||||
test('the direct typecheck reports mts and cts diagnostics and skips JavaScript files', ({ root, files }) => {
|
||||
for (const file of files) {
|
||||
const { calls, diagnostics } = invokeHook('post-edit-typecheck', root, JSON.stringify({ tool_input: { file_path: file } }));
|
||||
const isTypeScript = ['.ts', '.tsx', '.mts', '.cts'].includes(path.extname(file));
|
||||
assert.strictEqual(calls.length, isTypeScript ? 1 : 0, `typecheck invocation for ${path.basename(file)}`);
|
||||
if (isTypeScript) {
|
||||
assert.ok(diagnostics.includes(`TypeScript errors in ${path.basename(file)}:`));
|
||||
assert.ok(diagnostics.includes(`${path.basename(file)}(1,1): error TS2322`));
|
||||
} else assert.strictEqual(diagnostics, '');
|
||||
}
|
||||
});
|
||||
|
||||
test('the accumulator-to-Stop pipeline formats one batch and typechecks module files once', ({ root, files }) => {
|
||||
const plugin = path.join(root, '.claude', 'plugins', 'installed', 'source.mts');
|
||||
fs.mkdirSync(path.dirname(plugin), { recursive: true });
|
||||
fs.writeFileSync(plugin, 'export const value = 1;\n');
|
||||
invokeHook('post-edit-accumulator', root, JSON.stringify({
|
||||
session_id: 'batch', tool_input: { edits: [...files, files[0], plugin].map(file_path => ({ file_path })) },
|
||||
}));
|
||||
const { calls, diagnostics } = invokeHook('stop-format-typecheck', root, JSON.stringify({ session_id: 'batch' }));
|
||||
assert.strictEqual(calls.length, 2, 'one formatter and one tsc invocation');
|
||||
assert.deepStrictEqual(calls[0].args, ['--write', ...files]);
|
||||
assert.deepStrictEqual(calls[1].args, ['tsc', '--noEmit', '--pretty', 'false']);
|
||||
for (const extension of ['ts', 'tsx', 'mts', 'cts']) assert.ok(diagnostics.includes(`TypeScript errors in source.${extension}:`));
|
||||
for (const extension of ['js', 'jsx', 'mjs', 'cjs']) assert.ok(!diagnostics.includes(`TypeScript errors in source.${extension}:`));
|
||||
assert.ok(!fs.existsSync(path.join(root, 'ecc-edited-batch.txt')), 'Stop consumes the session accumulator');
|
||||
});
|
||||
|
||||
test('module extensions retain Windows formatter guards and batch diagnostic handling', ({ root, files }) => {
|
||||
const moduleFile = files.find(file => file.endsWith('.mjs'));
|
||||
const input = JSON.stringify({ tool_input: { file_path: moduleFile } });
|
||||
const formatted = invokeHook('post-edit-format', root, input, { platform: 'win32' });
|
||||
assert.strictEqual(formatted.calls.length, 1);
|
||||
assert.strictEqual(formatted.calls[0].bin, 'prettier.cmd');
|
||||
const failedFormatter = invokeHook('post-edit-format', root, input, { platform: 'win32', formatterFails: true });
|
||||
assert.strictEqual(failedFormatter.calls.length, 1, 'formatter failure remains non-blocking');
|
||||
|
||||
const unsafe = path.join(root, 'unsafe&module.mjs');
|
||||
fs.writeFileSync(unsafe, 'export const value = 1;\n');
|
||||
assert.strictEqual(invokeHook('post-edit-format', root,
|
||||
JSON.stringify({ tool_input: { file_path: unsafe } }), { platform: 'win32' }).calls.length, 0);
|
||||
fs.writeFileSync(path.join(root, 'ecc-edited-unsafe.txt'), `${unsafe}\n`);
|
||||
const guarded = invokeHook('stop-format-typecheck', root,
|
||||
JSON.stringify({ session_id: 'unsafe' }), { platform: 'win32' });
|
||||
assert.strictEqual(guarded.calls.length, 0);
|
||||
assert.ok(guarded.diagnostics.includes('unsafe path chars'));
|
||||
|
||||
const typed = files.filter(file => file.endsWith('.mts') || file.endsWith('.cts'));
|
||||
fs.writeFileSync(path.join(root, 'ecc-edited-typed.txt'), typed.join('\n'));
|
||||
const checked = invokeHook('stop-format-typecheck', root,
|
||||
JSON.stringify({ session_id: 'typed' }), { platform: 'win32' });
|
||||
assert.strictEqual(checked.calls.length, 2);
|
||||
assert.ok(checked.diagnostics.includes('TypeScript errors in source.mts:'));
|
||||
assert.ok(checked.diagnostics.includes('TypeScript errors in source.cts:'));
|
||||
});
|
||||
|
||||
console.log(`\nPassed: ${passed}, Failed: ${failed}`);
|
||||
process.exitCode = failed > 0 ? 1 : 0;
|
||||
Reference in new issue
Block a user