diff --git a/packages/mcp-server/src/tools.test.ts b/packages/mcp-server/src/tools.test.ts index d9e1149..f2d4c15 100644 --- a/packages/mcp-server/src/tools.test.ts +++ b/packages/mcp-server/src/tools.test.ts @@ -1,6 +1,8 @@ import { describe, it, expect } from "vitest"; import { validateSyntaxPure, detectPathDoubling, detectPathDoublingInfo, extractSignatures, safeHandler, computePartsLine, computeEffectiveMeshQuality, formatCollisionPairs, formatSweepCollisions, formatLastScreenshotLine, registerTools, getVersionTag, getViewerStatus, formatViewerBlock, partExtendsBelowBed, formatStatusText, workspaceMismatchWarning, type CollisionEntry, type SweepCollisionEntry } from "./tools.js"; import type { EngineStatus } from "./engine.js"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; // --------------------------------------------------------------------------- // Bug #6 — validate_syntax must trust .method() calls whose receiver was @@ -98,6 +100,157 @@ describe("validateSyntaxPure — stdlib whitelisting", () => { }); }); +// --------------------------------------------------------------------------- +// validate_syntax reported "unknown method(s)" for valid code that renders +// fine: built-in globals (`Math.cos`) and finder callbacks +// (`(e) => e.inDirection("Y")`). Real typos must still be flagged. +// --------------------------------------------------------------------------- + +describe("validateSyntaxPure — built-in globals and finder methods", () => { + it("does not warn on Math.cos / Math.sin", () => { + const code = [ + `import { makeCylinder } from "replicad";`, + `export default function main() {`, + ` const angle = Math.PI / 6;`, + ` const x = 20 * Math.cos(angle);`, + ` const y = 20 * Math.sin(angle);`, + ` return makeCylinder(5, 10).translate([x, y, 0]);`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).not.toMatch(/unknown method/i); + }); + + it("does not warn on an EdgeFinder callback (fillet + inDirection)", () => { + const code = [ + `import { makeBox } from "replicad";`, + `export default function main() {`, + ` const shape = makeBox([0, 0, 0], [40, 30, 20]);`, + ` return shape.fillet(2, (e) => e.inDirection("Y"));`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).not.toMatch(/unknown method/i); + }); + + it("does not warn on a FaceFinder callback (shell + inPlane)", () => { + const code = [ + `import { makeBox } from "replicad";`, + `export default function main() {`, + ` const shape = makeBox([0, 0, 0], [40, 30, 60]);`, + ` return shape.shell(2, (f) => f.inPlane("XY", 60));`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).not.toMatch(/unknown method/i); + }); + + it("accepts every public Finder method declared in the bundled replicad typings", () => { + // Drift guard: if replicad adds a filter, this fails until the + // whitelist in validateSyntaxPure learns it. + const dts = readFileSync( + fileURLToPath(new URL("../../extension/typings/replicad/index.d.ts", import.meta.url)), + "utf-8", + ); + const methods = new Set(); + const classPattern = /declare (?:abstract )?class (?:Finder|Finder3d|EdgeFinder|FaceFinder|CornerFinder)\b[^{]*\{([\s\S]*?)\n\}/g; + for (const [, body] of dts.matchAll(classPattern)) { + for (const [, name] of body.matchAll(/^ {4}(?:abstract )?(\w+)(?:<[^>]*>)?\(/gm)) { + if (name !== "constructor") methods.add(name); + } + } + expect(methods).toContain("inDirection"); + expect(methods).toContain("ofSurfaceType"); + expect(methods).toContain("containsPoint"); + const code = [ + `export default function main(shape) {`, + ...[...methods].map((m) => ` shape.fillet(1, (f) => f.${m}());`), + `}`, + ].join("\n"); + expect(validateSyntaxPure(code).text).not.toMatch(/unknown method/i); + }); + + it("still flags typos on Replicad shapes and on built-ins", () => { + const code = [ + `import { drawRectangle } from "replicad";`, + `export default function main() {`, + ` const r = 10 * Math.cso(0.5);`, + ` return drawRectangle(r, 20).sketchOnPlane("XY").extrdue(5);`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).toMatch(/unknown method/i); + expect(text).toContain(".extrdue()"); + expect(text).toContain(".cso()"); + expect(text).not.toContain(".sketchOnPlane()"); + }); +}); + +// --------------------------------------------------------------------------- +// Ordinary array/string/number instance methods (`pts.map`, `parts.push`, +// `n.toFixed`) were reported as "unknown method(s)". Typos — on Replicad +// shapes, on built-ins, and on arrays themselves — must still be flagged. +// --------------------------------------------------------------------------- + +describe("validateSyntaxPure — array, string and number instance methods", () => { + it("does not warn on map / push / forEach / Object.keys(o).map / toFixed", () => { + const code = [ + `import { makeCylinder } from "replicad";`, + `export default function main() {`, + ` const o = { a: 1, b: 2 };`, + ` const n = 12.345;`, + ` const holes = [[0, 0], [10, 0]];`, + ` const pts = holes.map((p) => [p[0] * 2, p[1]]);`, + ` const parts = [];`, + ` holes.forEach((h, i) => parts.push({ shape: makeCylinder(2, 5).translate([h[0], h[1], 0]), name: "h" + i }));`, + ` const label = Object.keys(o).map((k) => k.toUpperCase()).join("-") + n.toFixed(2);`, + ` return parts;`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).not.toMatch(/unknown method/i); + }); + + it("does not warn on chained array and string methods after a call", () => { + const code = [ + `export default function main({ count }) {`, + ` const names = Array.from({ length: count }, (_, i) => i)`, + ` .filter((i) => i % 2 === 0)`, + ` .map((i) => String(i).padStart(3, "0"))`, + ` .reduce((acc, s) => acc.concat(s.split("")), []);`, + ` return names.slice(0, 2).includes("0");`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).not.toMatch(/unknown method/i); + }); + + it("still flags Replicad, built-in and array-method typos next to them", () => { + const code = [ + `import { drawRectangle } from "replicad";`, + `export default function main() {`, + ` const sizes = [10, 20];`, + ` const scaled = sizes.map((s) => s * Math.cso(0.5));`, + ` scaled.pussh(5);`, + ` return drawRectangle(scaled[0], 20).sketchOnPlane("XY").extrdue(5);`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).toMatch(/unknown method/i); + expect(text).toContain(".extrdue()"); + expect(text).toContain(".cso()"); + expect(text).toContain(".pussh()"); + expect(text).not.toContain(".map()"); + }); +}); + // --------------------------------------------------------------------------- // Pitfall detector — hand-rolled boolean loops // Covers all four new patterns plus regression-guards for the existing diff --git a/packages/mcp-server/src/tools.ts b/packages/mcp-server/src/tools.ts index 06e8a11..fdc3f54 100644 --- a/packages/mcp-server/src/tools.ts +++ b/packages/mcp-server/src/tools.ts @@ -1779,7 +1779,10 @@ export function computeEffectiveMeshQuality( * 2. Unknown `.method()` calls — compared against a hand-curated Replicad * whitelist. Method calls whose receiver was imported from "shapeitup" * are trusted unconditionally (so stdlib additions don't need to be - * mirrored here). Warnings only; isError stays false. + * mirrored here); calls on ECMAScript built-ins (`Math.cos`) are + * checked against the built-in itself, and Array/String/Number instance + * methods (`pts.map`) are accepted by name. Warnings only; isError stays + * false. * 3. Seven well-known CAD pitfalls (sketch mischain, missing sketchOnPlane, * unclosed pen, non-uniform scale, oversized fillet, booleans in loop, * and the AST-based variable-assigned `extrude` variant). Warnings only. @@ -1809,8 +1812,43 @@ export function validateSyntaxPure(code: string): { text: string; isError: boole "close", "hLine", "vLine", "lineTo", "line", "sagittaArcTo", "tangentArcTo", "threePointsArcTo", "cubicBezierCurveTo", "smoothSplineTo", "closeWithMirror", "done", "localGC", "exportSTEP", + // EdgeFinder / FaceFinder / CornerFinder filters, plus the Finder and + // Finder3d bases they inherit from (packages/extension/typings/replicad). + // These mostly show up inside finder callbacks — `.fillet(2, (e) => + // e.inDirection("Y"))` — where the receiver is just the callback param. + "inDirection", "ofLength", "ofCurveType", "parallelTo", "inPlane", "ofSurfaceType", + "when", "inList", "atAngleWith", "atDistance", "containsPoint", "withinDistance", + "inBox", "inShape", "atPoint", "ofAngle", + "and", "not", "either", "find", "clone", "delete", "shouldKeep", ]); + // ECMAScript built-ins callable as `Global.method(` — Math.cos, + // Number.isFinite, JSON.stringify. Calls rooted here are resolved against + // the real built-in instead of the Replicad whitelist, so `Math.cso(` is + // still flagged. Deliberately not `globalThis` wholesale: Node globals + // like `process` don't exist in the worker the script runs in. + const builtinGlobals = new Set([ + "Math", "Number", "Object", "Array", "JSON", "String", "Boolean", "Date", + "Symbol", "BigInt", "Reflect", "Promise", "Map", "Set", "Intl", "console", + ]); + const isBuiltinMethod = (segments: string[], methodName: string): boolean => { + let target: any = (globalThis as any)[segments[0]]; + for (const seg of segments.slice(1)) target = target?.[seg]; + return target != null && typeof target[methodName] === "function"; + }; + + // Instance methods of arrays, strings and numbers — `pts.map(`, + // `parts.push(`, `n.toFixed(`, and `Object.keys(o).map(` via the chain + // pass. The receiver is usually a local, so there is no type to resolve + // against; accept the name if one of these prototypes has it. Cost: a + // Replicad typo that IS such a name goes unflagged — realistically only + // `.filter(`/`.fill(` for `.fillet(`, which still fails at runtime with + // "not a function". + const builtinPrototypes: any[] = [Array.prototype, String.prototype, Number.prototype]; + const isKnownMethod = (methodName: string): boolean => + knownMethods.has(methodName) || + builtinPrototypes.some((proto) => typeof proto[methodName] === "function"); + // Bug #6: trust .method() calls whose receiver was imported from the // shapeitup stdlib. Otherwise every stdlib helper (bearings.body, // holes.through, patterns.grid, etc.) shows up as "unknown method" — @@ -1857,7 +1895,8 @@ export function validateSyntaxPure(code: string): { text: string; isError: boole let match: RegExpExecArray | null; while ((match = receiverCallPattern.exec(code)) !== null) { const [, receiverChain, methodName] = match; - const rootIdent = receiverChain.split(/\s*\.\s*/)[0]; + const segments = receiverChain.split(/\s*\.\s*/); + const rootIdent = segments[0]; if (stdlibIdents.has(rootIdent)) { // Remember that this method name was seen on a stdlib receiver // somewhere — even if the SAME name later appears as a chain @@ -1867,7 +1906,11 @@ export function validateSyntaxPure(code: string): { text: string; isError: boole skippedByReceiver.add(methodName); continue; } - if (!knownMethods.has(methodName)) unknownMethods.add(methodName); + if (builtinGlobals.has(rootIdent)) { + if (!isBuiltinMethod(segments, methodName)) unknownMethods.add(methodName); + continue; + } + if (!isKnownMethod(methodName)) unknownMethods.add(methodName); } // Chain-continuation pass: picks up `foo().bar()` — where `bar`'s // receiver is a call expression, not a plain identifier, so the @@ -1878,7 +1921,7 @@ export function validateSyntaxPure(code: string): { text: string; isError: boole while ((match = chainCallPattern.exec(code)) !== null) { const methodName = match[1]; if (skippedByReceiver.has(methodName)) continue; - if (!knownMethods.has(methodName)) unknownMethods.add(methodName); + if (!isKnownMethod(methodName)) unknownMethods.add(methodName); } // --- Semantic checks (pitfall linter) -----------------------------