From 41b05582cc8d9651573cd45d714ac46e2053c5a3 Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Mon, 12 Oct 2026 15:25:29 +0200 Subject: [PATCH] fix(shared): declare runtime dependencies and keep tests out of the tarball @claude-flow/shared 3.0.1-3.0.3 declare only sql.js, but the compiled code imports zod (core/config) and express, cors, helmet and ws (mcp transports). They sat in devDependencies, so a clean `npm i @claude-flow/shared` cannot load `.` or `./core` (Cannot find package 'zod') or `./mcp` (Cannot find package 'express'). ruflo users never saw it because @claude-flow/cli declares the same packages and npm hoists them. - Move zod, express, cors, helmet and ws to dependencies, with ranges that overlap what @claude-flow/cli declares so a CLI install can dedupe them. express is bounded to `^4.22.2 || ^5.0.0` (the patched 4.x floor the repo overrides to, and the 5.x the workspace runs) instead of an open `>=`. - Move @types/ws to dependencies: dist/mcp/transport/websocket.d.ts imports `ws`, so a consumer type-checking with skipLibCheck off hit TS7016. - Exclude *.test.ts / *.spec.ts / __tests__ from the build, and negate them in `files` so a stale local dist (composite builds do not clear old outputs) cannot ship them either. 3.0.3 ships 6 compiled tests that import vitest. - HttpTransport: read `req.body ?? {}`. Under Express 5 a POST /rpc with no JSON body left req.body undefined and answered 500 instead of the JSON-RPC 400. Malformed JSON (body-parser's entity.parse.failed) now answers 400 / -32700 Parse error instead of 500 / -32603 Internal error, under Express 4 and 5. - Lockfile: only the shared importer block moves; ws 8.19.0 was referenced by nothing else and is dropped. `pnpm@8.15.0 install --frozen-lockfile` passes. - Tests: __tests__/package-manifest.test.ts scans src/ with the TypeScript AST (type-only imports erased, comments/strings ignored) and fails on an undeclared runtime import, a missing @types/ws, or removed test exclusions; __tests__/mcp/http-transport-body.test.ts (transport bound to port 0) covers the bodiless POST and malformed JSON. Every mutant (zod, express, @types/ws, spec negation, tsconfig exclude, each HTTP fix reverted) is caught. Verified: npm pack + clean `npm i ` imports all 9 exports subpaths (origin/main and registry 3.0.3 fail on 3 of them) and ships no test files; HTTP /health 200 and a WebSocket connect work under express 5.3.0 and 4.22.3; a consumer tsc with skipLibCheck off reports 0 errors; shared tests pass; the CI recursive build and the CLI type-check pass. Not included: the version bump and the CLI's exact `@claude-flow/shared` pin, which belong to the release. --- .../__tests__/mcp/http-transport-body.test.ts | 52 +++++++ .../shared/__tests__/package-manifest.test.ts | 128 ++++++++++++++++++ v3/@claude-flow/shared/package.json | 19 +-- .../shared/src/mcp/transport/http.ts | 12 +- v3/@claude-flow/shared/tsconfig.json | 2 +- v3/pnpm-lock.yaml | 48 +++---- 6 files changed, 221 insertions(+), 40 deletions(-) create mode 100644 v3/@claude-flow/shared/__tests__/mcp/http-transport-body.test.ts create mode 100644 v3/@claude-flow/shared/__tests__/package-manifest.test.ts diff --git a/v3/@claude-flow/shared/__tests__/mcp/http-transport-body.test.ts b/v3/@claude-flow/shared/__tests__/mcp/http-transport-body.test.ts new file mode 100644 index 0000000000..0c01edef7c --- /dev/null +++ b/v3/@claude-flow/shared/__tests__/mcp/http-transport-body.test.ts @@ -0,0 +1,52 @@ +/** + * HTTP transport request-body handling + * + * Express 5 leaves req.body undefined when no JSON body is parsed (Express 4 + * gave {}), and body-parser reports malformed JSON through the error handler. + * Both are the client's JSON-RPC errors (400), not internal errors (500). + * + * @module v3/shared/__tests__/mcp/http-transport-body.test + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import type { Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { HttpTransport } from '../../src/mcp/transport/http.js'; + +const logger = { debug() {}, info() {}, warn() {}, error() {} }; + +describe('HttpTransport request body', () => { + // Port 0: the transport's own server takes a free port, so nothing can claim it in between. + const transport = new HttpTransport(logger as never, { host: '127.0.0.1', port: 0 }); + let base = ''; + + beforeAll(async () => { + await transport.start(); + const server = (transport as unknown as { server: Server }).server; + base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + }); + + afterAll(async () => { + await transport.stop(); + }); + + const rpc = (init: RequestInit) => fetch(`${base}/rpc`, { method: 'POST', ...init }); + + it('answers a POST /rpc without a JSON body with a JSON-RPC 400', async () => { + const res = await rpc({}); + expect(res.status).toBe(400); + expect(await res.json()).toMatchObject({ jsonrpc: '2.0', id: null, error: { code: -32600 } }); + }); + + it('answers malformed JSON with a JSON-RPC parse error (400, -32700)', async () => { + const res = await rpc({ headers: { 'content-type': 'application/json' }, body: '{bad' }); + expect(res.status).toBe(400); + expect(await res.json()).toMatchObject({ jsonrpc: '2.0', id: null, error: { code: -32700 } }); + }); + + it('still answers a well-formed request that names the wrong version with a 400', async () => { + const res = await rpc({ headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '1.0', id: 7, method: 'x' }) }); + expect(res.status).toBe(400); + expect(await res.json()).toMatchObject({ id: 7, error: { code: -32600 } }); + }); +}); diff --git a/v3/@claude-flow/shared/__tests__/package-manifest.test.ts b/v3/@claude-flow/shared/__tests__/package-manifest.test.ts new file mode 100644 index 0000000000..270bf597ac --- /dev/null +++ b/v3/@claude-flow/shared/__tests__/package-manifest.test.ts @@ -0,0 +1,128 @@ +/** + * Package manifest tests + * + * The published tarball is installed without the workspace, so every package + * the compiled code imports at runtime must be declared in `dependencies`. + * 3.0.1–3.0.3 declared only sql.js: `@claude-flow/shared` and `/core` failed + * with "Cannot find package 'zod'" and `/mcp` with "Cannot find package 'express'". + * + * @module v3/shared/__tests__/package-manifest.test + */ + +import { describe, it, expect } from 'vitest'; +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import { isBuiltin } from 'node:module'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; + +const root = join(dirname(fileURLToPath(import.meta.url)), '..'); +const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); +const tsconfig = JSON.parse(readFileSync(join(root, 'tsconfig.json'), 'utf8')); + +const isTestFile = (path: string) => /\.(test|spec)\.ts$/.test(path) || path.includes('__tests__'); + +function sourceFiles(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + if (statSync(path).isDirectory()) return sourceFiles(path); + return path.endsWith('.ts') && !path.endsWith('.d.ts') && !isTestFile(path) ? [path] : []; + }); +} + +const packageName = (spec: string) => (spec.startsWith('@') ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0]); + +/** Bare specifiers that survive compilation: type-only imports and exports are erased, as tsc erases them. */ +function runtimeSpecifiers(source: string, fileName = 'x.ts'): string[] { + const file = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true); + const found: string[] = []; + const add = (node: ts.Expression | undefined) => { + if (node && ts.isStringLiteralLike(node)) found.push(node.text); + }; + const visit = (node: ts.Node) => { + if (ts.isImportDeclaration(node)) { + const clause = node.importClause; + const bindings = clause?.namedBindings; + const onlyTypes = + clause !== undefined && + (clause.isTypeOnly || + (!clause.name && bindings !== undefined && ts.isNamedImports(bindings) && bindings.elements.length > 0 && bindings.elements.every((e) => e.isTypeOnly))); + if (!onlyTypes) add(node.moduleSpecifier); + } else if (ts.isExportDeclaration(node)) { + const clause = node.exportClause; + const onlyTypes = node.isTypeOnly || (clause !== undefined && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((e) => e.isTypeOnly)); + if (!onlyTypes) add(node.moduleSpecifier); + } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) { + add(node.arguments[0]); + } else if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly && ts.isExternalModuleReference(node.moduleReference)) { + add(node.moduleReference.expression); + } + ts.forEachChild(node, visit); + }; + visit(file); + return found.filter((s) => !s.startsWith('.') && !isBuiltin(s)).map(packageName); +} + +describe('runtimeSpecifiers', () => { + it('finds every runtime import form', () => { + const source = [ + "import a from 'default-import';", + "import * as b from 'namespace-import';", + "import {\n c,\n d,\n} from 'multi-line';", + "import 'side-effect';", + "const x = 1; export * from 'star-reexport';", + "export { e } from 'named-reexport';", + "import { type F, g } from 'mixed-type-and-value';", + "const h = await import(/* note */ 'dynamic');", + "import i = require('import-equals');", + "import j from '@scope/pkg/sub/path';", + ].join('\n'); + expect(runtimeSpecifiers(source)).toEqual([ + 'default-import', 'namespace-import', 'multi-line', 'side-effect', 'star-reexport', + 'named-reexport', 'mixed-type-and-value', 'dynamic', 'import-equals', '@scope/pkg', + ]); + }); + + it('ignores what tsc erases or never resolves', () => { + const source = [ + "import type { A } from 'type-only';", + "import { type B } from 'inline-type-only';", + "export type { C } from 'type-reexport';", + "// import d from 'line-comment';", + "/* import e from 'block-comment'; */", + "const t = `import f from 'template-text'`;", + "const s = '/* import g from \"string-text\" */';", + "import fs from 'fs'; import p from 'node:path'; import w from 'worker_threads';", + "import local from './local.js';", + ].join('\n'); + expect(runtimeSpecifiers(source)).toEqual([]); + }); +}); + +describe('@claude-flow/shared package manifest', () => { + const imports = new Map(); + for (const file of sourceFiles(join(root, 'src'))) { + for (const name of runtimeSpecifiers(readFileSync(file, 'utf8'), file)) { + if (!imports.has(name)) imports.set(name, file.slice(root.length + 1)); + } + } + + it('declares every package imported at runtime by src/ in dependencies', () => { + const declared = new Set(Object.keys(pkg.dependencies ?? {})); + const missing = [...imports].filter(([name]) => name !== pkg.name && !declared.has(name)); + expect(Object.fromEntries(missing)).toEqual({}); + }); + + it('finds the imports this guard exists for (the scan is not vacuous)', () => { + for (const name of ['zod', 'express', 'ws', 'sql.js']) expect(imports.has(name)).toBe(true); + }); + + it('declares @types/ws for consumers, because dist/mcp/transport/websocket.d.ts imports ws', () => { + expect(Object.keys(pkg.dependencies ?? {})).toContain('@types/ws'); + }); + + it('keeps test files out of the build and the tarball', () => { + expect(tsconfig.exclude).toEqual(expect.arrayContaining(['src/**/*.test.ts', 'src/**/*.spec.ts', 'src/**/__tests__/**'])); + expect(pkg.files).toEqual(expect.arrayContaining(['dist', '!dist/**/*.test.*', '!dist/**/*.spec.*', '!dist/**/__tests__'])); + }); +}); diff --git a/v3/@claude-flow/shared/package.json b/v3/@claude-flow/shared/package.json index ae553ea8b1..757ed09df0 100644 --- a/v3/@claude-flow/shared/package.json +++ b/v3/@claude-flow/shared/package.json @@ -18,6 +18,9 @@ }, "files": [ "dist", + "!dist/**/*.test.*", + "!dist/**/*.spec.*", + "!dist/**/__tests__", "README.md" ], "scripts": { @@ -25,20 +28,20 @@ "build": "tsc" }, "dependencies": { - "sql.js": "^1.10.3" + "@types/ws": "^8.5.10", + "cors": "^2.8.5", + "express": "^4.22.2 || ^5.0.0", + "helmet": "^7.2.0", + "sql.js": "^1.10.3", + "ws": "^8.21.0", + "zod": "^3.22.4" }, "devDependencies": { "@types/cors": "^2.8.17", "@types/express": "^4.17.21", "@types/node": "^20.0.0", "@types/sql.js": "^1.4.9", - "@types/ws": "^8.5.10", - "cors": "^2.8.5", - "express": "^4.21.0", - "helmet": "^7.1.0", - "vitest": "^4.1.0", - "ws": "^8.16.0", - "zod": "^3.22.4" + "vitest": "^4.1.0" }, "publishConfig": { "access": "public" diff --git a/v3/@claude-flow/shared/src/mcp/transport/http.ts b/v3/@claude-flow/shared/src/mcp/transport/http.ts index 55f340e43a..c38d8317e0 100644 --- a/v3/@claude-flow/shared/src/mcp/transport/http.ts +++ b/v3/@claude-flow/shared/src/mcp/transport/http.ts @@ -330,6 +330,15 @@ export class HttpTransport extends EventEmitter implements ITransport { // Error handler this.app.use((err: Error, req: Request, res: Response, next: NextFunction) => { + // body-parser marks a malformed JSON body: that is the client's JSON-RPC parse error, not ours. + if ((err as { type?: string }).type === 'entity.parse.failed') { + res.status(400).json({ + jsonrpc: '2.0', + id: null, + error: { code: -32700, message: 'Parse error' }, + }); + return; + } this.logger.error('Express error', { error: err }); this.errors++; res.status(500).json({ @@ -402,7 +411,8 @@ export class HttpTransport extends EventEmitter implements ITransport { this.logger.warn('No authentication configured - running in development mode'); } - const message = req.body; + // Express 5 leaves req.body undefined when no JSON body was parsed (Express 4 gave {}). + const message = req.body ?? {}; // Validate JSON-RPC format if (message.jsonrpc !== '2.0') { diff --git a/v3/@claude-flow/shared/tsconfig.json b/v3/@claude-flow/shared/tsconfig.json index b813d42868..3d77742b69 100644 --- a/v3/@claude-flow/shared/tsconfig.json +++ b/v3/@claude-flow/shared/tsconfig.json @@ -5,5 +5,5 @@ "rootDir": "./src" }, "include": ["src/**/*"], - "exclude": ["node_modules", "dist"] + "exclude": ["node_modules", "dist", "src/**/*.test.ts", "src/**/*.spec.ts", "src/**/__tests__/**"] } diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yaml index 82036ff790..ed14e60393 100644 --- a/v3/pnpm-lock.yaml +++ b/v3/pnpm-lock.yaml @@ -625,9 +625,27 @@ importers: '@claude-flow/shared': dependencies: + '@types/ws': + specifier: ^8.5.10 + version: 8.18.1 + cors: + specifier: ^2.8.5 + version: 2.8.5 + express: + specifier: '>=4.22.2' + version: 5.2.1 + helmet: + specifier: ^7.2.0 + version: 7.2.0 sql.js: specifier: ^1.10.3 version: 1.13.0 + ws: + specifier: ^8.21.0 + version: 8.21.1 + zod: + specifier: ^3.22.4 + version: 3.25.76 devDependencies: '@types/cors': specifier: ^2.8.17 @@ -641,27 +659,9 @@ importers: '@types/sql.js': specifier: ^1.4.9 version: 1.4.9 - '@types/ws': - specifier: ^8.5.10 - version: 8.18.1 - cors: - specifier: ^2.8.5 - version: 2.8.5 - express: - specifier: '>=4.22.2' - version: 5.2.1 - helmet: - specifier: ^7.1.0 - version: 7.2.0 vitest: specifier: '>=4.1.0' version: 4.1.8(@opentelemetry/api@1.9.1)(@types/node@20.19.27)(@vitest/coverage-v8@4.1.9)(vite@7.3.0) - ws: - specifier: ^8.16.0 - version: 8.19.0 - zod: - specifier: ^3.22.4 - version: 3.25.76 '@claude-flow/swarm': devDependencies: @@ -13566,18 +13566,6 @@ packages: optional: true dev: false - /ws@8.19.0: - resolution: {integrity: sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==} - engines: {node: '>=10.0.0'} - peerDependencies: - bufferutil: ^4.0.1 - utf-8-validate: '>=5.0.2' - peerDependenciesMeta: - bufferutil: - optional: true - utf-8-validate: - optional: true - dev: true /ws@8.20.0: resolution: {integrity: sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==}