diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 4a81869..7f921e9 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -12,7 +12,7 @@
{
"name": "shapeitup",
"description": "CAD scripting toolkit: create/modify .shape.ts files, validate geometry, check collisions, export STEP/STL/3MF via Replicad + OpenCascade. Runs headless; live 3D preview available if the ShapeItUp VS Code extension is installed.",
- "version": "1.30.1",
+ "version": "1.31.1",
"author": {
"name": "Asbjorn Rorvik",
"email": "rorvik.asbjorn@gmail.com"
diff --git a/.gitignore b/.gitignore
index 8b963d4..8d84f5b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,6 +16,8 @@ Thumbs.db
*.stl
*.step
*.tsbuildinfo
+# ...except STEP inputs the importStep tests read.
+!packages/core/src/testing/fixtures/*.step
# Claude Code local state
.claude/plans/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7c001c2..f465027 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,45 @@ Releases 1.17.0–1.24.0 are described only in their
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); the
project follows semantic versioning at the extension level.
+## [1.31.1] - 2026-10-24
+
+Extension `1.31.1` / mcp-server `1.31.1` — STEP export no longer crashes the
+next run.
+
+### Fixed
+- **The render after a STEP export could crash OpenCascade** with "memory
+ access out of bounds", most often when that render rebundled because a local
+ import had changed (about 4 runs in 5). One MCP process doing export → next
+ file, as a benchmark run does, hit it every few files. Replicad's
+ `exportSTEP` frees its STEP work session twice once the garbage collector
+ gets to it: directly, and again through the refcounted handle the writer
+ shares. ShapeItUp now writes STEP itself with one owner per OpenCascade
+ object and frees them all before returning. The file is the same as before.
+ This covers `export_shape`, the viewer's STEP button, and scripts that call
+ `exportSTEP` themselves.
+
+## [1.31.0] - 2026-10-22
+
+Extension `1.31.0` / mcp-server `1.31.0` — STEP import.
+
+### Added
+- **Scripts can load an existing STEP file and edit it.** A `.shape.ts` can
+ `import part from "./input.step"` (`.step` / `.stp`, either case); every
+ bundler — the MCP engine, the VS Code extension and the serve host — inlines
+ the file as a `Uint8Array`. `importStep(bytes)` from `"shapeitup"` turns
+ those bytes into a shape synchronously, so it works inside `main()`, and the
+ result cuts, fuses and exports like any other shape. Editing the STEP file
+ re-renders the script. Editor typings declare `*.step` / `*.stp` modules, so
+ the import type-checks. Documented in `get_api_reference` (`stdlib`,
+ `export`) and the skill.
+
+### Fixed
+- **An `async main()` failed with "main() must return one of …"**, which said
+ nothing about the cause. `main()` runs synchronously, so an async main, or
+ Replicad's async `importSTEP()` returned directly, now fails with "main()
+ returned a Promise" and points at `importStep`. The abandoned Promise's
+ rejection is silenced instead of surfacing later as an unhandled one.
+
## [1.30.1] - 2026-10-12
Extension `1.30.1` / mcp-server `1.30.1` — Codex setup docs and three fixes.
diff --git a/esbuild.config.mjs b/esbuild.config.mjs
index ea8d850..d483886 100644
--- a/esbuild.config.mjs
+++ b/esbuild.config.mjs
@@ -291,8 +291,14 @@ function copyExtensionTypings() {
// Wrapper index.d.ts — re-exports everything from the emitted stdlib.
// Matches packages/extension/typings/shapeitup/index.d.ts but self-
// contained (no relative path out to the core source).
- const wrapper = `// Auto-generated by ShapeItUp build. Do not edit.\n// Re-exports the stdlib declarations bundled alongside this file.\nexport * from "./stdlib/index";\n`;
+ // The reference pulls in the ambient `*.step` module types, so
+ // `import part from "./input.step"` type-checks in user projects.
+ const wrapper = `// Auto-generated by ShapeItUp build. Do not edit.\n// Re-exports the stdlib declarations bundled alongside this file.\n/// \nexport * from "./stdlib/index";\n`;
writeFileSync(resolve(shapeitupDest, "index.d.ts"), wrapper);
+ cpSync(
+ resolve(typingsSrc, "shapeitup/step-imports.d.ts"),
+ resolve(shapeitupDest, "step-imports.d.ts"),
+ );
const pkg = {
name: "shapeitup",
diff --git a/packages/core/src/executor.test.ts b/packages/core/src/executor.test.ts
index 4693695..4f984d8 100644
--- a/packages/core/src/executor.test.ts
+++ b/packages/core/src/executor.test.ts
@@ -73,6 +73,49 @@ describe("executeScript — minimal scripts", () => {
});
});
+describe("executeScript — main() returning a Promise", () => {
+ // `async function main()` and replicad's async `importSTEP` both hand back a
+ // Promise; the executor never awaits it. The error must say so and point at
+ // the synchronous `importStep`, not fall through to "must return one of".
+ const ASYNC_MESSAGE = /main\(\) returned a Promise[\s\S]*importStep/;
+
+ it("rejects an async main with a message that names importStep", () => {
+ const js = `
+ async function main() { return 1; }
+ export { main as default };
+ `;
+ expect(() => executeScript(js, {}, {})).toThrow(ASYNC_MESSAGE);
+ });
+
+ it("rejects a part whose shape is still a Promise", () => {
+ const importSTEP = async () => ({});
+ const js = `
+ import { importSTEP } from "replicad";
+ function main() { return [{ shape: importSTEP(new Blob([])), name: "input" }]; }
+ export { main as default };
+ `;
+ expect(() => executeScript(js, { importSTEP }, {})).toThrow(ASYNC_MESSAGE);
+ });
+
+ it("silences the abandoned Promise's rejection", async () => {
+ const unhandled: unknown[] = [];
+ const onUnhandled = (reason: unknown) => unhandled.push(reason);
+ process.on("unhandledRejection", onUnhandled);
+ try {
+ const js = `
+ async function main() { throw new Error("STEP read failed"); }
+ export { main as default };
+ `;
+ expect(() => executeScript(js, {}, {})).toThrow(ASYNC_MESSAGE);
+ // Unhandled rejections are reported after the microtask queue drains.
+ await new Promise((r) => setTimeout(r, 10));
+ expect(unhandled).toEqual([]);
+ } finally {
+ process.off("unhandledRejection", onUnhandled);
+ }
+ });
+});
+
describe("executeScript — params flow", () => {
it("uses declared param defaults when no overrides are passed", () => {
const js = `
diff --git a/packages/core/src/executor.ts b/packages/core/src/executor.ts
index fe01246..b95e269 100644
--- a/packages/core/src/executor.ts
+++ b/packages/core/src/executor.ts
@@ -240,6 +240,46 @@ export function rewriteImports(js: string): string {
return code;
}
+const isThenable = (v: any): boolean =>
+ v !== null && (typeof v === "object" || typeof v === "function") && typeof v.then === "function";
+
+/**
+ * Throw a clear error when `main()` handed back a Promise — an `async main`, or
+ * replicad's `importSTEP` / `importSTL` (both async) returned directly. The
+ * executor calls `main()` synchronously, so without this the Promise reaches
+ * `normalizeParts` and fails as "main() must return one of …", which says
+ * nothing about why.
+ *
+ * Each Promise gets a no-op rejection handler first: nothing will ever await
+ * it, and a rejection would otherwise surface later as an unhandled one.
+ */
+export function rejectAsyncResult(result: any): void {
+ const pending: any[] = [];
+ if (isThenable(result)) pending.push(result);
+ else if (Array.isArray(result)) {
+ for (const item of result) {
+ if (isThenable(item)) pending.push(item);
+ else if (item && isThenable(item.shape)) pending.push(item.shape);
+ }
+ }
+ if (pending.length === 0) return;
+ for (const p of pending) {
+ try {
+ p.then(undefined, () => {});
+ } catch {
+ // A thenable with a throwing `then` — nothing to silence.
+ }
+ }
+ throw new Error(
+ `main() returned a Promise. ShapeItUp calls main() synchronously, so an async main(), ` +
+ `await, and replicad's async importSTEP()/importSTL() cannot be used.\n` +
+ `To load a STEP file, import it and use the synchronous importStep from "shapeitup":\n` +
+ ` import part from "./input.step";\n` +
+ ` import { importStep } from "shapeitup";\n` +
+ ` export default function main() { return importStep(part); }`,
+ );
+}
+
/**
* Execute a user .shape.ts script (already transpiled/bundled to JS).
*
@@ -501,6 +541,8 @@ export function executeScript(
paramOverrides || null
);
+ rejectAsyncResult(result);
+
// Resolve the script-level `export const material = ...` via the shared
// resolver (also used per-part inside `normalizeParts`). Unknown strings
// emit a runtime warning so a typo is visible instead of silently losing
diff --git a/packages/core/src/exporter.ts b/packages/core/src/exporter.ts
index 75ab4db..8f27631 100644
--- a/packages/core/src/exporter.ts
+++ b/packages/core/src/exporter.ts
@@ -1,5 +1,6 @@
import type { PartInput } from "./tessellate";
import { generate3MF } from "./3mf";
+import { writeStep } from "./step-writer";
export async function exportShapes(
parts: PartInput[],
@@ -15,9 +16,11 @@ async function exportPartsCombined(
replicadModule: any
): Promise {
if (format === "step") {
+ // Not replicadModule.exportSTEP: that one frees its work session twice
+ // once GC collects it, and the next OCCT call crashes. See step-writer.ts.
const stepParts = parts.map((p) => ({ shape: p.shape, name: p.name }));
- const blob: Blob = replicadModule.exportSTEP(stepParts);
- return blob.arrayBuffer();
+ const bytes = writeStep(replicadModule.getOC(), stepParts);
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
} else if (format === "3mf") {
return generate3MF(parts);
} else {
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index d66b82c..e179659 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -20,6 +20,7 @@ import { executeScript } from "./executor";
export { extractParamsStatic, extractConfigStatic, extractExpectedContactsStatic } from "./executor";
import { describeFaces, normalizeParts, tessellatePart, type MeshQuality, type PartInput, type PartStatsLevel, type TessellatedPart } from "./tessellate";
import { exportShapes, exportShapesSplit } from "./exporter";
+import { makeExportSTEP } from "./step-writer";
import {
validateParts,
hasGeometryErrors,
@@ -871,6 +872,10 @@ export async function initCore(
patchShapeFuseNoOpGuard(replicad);
const replicadExports: Record = { ...replicad };
+ // Scripts that call exportSTEP themselves get the version without the
+ // double-freed work session too. The module namespace is read-only, so the
+ // swap happens on this copy, which is what scripts destructure from.
+ replicadExports.exportSTEP = makeExportSTEP(replicad.getOC);
instrumentReplicadExports(replicadExports);
let lastParts: PartInput[] = [];
diff --git a/packages/core/src/stdlib/index.ts b/packages/core/src/stdlib/index.ts
index 1ad471c..1e61cbd 100644
--- a/packages/core/src/stdlib/index.ts
+++ b/packages/core/src/stdlib/index.ts
@@ -21,6 +21,7 @@ import { Part, joint, jointAt, part, faceAt, shaftAt, boreAt } from "./parts";
import { mate, assemble, subassembly, stack, stackOnZ, entries, symmetricPair, debugJoints, highlightJoints, composeAssembly } from "./assembly";
import { cylinder, rod } from "./cylinder";
import { box, prism, plate, wall } from "./shapes";
+import { importStep } from "./step";
// `plates` is a small namespace containing the plate-shaped helper(s). Kept
// separate from the top-level `plate` export so user scripts can reach either
// (`plates.plate({...})` mirrors `holes.through(...)` / `motors.nema17()`).
@@ -64,6 +65,9 @@ export type { Placement } from "./patterns";
// warning can type its callback without reaching into the module.
export type { CombineOp, CombineOptions, CombineStats } from "./booleans";
+// The argument type of `importStep`, for scripts that wrap it.
+export type { StepSource } from "./step";
+
// User-facing view of the standards namespace. Unknown-key reads throw with
// a did-you-mean suggestion so `standards.NEMA17.pilotDiameter` (typo for
// `pilotDia`) fails fast instead of returning undefined and propagating as
@@ -138,6 +142,7 @@ export {
gears,
pins,
cradles,
+ importStep,
};
/**
@@ -200,6 +205,7 @@ export const shapeitupStdlib = {
gears,
pins,
cradles,
+ importStep,
standards,
};
diff --git a/packages/core/src/stdlib/step.test.ts b/packages/core/src/stdlib/step.test.ts
new file mode 100644
index 0000000..68966b3
--- /dev/null
+++ b/packages/core/src/stdlib/step.test.ts
@@ -0,0 +1,127 @@
+/**
+ * importStep against real OCCT.
+ *
+ * The fixture is a 40 x 30 x 10 mm block that ShapeItUp exported itself — the
+ * MCP engine ran
+ *
+ * export default function main() {
+ * return { shape: drawRectangle(40, 30).sketchOnPlane("XY").extrude(10), name: "block" };
+ * }
+ *
+ * and `export_shape` wrote the STEP. Volumes are checked against that, not
+ * snapshotted: the failures worth catching are an import that silently comes
+ * back empty, or a shape that loads but won't take a boolean.
+ */
+import { describe, it, expect, beforeAll } from "vitest";
+import { readFileSync } from "node:fs";
+import { loadOCCTForTest } from "../testing/occt.js";
+
+const FIXTURE = new URL("../testing/fixtures/block-40x30x10.step", import.meta.url);
+const BLOCK_VOLUME = 40 * 30 * 10;
+
+let oc: any;
+let rc: typeof import("replicad");
+let importStep: typeof import("./step.js").importStep;
+let writeStep: typeof import("../step-writer.js").writeStep;
+let shapeitupStdlib: typeof import("./index.js").shapeitupStdlib;
+let fixture: Uint8Array;
+
+beforeAll(async () => {
+ oc = await loadOCCTForTest();
+ rc = await import("replicad");
+ rc.setOC(oc);
+ ({ importStep } = await import("./step.js"));
+ ({ writeStep } = await import("../step-writer.js"));
+ ({ shapeitupStdlib } = await import("./index.js"));
+ fixture = new Uint8Array(readFileSync(FIXTURE));
+}, 120_000);
+
+const vol = (s: any) => rc.measureVolume(s);
+
+describe("importStep", () => {
+ it("is on the runtime stdlib object scripts destructure from", () => {
+ expect(shapeitupStdlib.importStep).toBe(importStep);
+ });
+
+ it("returns the file's solid, synchronously", () => {
+ const shape = importStep(fixture) as any;
+ expect(shape instanceof Promise).toBe(false);
+ expect(shape.constructor.name).toBe("Solid");
+ expect(vol(shape)).toBeCloseTo(BLOCK_VOLUME, 1);
+ const bb = shape.boundingBox;
+ expect(bb.width).toBeCloseTo(40, 3);
+ expect(bb.height).toBeCloseTo(30, 3);
+ expect(bb.depth).toBeCloseTo(10, 3);
+ });
+
+ it("gives a shape that takes a boolean cut", () => {
+ const hole = rc.makeCylinder(5, 20, [0, 0, -5]);
+ const cut = (importStep(fixture) as any).cut(hole);
+ expect(vol(cut)).toBeCloseTo(BLOCK_VOLUME - Math.PI * 25 * 10, 1);
+ });
+
+ it("accepts an ArrayBuffer and the STEP text itself", () => {
+ const buffer = new ArrayBuffer(fixture.byteLength);
+ new Uint8Array(buffer).set(fixture);
+ expect(vol(importStep(buffer))).toBeCloseTo(BLOCK_VOLUME, 1);
+ expect(vol(importStep(new TextDecoder().decode(fixture)))).toBeCloseTo(BLOCK_VOLUME, 1);
+ });
+
+ it("round-trips a multi-body export as a compound", () => {
+ const a = rc.drawRectangle(10, 10).sketchOnPlane("XY").extrude(10);
+ const b = rc.drawRectangle(10, 10).sketchOnPlane("XY").extrude(10).translate(30, 0, 0);
+ const shape = importStep(
+ writeStep(oc, [
+ { shape: a, name: "a" },
+ { shape: b, name: "b" },
+ ]),
+ );
+ expect(shape.constructor.name).toBe("Compound");
+ expect(vol(shape)).toBeCloseTo(2000, 1);
+ });
+
+ // Class checks compare names: on failure vitest would otherwise try to print
+ // a replicad shape, whose graph reaches the whole OCCT module, and run out of
+ // memory instead of reporting.
+ it("returns a 3D shape for files with no solid in them", async () => {
+ const face = (rc.drawRectangle(10, 20).sketchOnPlane("XY") as any).face();
+ const surface = importStep(new Uint8Array(await face.blobSTEP().arrayBuffer())) as any;
+ expect(surface.constructor.name).toBe("Shell");
+ expect(rc.measureArea(surface)).toBeCloseTo(200, 3);
+
+ const edge = rc.makeLine([0, 0, 0], [25, 0, 0]) as any;
+ const curve = importStep(new Uint8Array(await edge.blobSTEP().arrayBuffer())) as any;
+ expect(curve.constructor.name).toBe("Compound");
+ expect(curve.edges).toHaveLength(1);
+ expect(rc.measureLength(curve)).toBeCloseTo(25, 3);
+ });
+
+ it("leaves nothing behind in the Emscripten FS", () => {
+ const before = oc.FS.readdir("/").filter((f: string) => f.startsWith("shapeitup-import-"));
+ importStep(fixture);
+ expect(() => importStep(new TextEncoder().encode("not a step file"))).toThrow();
+ const after = oc.FS.readdir("/").filter((f: string) => f.startsWith("shapeitup-import-"));
+ expect(after).toEqual(before);
+ });
+
+ it("says to pass bytes when given a path", () => {
+ expect(() => importStep("./input.step")).toThrow(/bytes, not its path[\s\S]*import part from "\.\/input\.step"/);
+ });
+
+ it("says why a Blob can't work", () => {
+ const blob = new Blob([fixture as BlobPart]);
+ expect(() => importStep(blob as any)).toThrow(/Blob[\s\S]*synchronously/);
+ });
+
+ it("names the problem for data that isn't STEP", () => {
+ expect(() => importStep(new TextEncoder().encode("solid cube\nendsolid cube\n"))).toThrow(
+ /not a STEP file/,
+ );
+ expect(() => importStep(new Uint8Array())).toThrow(/empty/);
+ });
+
+ it("reports a STEP header with a body OCCT can't read as a parse failure", () => {
+ const truncated = new TextEncoder().encode("ISO-10303-21;\nHEADER;\n");
+ expect(() => importStep(truncated)).toThrow(/could not parse|contains no shape/);
+ });
+});
diff --git a/packages/core/src/stdlib/step.ts b/packages/core/src/stdlib/step.ts
new file mode 100644
index 0000000..93d0bec
--- /dev/null
+++ b/packages/core/src/stdlib/step.ts
@@ -0,0 +1,140 @@
+/**
+ * Load an existing STEP file into a script, synchronously.
+ *
+ * The bundlers load `.step` / `.stp` imports as bytes (see
+ * `SHAPE_BUNDLE_LOADERS` in `@shapeitup/shared`), so a script can write
+ *
+ * import part from "./input.step";
+ * import { importStep } from "shapeitup";
+ * export default function main() {
+ * return importStep(part).cut(makeCylinder(3, 50).translate(10, 5, -1));
+ * }
+ *
+ * Replicad ships `importSTEP(blob)`, but it is async — only because it awaits
+ * `blob.arrayBuffer()` — and the executor calls `main()` synchronously, so a
+ * Promise can never reach the renderer. Everything after reading the bytes is
+ * synchronous OCCT, which is what this does: write the bytes to the Emscripten
+ * FS, read them with `STEPControl_Reader`, transfer the roots, cast the result.
+ */
+import {
+ CompSolid,
+ Compound,
+ Shell,
+ Solid,
+ cast,
+ compoundShapes,
+ getOC,
+ type AnyShape,
+ type Shape3D,
+} from "replicad";
+
+/** What `importStep` accepts: the imported bytes, or the file's text. */
+export type StepSource = Uint8Array | ArrayBuffer | string;
+
+const HOW_TO_IMPORT =
+ `Import the file so the bundler inlines its bytes, then pass those:\n` +
+ ` import part from "./input.step";\n` +
+ ` import { importStep } from "shapeitup";\n` +
+ ` export default function main() { return importStep(part); }`;
+
+/** Every STEP file (ISO 10303-21) opens with this keyword. */
+const STEP_MAGIC = "ISO-10303-21";
+
+let importCount = 0;
+
+function toBytes(source: StepSource): Uint8Array {
+ if (source instanceof Uint8Array) return source;
+ if (source instanceof ArrayBuffer) return new Uint8Array(source);
+ if (typeof source === "string") {
+ // A path is the likely mistake here, and OCCT's answer to one is a bare
+ // "read failed". Only text that is itself a STEP file is accepted.
+ if (!source.trimStart().startsWith(STEP_MAGIC)) {
+ throw new Error(
+ `importStep() got a string that is not STEP file content` +
+ ` (${JSON.stringify(source.slice(0, 40))}). It takes the file's bytes, not its path.\n` +
+ HOW_TO_IMPORT,
+ );
+ }
+ return new TextEncoder().encode(source);
+ }
+ const s = source as any;
+ if (s && typeof s.arrayBuffer === "function") {
+ throw new Error(
+ `importStep() got a Blob/File. A Blob can only be read asynchronously, and main() runs synchronously.\n` +
+ HOW_TO_IMPORT,
+ );
+ }
+ throw new Error(
+ `importStep() expects the STEP file's bytes (a Uint8Array), got ${s === null ? "null" : typeof s}.\n` +
+ HOW_TO_IMPORT,
+ );
+}
+
+const is3D = (shape: AnyShape): shape is Shape3D =>
+ shape instanceof Solid ||
+ shape instanceof Compound ||
+ shape instanceof Shell ||
+ shape instanceof CompSolid;
+
+function looksLikeStep(bytes: Uint8Array): boolean {
+ const head = new TextDecoder().decode(bytes.subarray(0, 256)).replace(/^/, "");
+ return head.trimStart().startsWith(STEP_MAGIC);
+}
+
+/**
+ * Read a STEP file into a shape. Synchronous, so it works inside `main()`.
+ *
+ * Lengths come back in millimetres whatever unit the file was written in —
+ * OCCT converts on transfer. A file with one body returns that `Solid`; a file
+ * with several returns a `Compound`, which `.cut()` / `.fuse()` accept as is.
+ * A file holding only a surface comes back as a `Shell`, and one holding only
+ * curves as a `Compound` of edges, so the result is always a `Shape3D`.
+ *
+ * @param source the file's bytes — `import part from "./input.step"` gives you
+ * these — or the STEP text itself.
+ */
+export function importStep(source: StepSource): Shape3D {
+ const bytes = toBytes(source);
+ if (bytes.byteLength === 0) {
+ throw new Error(`importStep(): the STEP file is empty.`);
+ }
+
+ const oc = getOC() as any;
+ // Unique per call: two imports in one script must not share a path.
+ const path = `/shapeitup-import-${++importCount}.step`;
+ oc.FS.writeFile(path, bytes);
+
+ const reader = new oc.STEPControl_Reader_1();
+ const progress = new oc.Message_ProgressRange_1();
+ let root: any;
+ try {
+ const status = reader.ReadFile(path);
+ if (status !== oc.IFSelect_ReturnStatus.IFSelect_RetDone) {
+ throw new Error(
+ looksLikeStep(bytes)
+ ? `importStep(): OpenCascade could not parse this STEP file (status ${status?.value ?? "unknown"}).`
+ : `importStep(): the data is not a STEP file — it does not start with "${STEP_MAGIC}". ` +
+ `Only STEP (.step / .stp) is supported.`,
+ );
+ }
+ reader.TransferRoots(progress);
+ root = reader.OneShape();
+ if (root.IsNull()) {
+ throw new Error(`importStep(): the STEP file parsed, but contains no shape OpenCascade can transfer.`);
+ }
+ // `cast` wraps a fresh downcast handle, so `root` is ours to free.
+ const shape = cast(root);
+ // OCCT already returns a Shell for a lone face and a Compound for curves;
+ // `cast` is typed AnyShape, so anything else is wrapped to keep that true.
+ return is3D(shape) ? shape : (compoundShapes([shape]) as Shape3D);
+ } finally {
+ try {
+ oc.FS.unlink(path);
+ } catch {
+ // Already gone — nothing to free.
+ }
+ root?.delete();
+ progress.delete();
+ reader.delete();
+ }
+}
diff --git a/packages/core/src/step-writer.test.ts b/packages/core/src/step-writer.test.ts
new file mode 100644
index 0000000..6832a82
--- /dev/null
+++ b/packages/core/src/step-writer.test.ts
@@ -0,0 +1,107 @@
+/**
+ * The STEP writer against real OCCT.
+ *
+ * The GC test is the one that matters. Replicad's exportSTEP queued a second
+ * free of its work session for the garbage collector, so the damage landed
+ * whenever GC next ran. This forces that collection instead of waiting for it.
+ */
+import { describe, it, expect, beforeAll, vi } from "vitest";
+import { setFlagsFromString } from "node:v8";
+import { runInNewContext } from "node:vm";
+import type { Shape3D } from "replicad";
+import { loadOCCTForTest } from "./testing/occt.js";
+
+let oc: any;
+let rc: typeof import("replicad");
+let writeStep: typeof import("./step-writer.js").writeStep;
+let makeExportSTEP: typeof import("./step-writer.js").makeExportSTEP;
+let exportShapes: typeof import("./exporter.js").exportShapes;
+let importStep: typeof import("./stdlib/step.js").importStep;
+
+beforeAll(async () => {
+ oc = await loadOCCTForTest();
+ rc = await import("replicad");
+ rc.setOC(oc);
+ ({ writeStep, makeExportSTEP } = await import("./step-writer.js"));
+ ({ exportShapes } = await import("./exporter.js"));
+ ({ importStep } = await import("./stdlib/step.js"));
+}, 120_000);
+
+const plate = () =>
+ (rc.drawRoundedRectangle(40, 30, 3).sketchOnPlane("XY").extrude(8) as Shape3D)
+ .cut(rc.makeCylinder(4, 20, [0, 0, -5]))
+ .fillet(1);
+
+const text = (bytes: Uint8Array | ArrayBuffer) => new TextDecoder().decode(bytes);
+
+/**
+ * `gc()` without `--expose-gc` on the command line, which the test runner's
+ * workers don't get. Finalizers run as tasks after a collection, so yield too.
+ */
+async function collectGarbage() {
+ setFlagsFromString("--expose-gc");
+ const gc = runInNewContext("gc") as () => void;
+ for (let i = 0; i < 3; i++) {
+ gc();
+ await new Promise((r) => setImmediate(r));
+ }
+}
+
+describe("writeStep", () => {
+ it("writes a STEP that reads back as the same solid", () => {
+ const shape = plate();
+ const bytes = writeStep(oc, [{ shape, name: "plate" }]);
+ expect(text(bytes)).toMatch(/^ISO-10303-21;/);
+ expect(rc.measureVolume(importStep(bytes))).toBeCloseTo(rc.measureVolume(shape), 1);
+ });
+
+ it("keeps replicad's names and colours", () => {
+ const step = text(
+ writeStep(oc, [
+ { shape: plate(), name: "base" },
+ { shape: plate().translate(60, 0, 0), name: "lid", color: "#0f0" },
+ ]),
+ );
+ expect(step).toMatch(/PRODUCT\('base'/);
+ expect(step).toMatch(/PRODUCT\('lid'/);
+ // Unset colours default to red, as replicad's do. OCCT writes pure
+ // primaries as named colours.
+ expect(step).toMatch(/DRAUGHTING_PRE_DEFINED_COLOUR\('red'\)/);
+ expect(step).toMatch(/DRAUGHTING_PRE_DEFINED_COLOUR\('green'\)/);
+ });
+
+ it("is what the exporter and the script-facing exportSTEP use", async () => {
+ const exported = await exportShapes([{ shape: plate(), name: "plate", color: null }], "step", rc);
+ expect(text(exported)).toMatch(/PRODUCT\('plate'/);
+ const blob = makeExportSTEP(() => oc)([{ shape: plate(), name: "blob" }]);
+ expect(blob.type).toBe("application/step"); // Blob lower-cases it
+ expect(text(await blob.arrayBuffer())).toMatch(/PRODUCT\('blob'/);
+ });
+
+ it("leaves nothing for the garbage collector to free twice", async () => {
+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});
+ try {
+ for (let i = 0; i < 5; i++) {
+ const shape = plate();
+ await exportShapes([{ shape, name: `plate_${i}`, color: null }], "step", rc);
+ shape.delete();
+ }
+ await collectGarbage();
+
+ // Replicad's registry logs what its finalizers throw rather than
+ // rethrowing, so a double free shows up here first.
+ const finalizerFailures = errors.mock.calls.map((args) => String(args[0]));
+ expect(finalizerFailures).toEqual([]);
+
+ // And the heap still works.
+ for (let i = 0; i < 10; i++) {
+ const shape = plate();
+ shape.mesh({ tolerance: 0.1, angularTolerance: 0.3 });
+ expect(rc.measureVolume(shape)).toBeGreaterThan(0);
+ shape.delete();
+ }
+ } finally {
+ errors.mockRestore();
+ }
+ });
+});
diff --git a/packages/core/src/step-writer.ts b/packages/core/src/step-writer.ts
new file mode 100644
index 0000000..4968b73
--- /dev/null
+++ b/packages/core/src/step-writer.ts
@@ -0,0 +1,137 @@
+/**
+ * Write shapes to a STEP file — replicad's `exportSTEP`, minus its double free.
+ *
+ * Replicad's version (replicad.js, `exportSTEP`) does
+ *
+ * const r = GCWithScope();
+ * const session = r(new oc.XSControl_WorkSession());
+ * const writer = r(new oc.STEPCAFControl_Writer_2(
+ * r(new oc.Handle_XSControl_WorkSession_2(session)), false));
+ *
+ * The session is a Standard_Transient, so the Handle — and the writer, which
+ * keeps a copy of it — own it by refcount. `r(session)` also queues a direct
+ * `session.delete()` for when the scope is garbage-collected. All three run
+ * from replicad's FinalizationRegistry, in whatever order V8 picks: whichever
+ * frees the session second frees it twice. That shows up as "function
+ * signature mismatch" or "table index is out of bounds" in the finalizer (the
+ * session's vtable is already gone) and, a few allocations later, as "memory
+ * access out of bounds" in whatever OCCT call comes next. It lands whenever GC
+ * runs, so it hits the call AFTER an export, not the export.
+ *
+ * Here every object has exactly one owner: transients are reached only
+ * through their Handle, and everything is deleted before returning, in an
+ * order that never touches freed memory. Nothing is left for GC to free.
+ * The output matches replicad's: same writer settings, names and colours.
+ */
+
+/** One part of the file. The same shape `exportSTEP` takes. */
+export interface StepPart {
+ shape: { wrapped: unknown };
+ name?: string;
+ /** Hex, `#rgb` or `#rrggbb`. Defaults to replicad's `#f00`. */
+ color?: string;
+ alpha?: number;
+}
+
+export interface StepUnits {
+ unit?: string;
+ modelUnit?: string;
+}
+
+interface Deletable {
+ delete(): void;
+}
+
+/** Emscripten FS path the writer goes through. Unlinked before returning. */
+const STEP_FILE = "shapeitup-export.step";
+
+/** Write `parts` as one STEP file and return its bytes. */
+export function writeStep(
+ oc: any,
+ parts: StepPart[],
+ { unit, modelUnit }: StepUnits = {},
+): Uint8Array {
+ // Deleted last-in-first-out, so the writer goes before the session it holds
+ // and every label and attribute handle before the document they live in.
+ const owned: Deletable[] = [];
+ const own = (value: T): T => {
+ owned.push(value);
+ return value;
+ };
+ const text = (s: string) => own(new oc.TCollection_ExtendedString_2(s, true));
+
+ try {
+ const doc = own(new oc.Handle_TDocStd_Document_2(new oc.TDocStd_Document(text("XmlOcaf"))));
+ oc.XCAFDoc_ShapeTool.SetAutoNaming(false);
+ const mainLabel = own(doc.get().Main());
+ const shapeTool = own(oc.XCAFDoc_DocumentTool.ShapeTool(mainLabel)).get();
+ const colorTool = own(oc.XCAFDoc_DocumentTool.ColorTool(mainLabel)).get();
+ for (const { shape, name, color, alpha } of parts) {
+ const node = own(shapeTool.NewShape());
+ shapeTool.SetShape(node, shape.wrapped);
+ own(oc.TDataStd_Name.Set_1(node, text(name || uuid())));
+ colorTool.SetColor_3(node, own(rgba(oc, color || "#f00", alpha ?? 1)), oc.XCAFDoc_ColorType.XCAFDoc_ColorSurf);
+ }
+ shapeTool.UpdateAssemblies();
+
+ if (unit || modelUnit) {
+ // Constructing a writer registers the STEP parameters SetCVal writes to.
+ own(new oc.STEPCAFControl_Writer_1());
+ oc.Interface_Static.SetCVal("xstep.cascade.unit", (modelUnit || unit || "MM").toUpperCase());
+ oc.Interface_Static.SetCVal("write.step.unit", (unit || modelUnit || "MM").toUpperCase());
+ }
+
+ // The session is owned by its Handle alone. It is freed when the last
+ // Handle to it goes, which is this one, after the writer's copy.
+ const session = own(new oc.Handle_XSControl_WorkSession_2(new oc.XSControl_WorkSession()));
+ const writer = own(new oc.STEPCAFControl_Writer_2(session, false));
+ writer.SetColorMode(true);
+ writer.SetLayerMode(true);
+ writer.SetNameMode(true);
+ oc.Interface_Static.SetIVal("write.surfacecurve.mode", true);
+ oc.Interface_Static.SetIVal("write.precision.mode", 0);
+ oc.Interface_Static.SetIVal("write.step.assembly", 2);
+ oc.Interface_Static.SetIVal("write.step.schema", 5);
+ writer.Transfer_1(doc, oc.STEPControl_StepModelType.STEPControl_AsIs, null, own(new oc.Message_ProgressRange_1()));
+
+ if (writer.Write(STEP_FILE) !== oc.IFSelect_ReturnStatus.IFSelect_RetDone) {
+ throw new Error("WRITE STEP FILE FAILED.");
+ }
+ // A fresh copy, not a view into the WASM heap.
+ const bytes: Uint8Array = oc.FS.readFile("/" + STEP_FILE);
+ oc.FS.unlink("/" + STEP_FILE);
+ return bytes;
+ } finally {
+ for (let i = owned.length - 1; i >= 0; i--) {
+ try {
+ owned[i].delete();
+ } catch {
+ // Already broken; one leak beats aborting the rest of the cleanup.
+ }
+ }
+ }
+}
+
+/**
+ * Drop-in for replicad's `exportSTEP`, for scripts that call it themselves:
+ * same arguments, same Blob.
+ */
+export function makeExportSTEP(getOC: () => any) {
+ return function exportSTEP(parts: StepPart[] = [], units: StepUnits = {}): Blob {
+ return new Blob([writeStep(getOC(), parts, units)], { type: "application/STEP" });
+ };
+}
+
+function rgba(oc: any, hex: string, alpha: number): Deletable {
+ let h = hex.startsWith("#") ? hex.slice(1) : hex;
+ if (h.length === 3) h = h.replace(/([0-9a-f])/gi, "$1$1");
+ const channel = (i: number) => parseInt(h.slice(i * 2, i * 2 + 2), 16) / 255;
+ return new oc.Quantity_ColorRGBA_5(channel(0), channel(1), channel(2), alpha);
+}
+
+/** Replicad names unnamed parts with a random v4-style UUID; so does this. */
+function uuid(): string {
+ return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) =>
+ (Number(c) ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (Number(c) / 4)))).toString(16),
+ );
+}
diff --git a/packages/core/src/testing/fixtures/block-40x30x10.step b/packages/core/src/testing/fixtures/block-40x30x10.step
new file mode 100644
index 0000000..545c456
--- /dev/null
+++ b/packages/core/src/testing/fixtures/block-40x30x10.step
@@ -0,0 +1,424 @@
+ISO-10303-21;
+HEADER;
+FILE_DESCRIPTION(('Open CASCADE Model'),'2;1');
+FILE_NAME('Open CASCADE Shape Model','2026-10-22T18:23:01',('Author'),(
+ 'Open CASCADE'),'Open CASCADE STEP processor 7.6','Open CASCADE 7.6'
+ ,'Unknown');
+FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));
+ENDSEC;
+DATA;
+#1 = APPLICATION_PROTOCOL_DEFINITION('international standard',
+ 'ap242_managed_model_based_3d_engineering',2013,#2);
+#2 = APPLICATION_CONTEXT('Managed model based 3d engineering');
+#3 = SHAPE_DEFINITION_REPRESENTATION(#4,#10);
+#4 = PRODUCT_DEFINITION_SHAPE('','',#5);
+#5 = PRODUCT_DEFINITION('design','',#6,#9);
+#6 = PRODUCT_DEFINITION_FORMATION('','',#7);
+#7 = PRODUCT('block','block','',(#8));
+#8 = PRODUCT_CONTEXT('',#2,'mechanical');
+#9 = PRODUCT_DEFINITION_CONTEXT('part definition',#2,'design');
+#10 = ADVANCED_BREP_SHAPE_REPRESENTATION('',(#11,#15),#345);
+#11 = AXIS2_PLACEMENT_3D('',#12,#13,#14);
+#12 = CARTESIAN_POINT('',(0.,0.,0.));
+#13 = DIRECTION('',(0.,0.,1.));
+#14 = DIRECTION('',(1.,0.,-0.));
+#15 = MANIFOLD_SOLID_BREP('',#16);
+#16 = CLOSED_SHELL('',(#17,#137,#213,#284,#331,#338));
+#17 = ADVANCED_FACE('',(#18),#32,.F.);
+#18 = FACE_BOUND('',#19,.F.);
+#19 = EDGE_LOOP('',(#20,#55,#83,#111));
+#20 = ORIENTED_EDGE('',*,*,#21,.T.);
+#21 = EDGE_CURVE('',#22,#24,#26,.T.);
+#22 = VERTEX_POINT('',#23);
+#23 = CARTESIAN_POINT('',(-20.,-15.,0.));
+#24 = VERTEX_POINT('',#25);
+#25 = CARTESIAN_POINT('',(-20.,-15.,10.));
+#26 = SURFACE_CURVE('',#27,(#31,#43),.PCURVE_S1.);
+#27 = LINE('',#28,#29);
+#28 = CARTESIAN_POINT('',(-20.,-15.,0.));
+#29 = VECTOR('',#30,1.);
+#30 = DIRECTION('',(0.,0.,1.));
+#31 = PCURVE('',#32,#37);
+#32 = PLANE('',#33);
+#33 = AXIS2_PLACEMENT_3D('',#34,#35,#36);
+#34 = CARTESIAN_POINT('',(-20.,-15.,0.));
+#35 = DIRECTION('',(0.,1.,0.));
+#36 = DIRECTION('',(1.,0.,0.));
+#37 = DEFINITIONAL_REPRESENTATION('',(#38),#42);
+#38 = LINE('',#39,#40);
+#39 = CARTESIAN_POINT('',(0.,0.));
+#40 = VECTOR('',#41,1.);
+#41 = DIRECTION('',(0.,-1.));
+#42 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#43 = PCURVE('',#44,#49);
+#44 = PLANE('',#45);
+#45 = AXIS2_PLACEMENT_3D('',#46,#47,#48);
+#46 = CARTESIAN_POINT('',(-20.,15.,0.));
+#47 = DIRECTION('',(1.,0.,-0.));
+#48 = DIRECTION('',(0.,-1.,0.));
+#49 = DEFINITIONAL_REPRESENTATION('',(#50),#54);
+#50 = LINE('',#51,#52);
+#51 = CARTESIAN_POINT('',(30.,0.));
+#52 = VECTOR('',#53,1.);
+#53 = DIRECTION('',(0.,-1.));
+#54 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#55 = ORIENTED_EDGE('',*,*,#56,.T.);
+#56 = EDGE_CURVE('',#24,#57,#59,.T.);
+#57 = VERTEX_POINT('',#58);
+#58 = CARTESIAN_POINT('',(20.,-15.,10.));
+#59 = SURFACE_CURVE('',#60,(#64,#71),.PCURVE_S1.);
+#60 = LINE('',#61,#62);
+#61 = CARTESIAN_POINT('',(-20.,-15.,10.));
+#62 = VECTOR('',#63,1.);
+#63 = DIRECTION('',(1.,0.,0.));
+#64 = PCURVE('',#32,#65);
+#65 = DEFINITIONAL_REPRESENTATION('',(#66),#70);
+#66 = LINE('',#67,#68);
+#67 = CARTESIAN_POINT('',(0.,-10.));
+#68 = VECTOR('',#69,1.);
+#69 = DIRECTION('',(1.,0.));
+#70 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#71 = PCURVE('',#72,#77);
+#72 = PLANE('',#73);
+#73 = AXIS2_PLACEMENT_3D('',#74,#75,#76);
+#74 = CARTESIAN_POINT('',(0.,0.,10.));
+#75 = DIRECTION('',(0.,0.,1.));
+#76 = DIRECTION('',(1.,0.,-0.));
+#77 = DEFINITIONAL_REPRESENTATION('',(#78),#82);
+#78 = LINE('',#79,#80);
+#79 = CARTESIAN_POINT('',(-20.,-15.));
+#80 = VECTOR('',#81,1.);
+#81 = DIRECTION('',(1.,0.));
+#82 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#83 = ORIENTED_EDGE('',*,*,#84,.F.);
+#84 = EDGE_CURVE('',#85,#57,#87,.T.);
+#85 = VERTEX_POINT('',#86);
+#86 = CARTESIAN_POINT('',(20.,-15.,0.));
+#87 = SURFACE_CURVE('',#88,(#92,#99),.PCURVE_S1.);
+#88 = LINE('',#89,#90);
+#89 = CARTESIAN_POINT('',(20.,-15.,0.));
+#90 = VECTOR('',#91,1.);
+#91 = DIRECTION('',(0.,0.,1.));
+#92 = PCURVE('',#32,#93);
+#93 = DEFINITIONAL_REPRESENTATION('',(#94),#98);
+#94 = LINE('',#95,#96);
+#95 = CARTESIAN_POINT('',(40.,0.));
+#96 = VECTOR('',#97,1.);
+#97 = DIRECTION('',(0.,-1.));
+#98 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#99 = PCURVE('',#100,#105);
+#100 = PLANE('',#101);
+#101 = AXIS2_PLACEMENT_3D('',#102,#103,#104);
+#102 = CARTESIAN_POINT('',(20.,-15.,0.));
+#103 = DIRECTION('',(-1.,0.,0.));
+#104 = DIRECTION('',(0.,1.,0.));
+#105 = DEFINITIONAL_REPRESENTATION('',(#106),#110);
+#106 = LINE('',#107,#108);
+#107 = CARTESIAN_POINT('',(0.,0.));
+#108 = VECTOR('',#109,1.);
+#109 = DIRECTION('',(0.,-1.));
+#110 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#111 = ORIENTED_EDGE('',*,*,#112,.F.);
+#112 = EDGE_CURVE('',#22,#85,#113,.T.);
+#113 = SURFACE_CURVE('',#114,(#118,#125),.PCURVE_S1.);
+#114 = LINE('',#115,#116);
+#115 = CARTESIAN_POINT('',(-20.,-15.,0.));
+#116 = VECTOR('',#117,1.);
+#117 = DIRECTION('',(1.,0.,0.));
+#118 = PCURVE('',#32,#119);
+#119 = DEFINITIONAL_REPRESENTATION('',(#120),#124);
+#120 = LINE('',#121,#122);
+#121 = CARTESIAN_POINT('',(0.,0.));
+#122 = VECTOR('',#123,1.);
+#123 = DIRECTION('',(1.,0.));
+#124 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#125 = PCURVE('',#126,#131);
+#126 = PLANE('',#127);
+#127 = AXIS2_PLACEMENT_3D('',#128,#129,#130);
+#128 = CARTESIAN_POINT('',(0.,0.,0.));
+#129 = DIRECTION('',(0.,0.,1.));
+#130 = DIRECTION('',(1.,0.,-0.));
+#131 = DEFINITIONAL_REPRESENTATION('',(#132),#136);
+#132 = LINE('',#133,#134);
+#133 = CARTESIAN_POINT('',(-20.,-15.));
+#134 = VECTOR('',#135,1.);
+#135 = DIRECTION('',(1.,0.));
+#136 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#137 = ADVANCED_FACE('',(#138),#100,.F.);
+#138 = FACE_BOUND('',#139,.F.);
+#139 = EDGE_LOOP('',(#140,#141,#164,#192));
+#140 = ORIENTED_EDGE('',*,*,#84,.T.);
+#141 = ORIENTED_EDGE('',*,*,#142,.T.);
+#142 = EDGE_CURVE('',#57,#143,#145,.T.);
+#143 = VERTEX_POINT('',#144);
+#144 = CARTESIAN_POINT('',(20.,15.,10.));
+#145 = SURFACE_CURVE('',#146,(#150,#157),.PCURVE_S1.);
+#146 = LINE('',#147,#148);
+#147 = CARTESIAN_POINT('',(20.,-15.,10.));
+#148 = VECTOR('',#149,1.);
+#149 = DIRECTION('',(0.,1.,0.));
+#150 = PCURVE('',#100,#151);
+#151 = DEFINITIONAL_REPRESENTATION('',(#152),#156);
+#152 = LINE('',#153,#154);
+#153 = CARTESIAN_POINT('',(0.,-10.));
+#154 = VECTOR('',#155,1.);
+#155 = DIRECTION('',(1.,0.));
+#156 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#157 = PCURVE('',#72,#158);
+#158 = DEFINITIONAL_REPRESENTATION('',(#159),#163);
+#159 = LINE('',#160,#161);
+#160 = CARTESIAN_POINT('',(20.,-15.));
+#161 = VECTOR('',#162,1.);
+#162 = DIRECTION('',(0.,1.));
+#163 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#164 = ORIENTED_EDGE('',*,*,#165,.F.);
+#165 = EDGE_CURVE('',#166,#143,#168,.T.);
+#166 = VERTEX_POINT('',#167);
+#167 = CARTESIAN_POINT('',(20.,15.,0.));
+#168 = SURFACE_CURVE('',#169,(#173,#180),.PCURVE_S1.);
+#169 = LINE('',#170,#171);
+#170 = CARTESIAN_POINT('',(20.,15.,0.));
+#171 = VECTOR('',#172,1.);
+#172 = DIRECTION('',(0.,0.,1.));
+#173 = PCURVE('',#100,#174);
+#174 = DEFINITIONAL_REPRESENTATION('',(#175),#179);
+#175 = LINE('',#176,#177);
+#176 = CARTESIAN_POINT('',(30.,0.));
+#177 = VECTOR('',#178,1.);
+#178 = DIRECTION('',(0.,-1.));
+#179 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#180 = PCURVE('',#181,#186);
+#181 = PLANE('',#182);
+#182 = AXIS2_PLACEMENT_3D('',#183,#184,#185);
+#183 = CARTESIAN_POINT('',(20.,15.,0.));
+#184 = DIRECTION('',(0.,-1.,0.));
+#185 = DIRECTION('',(-1.,0.,0.));
+#186 = DEFINITIONAL_REPRESENTATION('',(#187),#191);
+#187 = LINE('',#188,#189);
+#188 = CARTESIAN_POINT('',(0.,-0.));
+#189 = VECTOR('',#190,1.);
+#190 = DIRECTION('',(0.,-1.));
+#191 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#192 = ORIENTED_EDGE('',*,*,#193,.F.);
+#193 = EDGE_CURVE('',#85,#166,#194,.T.);
+#194 = SURFACE_CURVE('',#195,(#199,#206),.PCURVE_S1.);
+#195 = LINE('',#196,#197);
+#196 = CARTESIAN_POINT('',(20.,-15.,0.));
+#197 = VECTOR('',#198,1.);
+#198 = DIRECTION('',(0.,1.,0.));
+#199 = PCURVE('',#100,#200);
+#200 = DEFINITIONAL_REPRESENTATION('',(#201),#205);
+#201 = LINE('',#202,#203);
+#202 = CARTESIAN_POINT('',(0.,0.));
+#203 = VECTOR('',#204,1.);
+#204 = DIRECTION('',(1.,0.));
+#205 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#206 = PCURVE('',#126,#207);
+#207 = DEFINITIONAL_REPRESENTATION('',(#208),#212);
+#208 = LINE('',#209,#210);
+#209 = CARTESIAN_POINT('',(20.,-15.));
+#210 = VECTOR('',#211,1.);
+#211 = DIRECTION('',(0.,1.));
+#212 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#213 = ADVANCED_FACE('',(#214),#181,.F.);
+#214 = FACE_BOUND('',#215,.F.);
+#215 = EDGE_LOOP('',(#216,#217,#240,#263));
+#216 = ORIENTED_EDGE('',*,*,#165,.T.);
+#217 = ORIENTED_EDGE('',*,*,#218,.T.);
+#218 = EDGE_CURVE('',#143,#219,#221,.T.);
+#219 = VERTEX_POINT('',#220);
+#220 = CARTESIAN_POINT('',(-20.,15.,10.));
+#221 = SURFACE_CURVE('',#222,(#226,#233),.PCURVE_S1.);
+#222 = LINE('',#223,#224);
+#223 = CARTESIAN_POINT('',(20.,15.,10.));
+#224 = VECTOR('',#225,1.);
+#225 = DIRECTION('',(-1.,0.,0.));
+#226 = PCURVE('',#181,#227);
+#227 = DEFINITIONAL_REPRESENTATION('',(#228),#232);
+#228 = LINE('',#229,#230);
+#229 = CARTESIAN_POINT('',(0.,-10.));
+#230 = VECTOR('',#231,1.);
+#231 = DIRECTION('',(1.,0.));
+#232 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#233 = PCURVE('',#72,#234);
+#234 = DEFINITIONAL_REPRESENTATION('',(#235),#239);
+#235 = LINE('',#236,#237);
+#236 = CARTESIAN_POINT('',(20.,15.));
+#237 = VECTOR('',#238,1.);
+#238 = DIRECTION('',(-1.,0.));
+#239 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#240 = ORIENTED_EDGE('',*,*,#241,.F.);
+#241 = EDGE_CURVE('',#242,#219,#244,.T.);
+#242 = VERTEX_POINT('',#243);
+#243 = CARTESIAN_POINT('',(-20.,15.,0.));
+#244 = SURFACE_CURVE('',#245,(#249,#256),.PCURVE_S1.);
+#245 = LINE('',#246,#247);
+#246 = CARTESIAN_POINT('',(-20.,15.,0.));
+#247 = VECTOR('',#248,1.);
+#248 = DIRECTION('',(0.,0.,1.));
+#249 = PCURVE('',#181,#250);
+#250 = DEFINITIONAL_REPRESENTATION('',(#251),#255);
+#251 = LINE('',#252,#253);
+#252 = CARTESIAN_POINT('',(40.,0.));
+#253 = VECTOR('',#254,1.);
+#254 = DIRECTION('',(0.,-1.));
+#255 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#256 = PCURVE('',#44,#257);
+#257 = DEFINITIONAL_REPRESENTATION('',(#258),#262);
+#258 = LINE('',#259,#260);
+#259 = CARTESIAN_POINT('',(0.,0.));
+#260 = VECTOR('',#261,1.);
+#261 = DIRECTION('',(0.,-1.));
+#262 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#263 = ORIENTED_EDGE('',*,*,#264,.F.);
+#264 = EDGE_CURVE('',#166,#242,#265,.T.);
+#265 = SURFACE_CURVE('',#266,(#270,#277),.PCURVE_S1.);
+#266 = LINE('',#267,#268);
+#267 = CARTESIAN_POINT('',(20.,15.,0.));
+#268 = VECTOR('',#269,1.);
+#269 = DIRECTION('',(-1.,0.,0.));
+#270 = PCURVE('',#181,#271);
+#271 = DEFINITIONAL_REPRESENTATION('',(#272),#276);
+#272 = LINE('',#273,#274);
+#273 = CARTESIAN_POINT('',(0.,-0.));
+#274 = VECTOR('',#275,1.);
+#275 = DIRECTION('',(1.,0.));
+#276 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#277 = PCURVE('',#126,#278);
+#278 = DEFINITIONAL_REPRESENTATION('',(#279),#283);
+#279 = LINE('',#280,#281);
+#280 = CARTESIAN_POINT('',(20.,15.));
+#281 = VECTOR('',#282,1.);
+#282 = DIRECTION('',(-1.,0.));
+#283 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#284 = ADVANCED_FACE('',(#285),#44,.F.);
+#285 = FACE_BOUND('',#286,.F.);
+#286 = EDGE_LOOP('',(#287,#288,#309,#310));
+#287 = ORIENTED_EDGE('',*,*,#241,.T.);
+#288 = ORIENTED_EDGE('',*,*,#289,.T.);
+#289 = EDGE_CURVE('',#219,#24,#290,.T.);
+#290 = SURFACE_CURVE('',#291,(#295,#302),.PCURVE_S1.);
+#291 = LINE('',#292,#293);
+#292 = CARTESIAN_POINT('',(-20.,15.,10.));
+#293 = VECTOR('',#294,1.);
+#294 = DIRECTION('',(0.,-1.,-0.));
+#295 = PCURVE('',#44,#296);
+#296 = DEFINITIONAL_REPRESENTATION('',(#297),#301);
+#297 = LINE('',#298,#299);
+#298 = CARTESIAN_POINT('',(0.,-10.));
+#299 = VECTOR('',#300,1.);
+#300 = DIRECTION('',(1.,0.));
+#301 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#302 = PCURVE('',#72,#303);
+#303 = DEFINITIONAL_REPRESENTATION('',(#304),#308);
+#304 = LINE('',#305,#306);
+#305 = CARTESIAN_POINT('',(-20.,15.));
+#306 = VECTOR('',#307,1.);
+#307 = DIRECTION('',(0.,-1.));
+#308 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#309 = ORIENTED_EDGE('',*,*,#21,.F.);
+#310 = ORIENTED_EDGE('',*,*,#311,.F.);
+#311 = EDGE_CURVE('',#242,#22,#312,.T.);
+#312 = SURFACE_CURVE('',#313,(#317,#324),.PCURVE_S1.);
+#313 = LINE('',#314,#315);
+#314 = CARTESIAN_POINT('',(-20.,15.,0.));
+#315 = VECTOR('',#316,1.);
+#316 = DIRECTION('',(0.,-1.,-0.));
+#317 = PCURVE('',#44,#318);
+#318 = DEFINITIONAL_REPRESENTATION('',(#319),#323);
+#319 = LINE('',#320,#321);
+#320 = CARTESIAN_POINT('',(0.,0.));
+#321 = VECTOR('',#322,1.);
+#322 = DIRECTION('',(1.,0.));
+#323 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#324 = PCURVE('',#126,#325);
+#325 = DEFINITIONAL_REPRESENTATION('',(#326),#330);
+#326 = LINE('',#327,#328);
+#327 = CARTESIAN_POINT('',(-20.,15.));
+#328 = VECTOR('',#329,1.);
+#329 = DIRECTION('',(0.,-1.));
+#330 = ( GEOMETRIC_REPRESENTATION_CONTEXT(2)
+PARAMETRIC_REPRESENTATION_CONTEXT() REPRESENTATION_CONTEXT('2D SPACE',''
+ ) );
+#331 = ADVANCED_FACE('',(#332),#126,.F.);
+#332 = FACE_BOUND('',#333,.F.);
+#333 = EDGE_LOOP('',(#334,#335,#336,#337));
+#334 = ORIENTED_EDGE('',*,*,#112,.T.);
+#335 = ORIENTED_EDGE('',*,*,#193,.T.);
+#336 = ORIENTED_EDGE('',*,*,#264,.T.);
+#337 = ORIENTED_EDGE('',*,*,#311,.T.);
+#338 = ADVANCED_FACE('',(#339),#72,.T.);
+#339 = FACE_BOUND('',#340,.T.);
+#340 = EDGE_LOOP('',(#341,#342,#343,#344));
+#341 = ORIENTED_EDGE('',*,*,#56,.T.);
+#342 = ORIENTED_EDGE('',*,*,#142,.T.);
+#343 = ORIENTED_EDGE('',*,*,#218,.T.);
+#344 = ORIENTED_EDGE('',*,*,#289,.T.);
+#345 = ( GEOMETRIC_REPRESENTATION_CONTEXT(3)
+GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#349)) GLOBAL_UNIT_ASSIGNED_CONTEXT
+((#346,#347,#348)) REPRESENTATION_CONTEXT('Context #1',
+ '3D Context with UNIT and UNCERTAINTY') );
+#346 = ( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) );
+#347 = ( NAMED_UNIT(*) PLANE_ANGLE_UNIT() SI_UNIT($,.RADIAN.) );
+#348 = ( NAMED_UNIT(*) SI_UNIT($,.STERADIAN.) SOLID_ANGLE_UNIT() );
+#349 = UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-07),#346,
+ 'distance_accuracy_value','confusion accuracy');
+#350 = PRODUCT_RELATED_PRODUCT_CATEGORY('part',$,(#7));
+#351 = MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('',(#352)
+ ,#345);
+#352 = STYLED_ITEM('color',(#353),#15);
+#353 = PRESENTATION_STYLE_ASSIGNMENT((#354));
+#354 = SURFACE_STYLE_USAGE(.BOTH.,#355);
+#355 = SURFACE_SIDE_STYLE('',(#356));
+#356 = SURFACE_STYLE_FILL_AREA(#357);
+#357 = FILL_AREA_STYLE('',(#358));
+#358 = FILL_AREA_STYLE_COLOUR('',#359);
+#359 = DRAUGHTING_PRE_DEFINED_COLOUR('red');
+ENDSEC;
+END-ISO-10303-21;
diff --git a/packages/extension/package.json b/packages/extension/package.json
index 120dc23..73f7568 100644
--- a/packages/extension/package.json
+++ b/packages/extension/package.json
@@ -2,7 +2,7 @@
"name": "shapeitup-vscode",
"displayName": "ShapeItUp",
"description": "Scripted CAD for VS Code — write TypeScript, see 3D, export STEP/STL/3MF (Bambu Studio & OrcaSlicer ready). AI-powered with Claude Code MCP integration.",
- "version": "1.30.1",
+ "version": "1.31.1",
"publisher": "shapeitup",
"license": "MIT",
"icon": "icon.png",
diff --git a/packages/extension/src/viewer-provider.ts b/packages/extension/src/viewer-provider.ts
index 1443515..b6fbf0b 100644
--- a/packages/extension/src/viewer-provider.ts
+++ b/packages/extension/src/viewer-provider.ts
@@ -15,6 +15,7 @@ import {
renderViewerHtml,
computeParamEdit,
isOptionalReexportWarning,
+ SHAPE_BUNDLE_LOADERS,
type ExportFormat,
type ParamCommitResult,
type FaceOpResultMessage,
@@ -1266,8 +1267,9 @@ export class ViewerProvider implements vscode.WebviewViewProvider {
metafile: true,
// With the synthetic wrapper the user's file is resolved by its
// full `.shape.ts` absolute path. esbuild dispatches on the FULL
- // extension, so map `.shape.ts` and `.shape` explicitly to TS.
- loader: { ".shape.ts": "ts", ".shape": "ts" },
+ // extension, so map `.shape.ts` and `.shape` explicitly to TS. The
+ // shared map also loads `.step` / `.stp` as bytes for `importStep`.
+ loader: { ...SHAPE_BUNDLE_LOADERS },
// `sourcemap: "inline"` appends `//# sourceMappingURL=data:...` to
// the bundle. V8 uses that (together with the `//# sourceURL=`
// directive the core executor emits) to resolve user-script stack
diff --git a/packages/extension/typings/shapeitup/index.d.ts b/packages/extension/typings/shapeitup/index.d.ts
index f5f0158..be6dee2 100644
--- a/packages/extension/typings/shapeitup/index.d.ts
+++ b/packages/extension/typings/shapeitup/index.d.ts
@@ -1,3 +1,4 @@
+///
// Ambient typings for the virtual "shapeitup" import source used in .shape.ts
// files. The runtime executor rewrites `import { ... } from "shapeitup"` to
// destructure from an injected object — this file just gives the editor's
diff --git a/packages/extension/typings/shapeitup/step-imports.d.ts b/packages/extension/typings/shapeitup/step-imports.d.ts
new file mode 100644
index 0000000..69875b2
--- /dev/null
+++ b/packages/extension/typings/shapeitup/step-imports.d.ts
@@ -0,0 +1,25 @@
+// Ambient module types for the files ShapeItUp's bundler loads as raw bytes.
+// `import part from "./input.step"` gives a Uint8Array to pass to
+// `importStep` from "shapeitup". Kept as a script file (no import/export) so
+// the wildcard declarations are global; index.d.ts pulls it in by reference.
+//
+// The extension build copies this file next to the generated wrapper
+// (esbuild.config.mjs › copyExtensionTypings). The extension list mirrors
+// SHAPE_BUNDLE_LOADERS in packages/shared/src/bundle-spec.ts.
+
+declare module "*.step" {
+ const bytes: Uint8Array;
+ export default bytes;
+}
+declare module "*.stp" {
+ const bytes: Uint8Array;
+ export default bytes;
+}
+declare module "*.STEP" {
+ const bytes: Uint8Array;
+ export default bytes;
+}
+declare module "*.STP" {
+ const bytes: Uint8Array;
+ export default bytes;
+}
diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json
index c3c56c9..9269d8c 100644
--- a/packages/mcp-server/package.json
+++ b/packages/mcp-server/package.json
@@ -1,6 +1,6 @@
{
"name": "@shapeitup/mcp-server",
- "version": "1.30.1",
+ "version": "1.31.1",
"description": "ShapeItUp MCP server — scripted CAD tools (Replicad/OpenCascade) for Claude Code, Codex, Cursor, Claude Desktop, and other MCP clients.",
"type": "module",
"bin": {
diff --git a/packages/mcp-server/src/engine.ts b/packages/mcp-server/src/engine.ts
index 16f2c0b..e0be037 100644
--- a/packages/mcp-server/src/engine.ts
+++ b/packages/mcp-server/src/engine.ts
@@ -28,7 +28,7 @@ import {
type Core,
type ExecutedPart,
} from "@shapeitup/core";
-import { isOptionalReexportWarning, type ParamValue } from "@shapeitup/shared";
+import { isOptionalReexportWarning, SHAPE_BUNDLE_LOADERS, type ParamValue } from "@shapeitup/shared";
import * as esbuild from "esbuild-wasm";
// esbuild-wasm requires a one-shot initialize() before the first build().
@@ -1176,8 +1176,9 @@ export async function executeShapeFile(
// FULL extension — map it explicitly to the TS loader. `.ts` remains
// the default. Imported sibling `.shape` files (the form without the
// trailing `.ts`, common in the skill docs) resolve via esbuild's
- // module resolver and also need the loader override.
- loader: { ".shape.ts": "ts", ".shape": "ts" },
+ // module resolver and also need the loader override. The shared map also
+ // loads `.step` / `.stp` as bytes for the stdlib's `importStep`.
+ loader: { ...SHAPE_BUNDLE_LOADERS },
// Let a bare local import resolve to a sibling `.shape.ts`. Defaults come
// FIRST so existing behavior is unchanged (`./needle-spec` → needle-spec.ts,
// `./foo.shape` → foo.shape.ts via `.ts`); `.shape.ts` / `.shape` are
diff --git a/packages/mcp-server/src/export-rebundle.test.ts b/packages/mcp-server/src/export-rebundle.test.ts
new file mode 100644
index 0000000..e11d332
--- /dev/null
+++ b/packages/mcp-server/src/export-rebundle.test.ts
@@ -0,0 +1,74 @@
+import { describe, it, expect, vi } from "vitest";
+import { executeShapeFile, exportLastToFile } from "./engine.js";
+import { mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+// The sequence a benchmark run makes in one long-lived process: render, export
+// STEP, the next script's local dependency changes, render again.
+//
+// Replicad's exportSTEP hands its XSControl_WorkSession both to a GC scope that
+// deletes it directly and to a refcounting Handle the writer shares. Whichever
+// of those frees it second frees it twice — once GC got round to the scope,
+// usually during the rebundle's esbuild-wasm allocations. The render after it
+// then died with "memory access out of bounds" about 4 runs in 5, and the
+// rest logged "function signature mismatch" from the finalizer. Core now
+// writes STEP itself (core/src/step-writer.ts) with one owner per object.
+describe("STEP export, then a rebundle", () => {
+ it("leaves OCCT healthy for the next execution", async () => {
+ // Replicad's registry logs what its finalizers throw instead of rethrowing.
+ const errors = vi.spyOn(console, "error");
+ const workdir = mkdtempSync(join(tmpdir(), "siu-export-rebundle-"));
+ const storage = mkdtempSync(join(tmpdir(), "siu-export-rebundle-storage-"));
+ try {
+ const dep = join(workdir, "dep.ts");
+ writeFileSync(
+ dep,
+ [
+ `import { drawRoundedRectangle, makeCylinder } from "replicad";`,
+ `export function plate(width: number) {`,
+ ` return drawRoundedRectangle(width, 30, 3).sketchOnPlane("XY").extrude(8)`,
+ ` .cut(makeCylinder(4, 20, [0, 0, -5]))`,
+ ` .fillet(1);`,
+ `}`,
+ ].join("\n"),
+ );
+ const entry = join(workdir, "part.shape.ts");
+ writeFileSync(
+ entry,
+ [
+ `import { plate } from "./dep";`,
+ `export const params = { width: 40 };`,
+ `export default function main({ width }: typeof params) {`,
+ ` return { shape: plate(width), name: "plate" };`,
+ `}`,
+ ].join("\n"),
+ );
+
+ for (let round = 0; round < 4; round++) {
+ for (const width of [40 + round, 50 + round]) {
+ const exec = await executeShapeFile(entry, storage, { width });
+ expect(exec.status.error, `round ${round}, width ${width}`).toBeUndefined();
+ }
+
+ const out = join(workdir, `round-${round}.step`);
+ await exportLastToFile("step", out);
+ expect(readFileSync(out, "utf-8")).toMatch(/^ISO-10303-21;/);
+
+ // Only the dependency changes, so the next call must rebundle.
+ const later = new Date(Date.now() + 5_000 * (round + 1));
+ utimesSync(dep, later, later);
+
+ const after = await executeShapeFile(entry, storage, { width: 60 + round });
+ expect(after.status.error, `round ${round}, after export`).toBeUndefined();
+ expect(after.status.engineReset).toBeUndefined();
+ }
+ const wasmErrors = errors.mock.calls.filter(([e]) => e instanceof Error && e.name === "RuntimeError");
+ expect(wasmErrors.map(([e]) => String(e))).toEqual([]);
+ } finally {
+ errors.mockRestore();
+ rmSync(workdir, { recursive: true, force: true });
+ rmSync(storage, { recursive: true, force: true });
+ }
+ }, 120_000);
+});
diff --git a/packages/mcp-server/src/step-import.test.ts b/packages/mcp-server/src/step-import.test.ts
new file mode 100644
index 0000000..c1e593a
--- /dev/null
+++ b/packages/mcp-server/src/step-import.test.ts
@@ -0,0 +1,131 @@
+import { describe, it, expect } from "vitest";
+import { executeShapeFile, exportLastToFile } from "./engine.js";
+import { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync, utimesSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+// A 40 x 30 x 10 mm block ShapeItUp exported itself — see core's step.test.ts.
+const FIXTURE = fileURLToPath(
+ new URL("../../core/src/testing/fixtures/block-40x30x10.step", import.meta.url),
+);
+const BLOCK = 40 * 30 * 10;
+const hole = (r: number) => Math.PI * r * r * 10;
+
+// The editing flow end to end, through the engine calls `export_shape` makes:
+// esbuild-wasm inlines the STEP's bytes, the executor hands them to the
+// stdlib's `importStep`, OCCT cuts, and the result goes back out as STEP.
+// The export runs first on purpose, so the rebundle below follows an export:
+// that used to crash OCCT (see export-rebundle.test.ts).
+describe("STEP import — edit an existing part", () => {
+ const makeDirs = () => ({
+ workdir: mkdtempSync(join(tmpdir(), "siu-step-")),
+ storage: mkdtempSync(join(tmpdir(), "siu-step-storage-")),
+ });
+
+ const writeEdit = (path: string, inputSpec = "./input.step") =>
+ writeFileSync(
+ path,
+ [
+ `import { makeCylinder } from "replicad";`,
+ `import { importStep } from "shapeitup";`,
+ `import input from ${JSON.stringify(inputSpec)};`,
+ `export const params = { holeRadius: 5 };`,
+ `export default function main({ holeRadius }: typeof params) {`,
+ ` const part = importStep(input);`,
+ ` return { shape: part.cut(makeCylinder(holeRadius, 20, [0, 0, -5])), name: "block" };`,
+ `}`,
+ ].join("\n"),
+ );
+
+ it("imports a STEP, cuts a hole and exports STEP", async () => {
+ const { workdir, storage } = makeDirs();
+ try {
+ copyFileSync(FIXTURE, join(workdir, "input.step"));
+ const entry = join(workdir, "edit.shape.ts");
+ writeEdit(entry);
+
+ const exec = await executeShapeFile(entry, storage, undefined, { partStats: "full" });
+ expect(exec.status.error).toBeUndefined();
+ expect(exec.status.success).toBe(true);
+ expect(exec.status.partNames).toEqual(["block"]);
+ expect(exec.parts![0].volume).toBeCloseTo(BLOCK - hole(5), 0);
+
+ const out = join(workdir, "edited.step");
+ await exportLastToFile("step", out);
+ const step = readFileSync(out, "utf-8");
+ expect(step).toMatch(/^ISO-10303-21;/);
+ // The input is all planes; the hole is the only cylinder, at r = 5.
+ expect(step).toMatch(/CYLINDRICAL_SURFACE\('',#\d+,5\.\)/);
+ } finally {
+ rmSync(workdir, { recursive: true, force: true });
+ rmSync(storage, { recursive: true, force: true });
+ }
+ });
+
+ it("loads an upper-case .STP", async () => {
+ const { workdir, storage } = makeDirs();
+ try {
+ copyFileSync(FIXTURE, join(workdir, "INPUT.STP"));
+ const entry = join(workdir, "edit.shape.ts");
+ writeEdit(entry, "./INPUT.STP");
+ const exec = await executeShapeFile(entry, storage, undefined, { partStats: "full" });
+ expect(exec.status.error).toBeUndefined();
+ expect(exec.parts![0].volume).toBeCloseTo(BLOCK - hole(5), 0);
+ } finally {
+ rmSync(workdir, { recursive: true, force: true });
+ rmSync(storage, { recursive: true, force: true });
+ }
+ });
+
+ it("rebundles when the STEP file changes on disk", async () => {
+ const { workdir, storage } = makeDirs();
+ try {
+ const input = join(workdir, "input.step");
+ copyFileSync(FIXTURE, input);
+ const entry = join(workdir, "edit.shape.ts");
+ writeEdit(entry);
+ const first = await executeShapeFile(entry, storage);
+ expect(first.status.success).toBe(true);
+
+ // Only the imported file changes, not the entry. Stale bytes would
+ // render the block again; the new ones are not a STEP file at all.
+ writeFileSync(input, "solid cube\nendsolid cube\n");
+ const later = new Date(Date.now() + 5_000);
+ utimesSync(input, later, later);
+
+ const second = await executeShapeFile(entry, storage);
+ expect(second.status.success).toBe(false);
+ expect(second.status.error).toMatch(/not a STEP file/);
+ } finally {
+ rmSync(workdir, { recursive: true, force: true });
+ rmSync(storage, { recursive: true, force: true });
+ }
+ });
+
+ it("explains an async main instead of 'must return one of'", async () => {
+ const { workdir, storage } = makeDirs();
+ try {
+ copyFileSync(FIXTURE, join(workdir, "input.step"));
+ const entry = join(workdir, "async.shape.ts");
+ writeFileSync(
+ entry,
+ [
+ `import { importStep } from "shapeitup";`,
+ `import input from "./input.step";`,
+ `export default async function main() {`,
+ ` return importStep(input);`,
+ `}`,
+ ].join("\n"),
+ );
+ const exec = await executeShapeFile(entry, storage);
+ expect(exec.status.success).toBe(false);
+ expect(exec.status.error).toMatch(/main\(\) returned a Promise/);
+ expect(exec.status.error).toMatch(/importStep/);
+ expect(exec.status.error).not.toMatch(/must return one of/);
+ } finally {
+ rmSync(workdir, { recursive: true, force: true });
+ rmSync(storage, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/mcp-server/src/tools.test.ts b/packages/mcp-server/src/tools.test.ts
index d9e1149..b4461b1 100644
--- a/packages/mcp-server/src/tools.test.ts
+++ b/packages/mcp-server/src/tools.test.ts
@@ -1438,6 +1438,22 @@ describe("getApiReference — stdlib surface area bumps", () => {
});
});
+describe("getApiReference — importStep", () => {
+ it("keeps importStep in the compact stdlib view agents get by default", async () => {
+ const { getApiReference } = await import("./tools.js");
+ const sigs = extractSignatures(getApiReference("stdlib"), "stdlib");
+ expect(sigs).toMatch(/importStep\(bytes: Uint8Array \| ArrayBuffer \| string\) → Shape3D/);
+ });
+
+ it("points the export category at it, and away from replicad's async importSTEP", async () => {
+ const { getApiReference } = await import("./tools.js");
+ const ref = getApiReference("export");
+ expect(ref).toContain(`import input from "./input.step";`);
+ expect(ref).toContain("importStep(input)");
+ expect(ref).toContain("importSTEP(blob)`: it is async");
+ });
+});
+
describe("partExtendsBelowBed — below-z=0 rotation hint gating", () => {
// Real bug it should still catch: a part meant to rest on the bed, mostly
// above z=0 but rotated so an asymmetric chunk sinks below.
diff --git a/packages/mcp-server/src/tools.ts b/packages/mcp-server/src/tools.ts
index 06e8a11..b37d197 100644
--- a/packages/mcp-server/src/tools.ts
+++ b/packages/mcp-server/src/tools.ts
@@ -4728,7 +4728,7 @@ export function registerTools(server: McpServer) {
return {
content: [{
type: "text" as const,
- text: "Available API reference categories:\n- overview (start here)\n- drawing (2D shapes)\n- sketching (2D → 3D)\n- solids (3D operations)\n- booleans (cut, fuse, intersect)\n- modifications (fillet, chamfer, shell)\n- transforms (translate, rotate, mirror)\n- finders (edge/face selection)\n- export (STEP, STL)\n- examples (complete worked examples)\n- stdlib (mechanical/3D-print helpers: holes, screws, bearings, extrusions, print hints)\n\nCall get_api_reference with a category name for detailed docs, or pass `search` to search across all categories.",
+ text: "Available API reference categories:\n- overview (start here)\n- drawing (2D shapes)\n- sketching (2D → 3D)\n- solids (3D operations)\n- booleans (cut, fuse, intersect)\n- modifications (fillet, chamfer, shell)\n- transforms (translate, rotate, mirror)\n- finders (edge/face selection)\n- export (STEP, STL; importing a STEP to edit it)\n- examples (complete worked examples)\n- stdlib (mechanical/3D-print helpers: holes, screws, bearings, extrusions, print hints)\n\nCall get_api_reference with a category name for detailed docs, or pass `search` to search across all categories.",
}],
};
}
@@ -7901,7 +7901,26 @@ export_shape({ filePath: "assembly.shape.ts", format: "stl", partName: "bolt" })
// → writes assembly.bolt.stl
\`\`\`
-Runs fully in-process, no VSCode needed.`,
+Runs fully in-process, no VSCode needed.
+
+## Importing STEP — edit an existing part
+
+Import the file like a local module (\`.step\` / \`.stp\`, any case — it is
+bundled as a \`Uint8Array\`) and convert it with the stdlib's synchronous
+\`importStep\`. Then edit and export it like any other shape:
+
+\`\`\`typescript
+import { makeCylinder } from "replicad";
+import { importStep } from "shapeitup";
+import input from "./input.step";
+
+export default function main() {
+ return importStep(input).cut(makeCylinder(3, 50, [10, 5, -1]));
+}
+\`\`\`
+
+Do not use Replicad's \`importSTEP(blob)\`: it is async, and \`main()\` runs
+synchronously. See the \`stdlib\` category for the details.`,
examples: `# Example Shape Scripts
## Box with Hole and Fillets
@@ -8560,6 +8579,38 @@ Join, Cut or Intersect.
---
+## Importing STEP — \`importStep\`
+
+- \`importStep(bytes: Uint8Array | ArrayBuffer | string) → Shape3D\` — synchronous; a \`Solid\` for a one-body file, a \`Compound\` for several
+
+Edit a part you did not model. Import the file like a local module — the
+bundler inlines \`.step\` / \`.stp\` (any case) as a \`Uint8Array\` — and pass
+the bytes in:
+
+\`\`\`typescript
+import { makeCylinder } from "replicad";
+import { importStep } from "shapeitup";
+import input from "./input.step"; // path relative to this .shape.ts
+
+export default function main() {
+ const part = importStep(input);
+ return part.cut(makeCylinder(3, 50, [10, 5, -1])); // through-hole at (10, 5)
+}
+\`\`\`
+
+- Lengths come back in mm whatever unit the file uses. Names and colours in
+ the file are not read — geometry only.
+- Replicad's own \`importSTEP(blob)\` is async and cannot be used: \`main()\`
+ runs synchronously, so an \`async main\` or a returned Promise fails with
+ "main() returned a Promise".
+- There is no feature history. Measure first (return \`importStep(input)\`
+ alone and run \`describe_geometry\`, or read \`shape.boundingBox\`), then
+ select existing faces and edges with finders.
+- Passing a path string (\`importStep("./input.step")\`) throws: it takes the
+ bytes. Saving a new version of the STEP file re-renders the script.
+
+---
+
## Copies — mirror and pattern
\`\`\`typescript
diff --git a/packages/serve/src/bundle.test.ts b/packages/serve/src/bundle.test.ts
new file mode 100644
index 0000000..c5dc010
--- /dev/null
+++ b/packages/serve/src/bundle.test.ts
@@ -0,0 +1,44 @@
+/**
+ * The serve host's native-esbuild bundler, on a script that imports STEP files.
+ *
+ * `SHAPE_BUNDLE_LOADERS` maps `.step` / `.stp` to esbuild's `binary` loader, so
+ * the bytes travel inside the bundle as base64. Without it esbuild stops with
+ * `No loader is configured for ".step" files`. Loader keys are case-sensitive,
+ * hence the upper-case file.
+ */
+import { describe, it, expect } from "vitest";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { bundleShapeFile } from "./bundle.js";
+
+describe("bundleShapeFile — STEP imports", () => {
+ it("inlines .step and .STP files as bytes", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "siu-serve-step-"));
+ try {
+ const lower = "ISO-10303-21;\nHEADER;\n/* lower */\n";
+ const upper = "ISO-10303-21;\nHEADER;\n/* upper */\n";
+ writeFileSync(join(dir, "input.step"), lower);
+ writeFileSync(join(dir, "OTHER.STP"), upper);
+ const entry = join(dir, "part.shape.ts");
+ writeFileSync(
+ entry,
+ [
+ `import input from "./input.step";`,
+ `import other from "./OTHER.STP";`,
+ `import { importStep } from "shapeitup";`,
+ `export default function main() { return [importStep(input), importStep(other)]; }`,
+ ].join("\n"),
+ );
+
+ const js = await bundleShapeFile(entry);
+ expect(js).toContain("__toBinary(");
+ expect(js).toContain(Buffer.from(lower).toString("base64"));
+ expect(js).toContain(Buffer.from(upper).toString("base64"));
+ // `shapeitup` stays external for the executor to supply.
+ expect(js).toMatch(/from\s*["']shapeitup["']/);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/shared/src/bundle-spec.test.ts b/packages/shared/src/bundle-spec.test.ts
index 7a4b4ec..bc87db3 100644
--- a/packages/shared/src/bundle-spec.test.ts
+++ b/packages/shared/src/bundle-spec.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
-import { buildSyntheticShapeEntry, isOptionalReexportWarning } from "./bundle-spec.js";
+import {
+ buildSyntheticShapeEntry,
+ isOptionalReexportWarning,
+ SHAPE_BUNDLE_LOADERS,
+ shapeBundleOptions,
+} from "./bundle-spec.js";
// esbuild's text for an import the wrapper makes that the user's file doesn't
// satisfy, e.g. `export const sim = __shapeitup_entry__.sim;`.
@@ -21,3 +26,16 @@ describe("isOptionalReexportWarning", () => {
expect(isOptionalReexportWarning(warning("simulate"))).toBe(false);
});
});
+
+describe("SHAPE_BUNDLE_LOADERS", () => {
+ it("loads STEP files as bytes, in both cases esbuild distinguishes", () => {
+ for (const ext of [".step", ".stp", ".STEP", ".STP"]) {
+ expect(SHAPE_BUNDLE_LOADERS[ext as keyof typeof SHAPE_BUNDLE_LOADERS], ext).toBe("binary");
+ }
+ });
+
+ it("is what shapeBundleOptions passes to esbuild", () => {
+ const opts = shapeBundleOptions("/tmp/part.shape.ts", "/tmp", (a, b) => `${a}/${b}`);
+ expect(opts.loader).toEqual(SHAPE_BUNDLE_LOADERS);
+ });
+});
diff --git a/packages/shared/src/bundle-spec.ts b/packages/shared/src/bundle-spec.ts
index 5b13d76..b80430f 100644
--- a/packages/shared/src/bundle-spec.ts
+++ b/packages/shared/src/bundle-spec.ts
@@ -54,6 +54,29 @@ export function isOptionalReexportWarning(text: string): boolean {
return OPTIONAL_REEXPORT_WARNING.test(text);
}
+/**
+ * The per-extension loaders every `.shape.ts` bundler passes to esbuild.
+ *
+ * esbuild dispatches on the FULL extension, so `.shape.ts` needs an explicit
+ * loader; `.shape` covers the form used throughout the skill docs.
+ *
+ * STEP files load as `binary`: `import part from "./input.step"` inlines the
+ * file's bytes as a `Uint8Array`, which the stdlib's synchronous
+ * `importStep(bytes)` turns into a shape. Loader keys are case-sensitive, and
+ * CAD tools write both `part.step` and `PART.STEP`, so both spellings are here.
+ *
+ * The MCP engine and the extension host build their own options rather than
+ * calling `shapeBundleOptions`, so this map is exported for them to share.
+ */
+export const SHAPE_BUNDLE_LOADERS = {
+ ".shape.ts": "ts",
+ ".shape": "ts",
+ ".step": "binary",
+ ".stp": "binary",
+ ".STEP": "binary",
+ ".STP": "binary",
+} as const;
+
/**
* esbuild options every `.shape.ts` bundler must agree on, whatever esbuild
* flavour it runs (native in `@shapeitup/serve`, `esbuild-wasm` in the MCP
@@ -82,9 +105,7 @@ export function shapeBundleOptions(absPath: string, dirname: string, join: (a: s
external: [...BUNDLE_EXTERNALS],
platform: "neutral" as const,
absWorkingDir: dirname,
- // esbuild dispatches on the FULL extension, so `.shape.ts` needs an
- // explicit loader; `.shape` covers the form used throughout the skill docs.
- loader: { ".shape.ts": "ts" as const, ".shape": "ts" as const },
+ loader: { ...SHAPE_BUNDLE_LOADERS },
// Defaults first so existing resolution is unchanged; the `.shape`
// fallbacks let `import { makeBed } from "./needle-bed"` find
// `needle-bed.shape.ts`.
diff --git a/skills/shapeitup/SKILL.md b/skills/shapeitup/SKILL.md
index 2b941f1..7a6c6cc 100644
--- a/skills/shapeitup/SKILL.md
+++ b/skills/shapeitup/SKILL.md
@@ -27,6 +27,7 @@ This skill gives you breadth: what to call, when, how. For depth (full signature
- [Finders](#finders)
- [Memory Management](#memory-management)
- [Multi-File & Assemblies](#multi-file--assemblies)
+- [Editing an existing STEP file](#editing-an-existing-step-file)
- [Export Decision Table](#export-decision-table)
- [Complete Examples](#complete-examples)
@@ -706,6 +707,29 @@ Both args also exist on `verify_shape` (as `acceptedPairs` / `pressFitThreshold`
---
+## Editing an existing STEP file
+
+Import the file like a local module, then turn its bytes into a shape with `importStep` from the stdlib. The result is an ordinary shape: cut, fuse, fillet and export it like anything you built yourself.
+
+```typescript
+import { makeCylinder } from "replicad";
+import { importStep } from "shapeitup";
+import input from "./input.step"; // .step / .stp, any case — bundled as a Uint8Array
+
+export default function main() {
+ const part = importStep(input);
+ return part.cut(makeCylinder(3, 50, [10, 5, -1])); // through-hole at (10, 5)
+}
+```
+
+- `importStep(bytes)` returns a `Solid` for a one-body file and a `Compound` for several. Lengths are in mm whatever unit the file was written in. Only geometry comes across: names and colours in the file are dropped.
+- The path is relative to the `.shape.ts`, like any local import. Saving a new version of the STEP re-renders the script.
+- **Do not use Replicad's `importSTEP(blob)`.** It is async, and `main()` runs synchronously, so an `async main()` or a returned Promise fails with "main() returned a Promise".
+- There is no feature history to edit. Before changing a part, find out where things are: return `importStep(input)` on its own, then use `describe_geometry` / `render_preview`, or `shape.boundingBox` in the script. Select existing faces and edges with [finders](#finders).
+- Write the result with `export_shape({ format: "step" })`.
+
+---
+
## Export Decision Table
`export_shape` signature: `{ format, filePath?, outputPath?, partName?, openIn? }`.