scadify 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,252 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, readFileSync, rmSync, existsSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join, dirname } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { spawnSync } from 'node:child_process';
8
+ import { Store } from '../src/store.js';
9
+ import { normalize, RecipeError } from '../src/recipe.js';
10
+ import { compile, measure } from '../src/engine.js';
11
+ import { makeHandlers, serve } from '../src/mcp.js';
12
+ import { unzip } from '../src/emitters/zip.js';
13
+ import { uniqueNames } from '../src/emitters/common.js';
14
+ import { decodePNGHeader } from '../src/raster.js';
15
+ import { PassThrough } from 'node:stream';
16
+ import { inflateSync } from 'node:zlib';
17
+
18
+ // decode a PNG written by src/raster.js (8-bit RGBA, filter 0) -> { w, h, px: Buffer }
19
+ function decodeRGBA(buf) {
20
+ const w = buf.readUInt32BE(16), h = buf.readUInt32BE(20); let p = 8; const idat = [];
21
+ while (p < buf.length) { const n = buf.readUInt32BE(p); if (buf.toString('latin1', p + 4, p + 8) === 'IDAT') idat.push(buf.subarray(p + 8, p + 8 + n)); p += 12 + n; }
22
+ const raw = inflateSync(Buffer.concat(idat)); const px = Buffer.alloc(w * h * 4);
23
+ for (let y = 0; y < h; y++) raw.copy(px, y * w * 4, y * (w * 4 + 1) + 1, (y + 1) * (w * 4 + 1));
24
+ return { w, h, px };
25
+ }
26
+
27
+ const here = dirname(fileURLToPath(import.meta.url));
28
+ // Inline fixture: a 40x30x12 open tray (blue shell) with four standoffs (gold). Fully deterministic, no randomness.
29
+ const example = {
30
+ kind: 'scad', title: 'demo-tray', seed: 7, // units omitted -> default 'dm'
31
+ program: 'wall_h = 12;\nmodule tray() { difference() { cube([40, 30, wall_h]); translate([2, 2, 2]) cube([36, 26, wall_h]); } }\nmodule standoffs() { for (x = [5, 33], y = [6, 20]) translate([x, y, 1.99]) cylinder(d = 5, h = 4, $fn = 24); }',
32
+ parts: { tray: 'tray();', standoffs: 'standoffs();' },
33
+ params: { wall_h: 12 },
34
+ tints: { tray: '#3f6fb0', standoffs: '#c9a227' },
35
+ };
36
+ const tmp = mkdtempSync(join(tmpdir(), 'scadify-'));
37
+ const store = new Store(join(tmp, 'store'));
38
+ const h = makeHandlers({ store, outDir: join(tmp, 'out') });
39
+ process.on('exit', () => rmSync(tmp, { recursive: true, force: true }));
40
+ const near = (a, b, e = 1e-3) => assert.ok(Math.abs(a - b) <= e, `${a} !~ ${b}`);
41
+
42
+ test('recipe validation', () => {
43
+ assert.throws(() => normalize({ kind: 'nope' }), RecipeError);
44
+ assert.throws(() => normalize({ kind: 'scad' }), /program/);
45
+ assert.throws(() => normalize({ kind: 'scad', program: '', parts: { 'bad name': 'x' } }), /part name/);
46
+ assert.throws(() => normalize({ kind: 'csg', tree: { op: 'bogus' } }), /unknown csg op/);
47
+ assert.throws(() => normalize({ kind: 'scad', program: '', params: { 'x;y': 1 } }), /param name/);
48
+ const base = { kind: 'scad', program: '', parts: { a: 'cube(1);' } };
49
+ assert.equal(normalize(base).units, 'dm', 'default unit is architectural');
50
+ for (const u of ['mm', 'cm', 'dm', 'm']) assert.equal(normalize({ ...base, units: u }).units, u);
51
+ for (const u of ['km', 'ft', '', 5]) assert.throws(() => normalize({ ...base, units: u }), /units must be one of/);
52
+ });
53
+
54
+ test('part call without a trailing ";" is terminated (OpenSCAD EOF parse guard)', () => {
55
+ const base = { kind: 'scad', program: 'module b() { cube([1,1,1]); }' };
56
+ const r = normalize({ ...base, parts: { b: 'b()' } });
57
+ assert.equal(r.parts.b, 'b();'); // bare call gets the semicolon
58
+ assert.equal(normalize({ ...base, parts: { b: 'b();' } }).parts.b, 'b();'); // already-terminated unchanged
59
+ assert.equal(normalize({ ...base, parts: { b: '' } }).parts.b, ';'); // empty -> statement terminator
60
+ });
61
+
62
+ test('store: mint is idempotent, update keeps ref, bad refs rejected', async () => {
63
+ const a = await h.mint_solid({ recipe: example });
64
+ const b = await h.mint_solid({ recipe: example });
65
+ assert.equal(a.ref, b.ref);
66
+ assert.equal((await h.list_solids()).solids.length, 1);
67
+ await assert.rejects(h.get_solid({ ref: '../etc/passwd' }), /invalid ref/);
68
+ const u = await h.update_solid({ ref: a.ref, params: { wall_h: 20 } });
69
+ assert.equal(u.recipe.params.wall_h, 20);
70
+ assert.equal(u.ref, a.ref);
71
+ await h.update_solid({ ref: a.ref, params: { wall_h: 12 } });
72
+ });
73
+
74
+ test('determinism: two compiles give the same checksum; params change geometry', async () => {
75
+ const r = normalize(example);
76
+ const m1 = await compile(r);
77
+ const m2 = await compile({ ...r, title: 'again' }); // different hash -> uncached recompile
78
+ assert.equal(m1.checksum, m2.checksum);
79
+ const tall = await compile(normalize({ ...example, params: { wall_h: 20 } }));
80
+ assert.notEqual(tall.checksum, m1.checksum);
81
+ const s = measure(m1);
82
+ near(s.size[0], 40); near(s.size[1], 30); near(s.size[2], 12);
83
+ near(s.parts.find((p) => p.name === 'tray').volume_mm3, 5040, 0.01); // 40*30*12 - 36*26*10
84
+ assert.equal(s.parts.length, 2);
85
+ assert.ok(s.volume_mm3 > 0);
86
+ });
87
+
88
+ test('seed reaches a program that never declares it (rands(..., seed))', async () => {
89
+ const mk = (seed) => normalize({ kind: 'scad', title: 'seeded', seed, program: 'R = rands(0, 1, 4, seed);', parts: { a: 'cube([5, 5, 2 + 10 * R[0]]);' } });
90
+ const a = measure(await compile(mk(1))), b = measure(await compile(mk(2)));
91
+ assert.ok(a.size[2] < 12 && b.size[2] < 12, 'undef seed would extrude to the 100 mm default');
92
+ assert.notEqual(a.checksum, b.checksum);
93
+ });
94
+
95
+ test('units: glb/usd are written in metres (metersPerUnit 1); stl/3mf in millimetres; raw mesh coords stay in recipe units', async () => {
96
+ const cube = (units) => ({ kind: 'csg', title: `cube-${units}`, units, tree: { op: 'cube', size: [10, 20, 30] } });
97
+ const want = { mm: [0.001, 1], cm: [0.01, 10], dm: [0.1, 100], m: [1, 1000] }; // [metersPerUnit, mm per unit]
98
+ for (const [units, [mpu, toMm]] of Object.entries(want)) {
99
+ const { ref } = await h.mint_solid({ recipe: cube(units) });
100
+ assert.equal((await h.measure_solid({ ref })).size[2], 30, 'mesh coords are in recipe units');
101
+ const glb = readFileSync((await h.export_solid({ ref, format: 'glb' })).path);
102
+ const g = JSON.parse(glb.toString('utf8', 20, 20 + glb.readUInt32LE(12)));
103
+ assert.equal(g.asset.extras.units, 'm'); assert.equal(g.asset.extras.metersPerUnit, 1); assert.equal(g.asset.extras.sourceUnits, units);
104
+ near(g.accessors[0].max[2], 30 * mpu, 1e-5); near(g.accessors[0].max[0] - g.accessors[0].min[0], 10 * mpu, 1e-5); // metres
105
+ const usda = readFileSync((await h.export_solid({ ref, format: 'usda' })).path, 'utf8');
106
+ assert.match(usda, /metersPerUnit = 1\n/);
107
+ const ext = usda.match(/float3\[\] extent = \[\([^)]*\), \(([^)]*)\)\]/)[1].split(',').map(Number); near(ext[2], 30 * mpu, 1e-5);
108
+ const stl = readFileSync((await h.export_solid({ ref, format: 'stl' })).path); let zmax = -Infinity;
109
+ for (let t = 0; t < stl.readUInt32LE(80); t++) for (let v = 0; v < 3; v++) zmax = Math.max(zmax, stl.readFloatLE(84 + t * 50 + 12 + v * 12 + 8));
110
+ near(zmax, 30 * toMm, 1e-2);
111
+ const m3 = unzip(readFileSync((await h.export_solid({ ref, format: '3mf' })).path))['3D/3dmodel.model'].data.toString();
112
+ assert.match(m3, /unit="millimeter"/); near(Math.max(...[...m3.matchAll(/ z="([-\d.]+)"/g)].map((m) => +m[1])), 30 * toMm, 1e-2);
113
+ assert.match(readFileSync((await h.export_solid({ ref, format: 'scad' })).path, 'utf8'), new RegExp(`units: ${units}\\)`));
114
+ }
115
+ });
116
+
117
+ test('part naming: names are the part names; a numeric suffix only on collision', () => {
118
+ assert.deepEqual(uniqueNames(['shell', 'dome', 'dome_coral']), ['shell', 'dome', 'dome_coral']);
119
+ assert.deepEqual(uniqueNames(['a', 'a', 'a', 'b']), ['a', 'a_2', 'a_3', 'b']);
120
+ assert.deepEqual(uniqueNames(['Materials', 'x'], ['Materials']), ['Materials_2', 'x']);
121
+ });
122
+
123
+ test('csg compiles via manifold and transpiles to scad; param refs work', async () => {
124
+ const recipe = { kind: 'csg', title: 'block', params: { w: 30 }, tree: { op: 'difference', children: [
125
+ { op: 'cube', size: [{ param: 'w' }, 20, 10] }, { op: 'translate', v: [15, 10, -1], children: [{ op: 'cylinder', h: 12, r: 4, fn: 32 }] }] } };
126
+ const { ref } = await h.mint_solid({ recipe });
127
+ const s = await h.measure_solid({ ref });
128
+ near(s.size[0], 30); near(s.size[2], 10);
129
+ const full = 30 * 20 * 10; assert.ok(s.volume_mm3 < full && s.volume_mm3 > full - 12 * Math.PI * 16 - 5);
130
+ const scad = readFileSync((await h.export_solid({ ref, format: 'scad' })).path, 'utf8');
131
+ assert.match(scad, /difference\(\)/); assert.match(scad, /w = 30;/);
132
+ });
133
+
134
+ let ref;
135
+ test('every format: export, re-read, assert structure', async () => {
136
+ ({ ref } = await h.mint_solid({ recipe: example }));
137
+ const out = {};
138
+ for (const format of ['glb', 'gltf', 'stl', '3mf', 'usdz', 'usda', 'scad', 'json']) {
139
+ out[format] = await h.export_solid({ ref, format });
140
+ assert.ok(existsSync(out[format].path)); assert.ok(out[format].sizeBytes > 0); assert.equal(out[format].sha256.length, 64);
141
+ }
142
+ // GLB: 2 parts, bbox, flat tree, no cameras/lights/ground/skins/animations
143
+ const glb = readFileSync(out.glb.path);
144
+ assert.equal(glb.readUInt32LE(0), 0x46546c67); assert.equal(glb.readUInt32LE(8), glb.length);
145
+ const jl = glb.readUInt32LE(12); const g = JSON.parse(glb.toString('utf8', 20, 20 + jl));
146
+ assert.equal(g.nodes.length, 2); assert.equal(g.meshes.length, 2); assert.deepEqual(g.nodes.map((n) => n.name).sort(), ['standoffs', 'tray']);
147
+ for (const n of g.nodes) { assert.ok(!n.children && !n.camera && !n.matrix && !n.translation && !n.skin); }
148
+ for (const k of ['cameras', 'skins', 'animations', 'extensions', 'extensionsUsed']) assert.equal(g[k], undefined, k);
149
+ assert.equal(g.asset.extras.units, 'm'); assert.equal(g.asset.extras.metersPerUnit, 1); assert.equal(g.asset.extras.sourceUnits, 'dm'); assert.equal(g.asset.extras.upAxis, 'Z');
150
+ const ti = g.nodes.findIndex((n) => n.name === 'tray'); const tray = g.accessors[g.meshes[g.nodes[ti].mesh].primitives[0].attributes.POSITION]; near(tray.max[0] - tray.min[0], 4); near(tray.max[2] - tray.min[2], 1.2); // 40 x 12 dm in metres
151
+ assert.deepEqual(g.materials[g.meshes[g.nodes[ti].mesh].primitives[0].material].pbrMetallicRoughness.baseColorFactor.slice(0, 3).map((x) => +x.toFixed(2)), [0.25, 0.44, 0.69]);
152
+ const gltf = JSON.parse(readFileSync(out.gltf.path, 'utf8')); assert.equal(gltf.nodes.length, 2);
153
+ // STL: binary, count matches, bbox
154
+ const stl = readFileSync(out.stl.path); const n = stl.readUInt32LE(80); assert.equal(stl.length, 84 + n * 50);
155
+ let max = -Infinity; for (let t = 0; t < n; t++) for (let v = 0; v < 3; v++) max = Math.max(max, stl.readFloatLE(84 + t * 50 + 12 + v * 12 + 8));
156
+ near(max, 1200); // 12 dm written in millimetres
157
+ // 3MF
158
+ const z = unzip(readFileSync(out['3mf'].path)); const model = z['3D/3dmodel.model'].data.toString();
159
+ assert.match(model, /unit="millimeter"/); near(Math.max(...[...model.matchAll(/ x="([-\d.]+)"/g)].map((m) => +m[1])), 4000); // 40 dm -> 4000 mm
160
+ assert.equal((model.match(/<object /g) || []).length, 2); assert.ok(z['[Content_Types].xml'] && z['_rels/.rels']);
161
+ // USDZ: one aligned usda, z-up, metres; USDA same text
162
+ const uz = unzip(readFileSync(out.usdz.path)); const names = Object.keys(uz); assert.equal(names.length, 1);
163
+ assert.equal(uz[names[0]].offset % 64, 0);
164
+ const usda = uz[names[0]].data.toString(); assert.equal(usda, readFileSync(out.usda.path, 'utf8'));
165
+ assert.match(usda, /upAxis = "Z"/); assert.match(usda, /metersPerUnit = 1\n/); assert.equal((usda.match(/def Mesh /g) || []).length, 2);
166
+ // prims are named after the parts, never generic
167
+ assert.match(usda, /def Xform "tray"\n\s*\{\n\s*def Mesh "tray"/); assert.match(usda, /def Xform "standoffs"\n\s*\{\n\s*def Mesh "standoffs"/);
168
+ assert.ok(!/def Mesh "mesh"/i.test(usda));
169
+ for (const k of ['nodes', 'meshes', 'materials']) assert.deepEqual(g[k].map((x) => x.name).sort(), ['standoffs', 'tray'], `glb ${k} named after parts`);
170
+ assert.ok(!/Camera|Light/.test(usda));
171
+ assert.match(readFileSync(out.scad.path, 'utf8'), /module tray/);
172
+ assert.equal(JSON.parse(readFileSync(out.json.path, 'utf8')).title, 'demo-tray');
173
+ });
174
+
175
+ test('export is byte-for-byte deterministic (second export, fresh handlers)', async () => {
176
+ const h2 = makeHandlers({ store, outDir: join(tmp, 'out2') });
177
+ for (const format of ['glb', 'stl', '3mf', 'usdz']) {
178
+ const a = await h.export_solid({ ref, format }); const b = await h2.export_solid({ ref, format });
179
+ assert.equal(a.sha256, b.sha256, format);
180
+ }
181
+ });
182
+
183
+ test('turntable: N valid PNG frames that differ per angle', async () => {
184
+ const r = await h.render_turntable({ ref, frames: 4, size: 96 });
185
+ assert.equal(r.paths.length, 4);
186
+ const sums = new Set();
187
+ for (const p of r.paths) {
188
+ const b = readFileSync(p); const d = decodePNGHeader(b);
189
+ assert.equal(d.sig, '89504e470d0a1a0a'); assert.equal(d.w, 96); assert.equal(d.h, 96); sums.add(b.toString('base64'));
190
+ }
191
+ assert.equal(sums.size, 4, 'frames differ per angle');
192
+ assert.equal(decodeRGBA(readFileSync(r.paths[0])).px[3], 0, 'turntable corner stays transparent');
193
+ await assert.rejects(h.render_turntable({ ref, frames: 2 }), /3\.\.36/);
194
+ });
195
+
196
+ test('render_shot: exactly one valid PNG at a chosen angle, differing by angle', async () => {
197
+ const a = await h.render_shot({ ref, angle_deg: 30, elevation_deg: 30, size: 96 });
198
+ assert.equal(a.size, 96); assert.match(a.path, /\.png$/);
199
+ const b = readFileSync(a.path); const d = decodePNGHeader(b);
200
+ assert.equal(d.sig, '89504e470d0a1a0a'); assert.equal(d.w, 96); assert.equal(d.h, 96);
201
+ const c = await h.render_shot({ ref, angle_deg: 120, elevation_deg: 30, size: 96 });
202
+ assert.notEqual(readFileSync(c.path).toString('base64'), b.toString('base64'));
203
+ await assert.rejects(h.render_shot({ ref, elevation_deg: 95 }), /elevation/);
204
+ });
205
+
206
+ test('background: shots are opaque studio #0C1019 by default; transparent on request; render_standard is opaque with two distinct halves', async () => {
207
+ const bgAt = (img, x, y) => [...img.px.subarray((y * img.w + x) * 4, (y * img.w + x) * 4 + 4)];
208
+ const shot = decodeRGBA(readFileSync((await h.render_shot({ ref, angle_deg: 30, elevation_deg: 30, size: 96, background: '#0C1019' })).path));
209
+ for (let i = 3; i < shot.px.length; i += 4) assert.equal(shot.px[i], 255, 'every pixel opaque');
210
+ assert.deepEqual(bgAt(shot, 0, 0), [12, 16, 25, 255]);
211
+ const dflt = decodeRGBA(readFileSync((await h.render_shot({ ref, angle_deg: 30, elevation_deg: 30, size: 96 })).path));
212
+ assert.deepEqual(dflt.px, shot.px, 'default background is #0C1019');
213
+ const clear = decodeRGBA(readFileSync((await h.render_shot({ ref, angle_deg: 30, elevation_deg: 30, size: 96, background: 'transparent' })).path));
214
+ assert.equal(clear.px[3], 0, 'transparent corner');
215
+ await assert.rejects(h.render_shot({ ref, background: 'red' }), /background/);
216
+
217
+ const r = await h.render_standard({ ref, size: 256 });
218
+ assert.equal(r.size, 256); assert.ok(r.panels.front.includes('angle_deg=0') && r.panels.high.includes('angle_deg=30'));
219
+ const img = decodeRGBA(readFileSync(r.path)); assert.equal(img.w, 256); assert.equal(img.h, 256);
220
+ for (let i = 3; i < img.px.length; i += 4) assert.equal(img.px[i], 255, 'composite opaque');
221
+ assert.deepEqual(bgAt(img, 0, 0), [12, 16, 25, 255]);
222
+ const half = 128; const left = Buffer.alloc(half * 256 * 4), right = Buffer.alloc(half * 256 * 4);
223
+ for (let y = 0; y < 256; y++) { img.px.copy(left, y * half * 4, y * 256 * 4, (y * 256 + half) * 4); img.px.copy(right, y * half * 4, (y * 256 + half) * 4, (y * 256 + 256) * 4); }
224
+ assert.ok(!left.equals(right), 'halves differ');
225
+ const nonBg = (b) => { let n = 0; for (let i = 0; i < b.length; i += 4) if (b[i] !== 12 || b[i + 1] !== 16 || b[i + 2] !== 25) n++; return n; };
226
+ assert.ok(nonBg(left) > 200 && nonBg(right) > 200, 'both halves contain the model');
227
+ });
228
+
229
+ test('mcp stdio: initialize, tools/list, tools/call, errors', async () => {
230
+ const input = new PassThrough(); const output = new PassThrough(); const lines = [];
231
+ output.on('data', (d) => lines.push(...d.toString().split('\n').filter(Boolean).map((l) => JSON.parse(l))));
232
+ const done = serve({ input, output, handlers: h });
233
+ const send = (m) => input.write(JSON.stringify(m) + '\n');
234
+ send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05' } });
235
+ send({ jsonrpc: '2.0', method: 'notifications/initialized' });
236
+ send({ jsonrpc: '2.0', id: 2, method: 'tools/list' });
237
+ send({ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'measure_solid', arguments: { ref } } });
238
+ send({ jsonrpc: '2.0', id: 4, method: 'tools/call', params: { name: 'nope', arguments: {} } });
239
+ send({ jsonrpc: '2.0', id: 5, method: 'bogus' });
240
+ input.end(); await done;
241
+ const by = Object.fromEntries(lines.map((l) => [l.id, l]));
242
+ assert.equal(lines.length, 5); // the notification gets no reply
243
+ assert.equal(by[1].result.serverInfo.name, 'scadify');
244
+ assert.deepEqual(by[2].result.tools.map((t) => t.name), ['mint_solid', 'list_solids', 'get_solid', 'update_solid', 'export_solid', 'render_turntable', 'render_shot', 'render_standard', 'measure_solid']);
245
+ near(by[3].result.structuredContent.size[2], 12);
246
+ assert.equal(by[4].result.isError, true); assert.equal(by[5].error.code, -32601);
247
+ });
248
+
249
+ test('bin starts and answers initialize', () => {
250
+ const r = spawnSync('node', [join(here, '../src/scadify-cli.mjs')], { input: '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}\n', encoding: 'utf8', timeout: 20000 });
251
+ assert.equal(JSON.parse(r.stdout.split('\n')[0]).result.serverInfo.name, 'scadify');
252
+ });