@rulecad/cad 0.7.97 → 0.9.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.
- package/AGENTS.md +26 -10
- package/CHANGELOG.md +442 -2
- package/EXAMPLES.md +48 -42
- package/README.md +226 -73
- package/TUTORIAL.md +2 -2
- package/bin/cad.mjs +2253 -514
- package/lib/animate.mjs +173 -49
- package/lib/assembly.mjs +1854 -437
- package/lib/beams.mjs +256 -52
- package/lib/belts.mjs +66 -15
- package/lib/board-work.mjs +12 -0
- package/lib/bought.mjs +309 -53
- package/lib/buildpage.mjs +179 -29
- package/lib/carried.mjs +201 -0
- package/lib/clone.mjs +194 -42
- package/lib/design.mjs +734 -113
- package/lib/drive.mjs +187 -63
- package/lib/edit.mjs +900 -191
- package/lib/errors.mjs +16 -3
- package/lib/explain.mjs +62 -13
- package/lib/fasten.mjs +2710 -502
- package/lib/fittings.mjs +715 -121
- package/lib/fixings.mjs +21 -9
- package/lib/framebuild.mjs +792 -176
- package/lib/framecheck.mjs +1901 -368
- package/lib/framegen.mjs +100 -22
- package/lib/frameheat.mjs +225 -42
- package/lib/frameprint.mjs +513 -108
- package/lib/frames.mjs +81 -17
- package/lib/framesize.mjs +792 -120
- package/lib/frametip.mjs +235 -0
- package/lib/gait.mjs +135 -23
- package/lib/grip.mjs +62 -13
- package/lib/guides.mjs +1403 -230
- package/lib/host.mjs +149 -18
- package/lib/inplace.mjs +171 -36
- package/lib/jigs.mjs +360 -78
- package/lib/joins.mjs +697 -118
- package/lib/jsonedit.mjs +88 -26
- package/lib/kept.mjs +84 -0
- package/lib/kit.mjs +438 -68
- package/lib/layout.mjs +3 -1
- package/lib/links.mjs +149 -42
- package/lib/list.mjs +326 -64
- package/lib/live-guard.mjs +68 -0
- package/lib/live-shape.mjs +96 -24
- package/lib/live.mjs +189 -59
- package/lib/loads.mjs +579 -130
- package/lib/machine.mjs +372 -74
- package/lib/magnets.mjs +162 -44
- package/lib/measured.mjs +417 -94
- package/lib/mesh.mjs +526 -119
- package/lib/meshcmd.mjs +215 -60
- package/lib/motors.mjs +1022 -212
- package/lib/motorsvg.mjs +114 -32
- package/lib/names.mjs +41 -0
- package/lib/optimise.mjs +979 -283
- package/lib/order.mjs +519 -112
- package/lib/panels.mjs +482 -94
- package/lib/parts.mjs +78 -23
- package/lib/pins.mjs +163 -44
- package/lib/plates.mjs +224 -36
- package/lib/player.mjs +37 -9
- package/lib/power.mjs +64 -13
- package/lib/preview.mjs +83 -16
- package/lib/profilemeasure.mjs +572 -129
- package/lib/rules.mjs +38 -4
- package/lib/sandbox-hooks.mjs +154 -12
- package/lib/sandbox-preload.mjs +2 -2
- package/lib/sandbox-run.mjs +127 -12
- package/lib/sandbox.mjs +632 -35
- package/lib/schema.mjs +43 -11
- package/lib/seats.mjs +227 -49
- package/lib/services.mjs +261 -52
- package/lib/sheet.mjs +851 -178
- package/lib/slotnuts.mjs +213 -34
- package/lib/targets/gist.mjs +4 -1
- package/lib/targets.mjs +42 -6
- package/lib/task.mjs +376 -79
- package/lib/versions.mjs +113 -28
- package/lib/wires.mjs +228 -45
- package/lib/workspace.mjs +216 -17
- package/package.json +19 -19
- package/schemas/assembly.schema.json +2 -2
- package/schemas/object.schema.json +1 -1
- package/schemas/project.schema.json +1 -1
package/lib/sandbox.mjs
CHANGED
|
@@ -9,20 +9,30 @@
|
|
|
9
9
|
// the permission model doesn't cover the network, so a design written to get round them might still reach it, and
|
|
10
10
|
// read the workspace as it does. So: run only designs you trust, as with any code.
|
|
11
11
|
// It gets its values as data and sends back its parts' faces. A workspace that trusts its designs sets
|
|
12
|
-
// "sandbox": false in cad.config.json (or CAD_TRUST=1).
|
|
13
|
-
// with the board engine
|
|
12
|
+
// "sandbox": false in cad.config.json (or CAD_TRUST=1).
|
|
13
|
+
// Board designs (engine pcb) run here too, with the board engine: the sandbox may then also read @rulecad/pcb and what
|
|
14
|
+
// it loads (tscircuit's packages), the design gets v.pcb as it would in the tool's process (v.pcb.mount reads the
|
|
15
|
+
// workspace's thread sets, handed in as data), the runner builds the board's Circuit JSON, and the reply carries it
|
|
16
|
+
// (with the keyboard matrix and a cloned board's source) for the tool to check and make the board's solid and files
|
|
17
|
+
// from. The autorouter's results come back the same way as a lamina's stages, for the tool to keep.
|
|
14
18
|
import fs from 'node:fs';
|
|
15
19
|
import path from 'node:path';
|
|
16
|
-
import { spawn } from 'node:child_process';
|
|
20
|
+
import { spawn, execFile } from 'node:child_process';
|
|
21
|
+
import { constants as bufferConstants } from 'node:buffer';
|
|
17
22
|
import * as nodeModule from 'node:module';
|
|
18
23
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
19
|
-
import { WS, TOOL, config,
|
|
24
|
+
import { WS, TOOL, config, trusted, DESIGN_TIMEOUT, DESIGN_MEMORY, ownFile } from './workspace.mjs';
|
|
20
25
|
import { fromFaces } from './parts.mjs';
|
|
21
26
|
import { located } from './errors.mjs';
|
|
27
|
+
import { STAGES_MOST, ROUTES_MOST } from './kept.mjs';
|
|
22
28
|
|
|
23
29
|
const flag = (() => {
|
|
24
30
|
const f = process.allowedNodeEnvironmentFlags;
|
|
25
|
-
return f.has('--permission')
|
|
31
|
+
return f.has('--permission')
|
|
32
|
+
? '--permission'
|
|
33
|
+
: f.has('--experimental-permission')
|
|
34
|
+
? '--experimental-permission'
|
|
35
|
+
: null;
|
|
26
36
|
})();
|
|
27
37
|
|
|
28
38
|
const inThread = typeof nodeModule.registerHooks === 'function'; // import hooks in this thread; older Node needs a worker for them
|
|
@@ -32,18 +42,128 @@ const inThread = typeof nodeModule.registerHooks === 'function'; // import hooks
|
|
|
32
42
|
export const sandboxed = () => !!flag && process.env.CAD_TRUST !== '1' && !(config.sandbox === false && trusted());
|
|
33
43
|
|
|
34
44
|
// What the sandbox may read: the workspace, and the packages designs and the runner load (wherever npm put them), and
|
|
35
|
-
// what those load in turn (@rulecad/frames sizes a beam's operations through @rulecad/fixings)
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
45
|
+
// what those load in turn (@rulecad/frames sizes a beam's operations through @rulecad/fixings). Node's permission
|
|
46
|
+
// model follows a link inside these folders wherever it leads, so a link in the design's project or rules/ that leads
|
|
47
|
+
// out of the workspace is refused before the sandbox starts (workspace.mjs noLinksOut, from design.mjs).
|
|
48
|
+
function readable({ board = false, extra = [] } = {}) {
|
|
49
|
+
const real = (p) => {
|
|
50
|
+
try {
|
|
51
|
+
return fs.realpathSync(p);
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
40
55
|
};
|
|
41
|
-
const
|
|
56
|
+
const pkgDir = (name, from) => {
|
|
57
|
+
// the package's folder: from its entry up to its package.json (exports may hide that file)
|
|
58
|
+
try {
|
|
59
|
+
let d = path.dirname(nodeModule.createRequire(from).resolve(name));
|
|
60
|
+
while (!fs.existsSync(path.join(d, 'package.json')) && path.dirname(d) !== d) d = path.dirname(d);
|
|
61
|
+
return d;
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const fromWs = path.join(WS, 'package.json'),
|
|
67
|
+
fromTool = path.join(TOOL, 'package.json');
|
|
42
68
|
// Every node_modules above the workspace and the tool (package lookups read their links), and where links lead
|
|
43
|
-
const up = (dir) => {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
69
|
+
const up = (dir) => {
|
|
70
|
+
const out = [];
|
|
71
|
+
for (let d = dir; ; d = path.dirname(d)) {
|
|
72
|
+
out.push(path.join(d, 'node_modules'));
|
|
73
|
+
if (path.dirname(d) === d) return out;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const dirs = [
|
|
77
|
+
WS,
|
|
78
|
+
TOOL,
|
|
79
|
+
...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
|
|
80
|
+
...[
|
|
81
|
+
'@jscad/modeling',
|
|
82
|
+
'@rulecad/shapes',
|
|
83
|
+
'@rulecad/flexures',
|
|
84
|
+
'@rulecad/gears',
|
|
85
|
+
'@rulecad/motors',
|
|
86
|
+
'@rulecad/frames',
|
|
87
|
+
'@rulecad/fixings',
|
|
88
|
+
'@rulecad/rules/x1c.json',
|
|
89
|
+
'@rulecad/fea',
|
|
90
|
+
'@rulecad/variables',
|
|
91
|
+
'manifold-3d',
|
|
92
|
+
].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)]),
|
|
93
|
+
...extra,
|
|
94
|
+
];
|
|
95
|
+
const out = [
|
|
96
|
+
...new Set(
|
|
97
|
+
dirs
|
|
98
|
+
.filter(Boolean)
|
|
99
|
+
.flatMap((d) => [d, real(d)])
|
|
100
|
+
.filter(Boolean),
|
|
101
|
+
),
|
|
102
|
+
];
|
|
103
|
+
// A board's engine loads tscircuit's packages and @rulecad's own (smooth, rules, fixings): what it depends on, and
|
|
104
|
+
// what they do in turn, wherever each really is. Most are in a node_modules listed above; a package linked in from
|
|
105
|
+
// elsewhere (a workspace of packages, as rulecad's own repository is) is added by its real folder.
|
|
106
|
+
if (board) out.push(...(engineDirs ||= engineFolders(out, real, pkgDir, fromTool))); // (found once a run: the packages don't move under it)
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
let engineDirs = null;
|
|
110
|
+
// A package's name as npm allows it: never a path ("/home/me/.ssh/key", "../..") that would lead the walk below anywhere
|
|
111
|
+
const PACKAGE_NAME = /^(@[a-z0-9][\w.~-]*\/)?[a-z0-9][\w.~-]*$/i;
|
|
112
|
+
// The real folders of @rulecad/pcb and every package it loads, but those inside a folder the sandbox already reads.
|
|
113
|
+
// The engine the runner loads is the tool's own (sandbox-run.mjs imports it from here), so the walk starts there, never
|
|
114
|
+
// at a copy in the workspace: a workspace's node_modules is the workspace's to write, and a package.json there naming
|
|
115
|
+
// "dependencies" that lead out of it (a link, a path) would have the sandbox read wherever they lead. Each dependency is
|
|
116
|
+
// a package name, and its folder one whose package.json has that name.
|
|
117
|
+
function engineFolders(out, real, pkgDir, from) {
|
|
118
|
+
const found = [],
|
|
119
|
+
seen = new Set(),
|
|
120
|
+
under = (d) => out.some((o) => d === o || d.startsWith(o + path.sep));
|
|
121
|
+
const named = (d, n) => {
|
|
122
|
+
try {
|
|
123
|
+
return JSON.parse(fs.readFileSync(path.join(d, 'package.json'), 'utf8')).name === n;
|
|
124
|
+
} catch {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
// (the folder found, or the one above it of that name: by its entry, a package's dist/package.json may be found first,
|
|
129
|
+
// but never above the node_modules it is in)
|
|
130
|
+
const own = (d, n) => {
|
|
131
|
+
for (; d && path.basename(d) !== 'node_modules' && path.dirname(d) !== d; d = path.dirname(d))
|
|
132
|
+
if (named(d, n)) return d;
|
|
133
|
+
return null;
|
|
134
|
+
};
|
|
135
|
+
const add = (d, n) => {
|
|
136
|
+
d = d && own(d, n);
|
|
137
|
+
if (!d || seen.has(d)) return;
|
|
138
|
+
seen.add(d);
|
|
139
|
+
if (!under(d)) found.push(d);
|
|
140
|
+
walk(d);
|
|
141
|
+
};
|
|
142
|
+
const find = (n, dir) => {
|
|
143
|
+
// (findPackageJSON where Node has it: exports that hide a package's entry from require don't hide this)
|
|
144
|
+
const at = path.join(dir, 'package.json');
|
|
145
|
+
try {
|
|
146
|
+
if (nodeModule.findPackageJSON) {
|
|
147
|
+
const f = nodeModule.findPackageJSON(n, pathToFileURL(at));
|
|
148
|
+
if (f) return real(path.dirname(f));
|
|
149
|
+
}
|
|
150
|
+
} catch {
|
|
151
|
+
/* by its entry, below */
|
|
152
|
+
}
|
|
153
|
+
return real(pkgDir(n, at) || '');
|
|
154
|
+
};
|
|
155
|
+
function walk(dir) {
|
|
156
|
+
let j;
|
|
157
|
+
try {
|
|
158
|
+
j = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
|
|
159
|
+
} catch {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
for (const n of Object.keys({ ...j.dependencies, ...j.optionalDependencies, ...j.peerDependencies }))
|
|
163
|
+
if (PACKAGE_NAME.test(n)) add(find(n, dir), n);
|
|
164
|
+
}
|
|
165
|
+
add(real(pkgDir('@rulecad/pcb', from) || ''), '@rulecad/pcb');
|
|
166
|
+
return found;
|
|
47
167
|
}
|
|
48
168
|
|
|
49
169
|
// A read the permission model refused, said with what to do. Node names the first path it may not read; when that is
|
|
@@ -51,43 +171,520 @@ function readable() {
|
|
|
51
171
|
// are reached through a node_modules link spelled through it, which the sandbox follows by its real path and may not.
|
|
52
172
|
function refused(e) {
|
|
53
173
|
if (e.code !== 'design.sandbox' || !e.resource) return e.message;
|
|
54
|
-
const res = e.resource,
|
|
174
|
+
const res = e.resource,
|
|
175
|
+
to = (() => {
|
|
176
|
+
try {
|
|
177
|
+
return fs.lstatSync(res).isSymbolicLink() ? fs.realpathSync(res) : null;
|
|
178
|
+
} catch {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
})();
|
|
55
182
|
const trust = 'or trust the workspace ("sandbox": false in cad.config.json, then cad trust)';
|
|
56
183
|
return to
|
|
57
184
|
? `the design's sandbox was refused ${res}, a link to ${to}: something the design loads is reached through it (a node_modules link spelled through ${res}, most likely). Make that link with its real path (ln -s "$(pwd -P)/node_modules"), ${trust}`
|
|
58
185
|
: `the design's sandbox was refused ${res}: a design may read only its workspace and the packages it uses. Keep what it needs inside the workspace, ${trust}`;
|
|
59
186
|
}
|
|
60
187
|
|
|
188
|
+
// The child's reply is untrusted input. The design shares the runner's process, so it can print anything on the
|
|
189
|
+
// stdout the reply is read from, and end the process before the runner prints the real one. So every field is checked
|
|
190
|
+
// before it is used (checkReply), and the only thing written from it is a stage of the cache: under a key of the form
|
|
191
|
+
// the stage cache makes (@rulecad/flexures cache.mjs: `${name}-${sha256 hex}`, a name such as "physics" or "flood
|
|
192
|
+
// probe"), as a file directly in the design's own stages folder (stageFile), which only that design reads: a key is a
|
|
193
|
+
// hash anyone can work out, so a stage handed back under another design's key must never be read by that design. A
|
|
194
|
+
// reply that is not one the runner makes, or that hands back more stages than a build makes (STAGES_MOST), is refused
|
|
195
|
+
// whole, with nothing written.
|
|
196
|
+
|
|
197
|
+
// A cache folder the sandbox reads (the stages, the routes): one of the workspace's only where it really is inside it.
|
|
198
|
+
// A cloned workspace's .cache/ that is a link to a folder elsewhere is not read from (null: every stage a miss), and the
|
|
199
|
+
// runner reads a file of the folder only where it really is in it (sandbox-run.mjs fromFolder).
|
|
200
|
+
const ownFolder = (dir) => {
|
|
201
|
+
try {
|
|
202
|
+
return ownFile(dir);
|
|
203
|
+
} catch (e) {
|
|
204
|
+
if (e.code === 'workspace.outside') return null;
|
|
205
|
+
throw e;
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/** The form of a stage's key, as the stage cache makes it: a stage's name, a dash and the 64 hex digits of a SHA-256. */
|
|
210
|
+
export const STAGE_KEY = /^[a-z][a-z0-9 _-]{0,39}-[0-9a-f]{64}$/;
|
|
211
|
+
|
|
212
|
+
// How many stages one reply may hand back, and how much text in all (kept.mjs, which the runner keeps to): a reply past
|
|
213
|
+
// either is refused whole, since it would fill the disk, or push the design's honest stages out of its folder of the
|
|
214
|
+
// cache. Routes likewise.
|
|
215
|
+
export { STAGES_MOST, ROUTES_MOST };
|
|
216
|
+
// What is wrong with a reply's stages or routes past its cap, or null
|
|
217
|
+
const overCap = (o, most, what) => {
|
|
218
|
+
const all = Object.values(o),
|
|
219
|
+
bytes = all.reduce((n, text) => n + Buffer.byteLength(text, 'utf8'), 0);
|
|
220
|
+
if (all.length > most.count) return `it hands back ${all.length} ${what}, more than the ${most.count} a build makes`;
|
|
221
|
+
if (bytes > most.bytes) return `it hands back ${bytes} bytes of ${what}, more than the ${most.bytes} a build makes`;
|
|
222
|
+
return null;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* The file a stage of the cache is kept in, or null when its key would put it anywhere but directly in `dir`.
|
|
227
|
+
* @param {string} dir the stages folder @param {unknown} key @returns {string | null}
|
|
228
|
+
*/
|
|
229
|
+
export function stageFile(dir, key) {
|
|
230
|
+
if (typeof key !== 'string' || !key) return null;
|
|
231
|
+
const file = path.resolve(dir, `${key}.json`),
|
|
232
|
+
rel = path.relative(path.resolve(dir), file);
|
|
233
|
+
return rel && !path.isAbsolute(rel) && !rel.split(/[\\/]/).includes('..') && path.basename(rel) === rel ? file : null;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const plain = (x) =>
|
|
237
|
+
x !== null && typeof x === 'object' && !Array.isArray(x) && Object.getPrototypeOf(x) === Object.prototype;
|
|
238
|
+
const point = (p) => Array.isArray(p) && p.length === 3 && p.every((n) => typeof n === 'number' && Number.isFinite(n));
|
|
239
|
+
const faceList = (x) => Array.isArray(x) && x.every((f) => Array.isArray(f) && f.every(point));
|
|
240
|
+
const PART = { name: 'string', role: 'string', label: 'string', filament: 'string', mirror: 'boolean' },
|
|
241
|
+
PART_FACES = ['solid', 'polygons', 'triangles'];
|
|
242
|
+
const REPLY = ['parts', 'read', 'mechanism', 'fixings', 'stages', 'board', 'mounted', 'routes'],
|
|
243
|
+
ERROR = { message: 'string', code: 'string', line: 'number', syntax: 'boolean', resource: 'string' };
|
|
244
|
+
const fields = (o, kinds) => Object.entries(o).find(([k, x]) => !(k in kinds) || typeof x !== kinds[k]);
|
|
245
|
+
|
|
246
|
+
/** The form of a route's key, as @rulecad/pcb's route cache makes it: the 64 hex digits of a SHA-256. */
|
|
247
|
+
export const ROUTE_KEY = /^[0-9a-f]{64}$/;
|
|
248
|
+
// A key JSON.parse keeps as a plain field that Object.assign and the like would take as the object's prototype
|
|
249
|
+
const polluting = (x) => {
|
|
250
|
+
for (const stack = [x]; stack.length;) {
|
|
251
|
+
const o = stack.pop();
|
|
252
|
+
if (o === null || typeof o !== 'object') continue;
|
|
253
|
+
if (!Array.isArray(o) && Object.hasOwn(o, '__proto__')) return true;
|
|
254
|
+
for (const v of Array.isArray(o) ? o : Object.values(o)) if (v !== null && typeof v === 'object') stack.push(v);
|
|
255
|
+
}
|
|
256
|
+
return false;
|
|
257
|
+
};
|
|
258
|
+
// A board's reply: its Circuit JSON (a list of elements, each with its type), and the matrix and source the design gave
|
|
259
|
+
function checkBoard(b) {
|
|
260
|
+
if (!plain(b)) return 'its board is not an object';
|
|
261
|
+
const extra = Object.keys(b).find((k) => !['circuit', 'matrix', 'source'].includes(k));
|
|
262
|
+
if (extra) return `its board has a field "${extra}" the runner doesn't send`;
|
|
263
|
+
if (!Array.isArray(b.circuit) || !b.circuit.length || !b.circuit.every((e) => plain(e) && typeof e.type === 'string'))
|
|
264
|
+
return "its board's circuit is not a list of circuit elements";
|
|
265
|
+
if (b.matrix != null && !(plain(b.matrix) || Array.isArray(b.matrix))) return "its board's matrix is not an object";
|
|
266
|
+
if (b.source != null && !plain(b.source)) return "its board's source is not an object";
|
|
267
|
+
if (polluting(b)) return 'its board has a field named __proto__';
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* What is wrong with a reply from the sandbox's runner, in a few words, or null when it is one the runner makes:
|
|
273
|
+
* `{ parts, read, mechanism?, fixings?, stages? }`, a board design's `{ parts: [], read, board: { circuit, matrix?,
|
|
274
|
+
* source? }, mounted?, fixings?, routes? }`, or `{ error }`. Its stages no more than `stagesMost` (STAGES_MOST), its
|
|
275
|
+
* routes no more than ROUTES_MOST.
|
|
276
|
+
* @param {unknown} r the child's stdout, parsed
|
|
277
|
+
* @param {{ count: number, bytes: number }} [stagesMost] @returns {string | null}
|
|
278
|
+
*/
|
|
279
|
+
export function checkReply(r, stagesMost = STAGES_MOST) {
|
|
280
|
+
if (!plain(r)) return 'it is not an object';
|
|
281
|
+
if ('error' in r) {
|
|
282
|
+
if (Object.keys(r).length !== 1 || !plain(r.error)) return 'its error is not one the runner makes';
|
|
283
|
+
const bad = fields(r.error, ERROR);
|
|
284
|
+
return bad
|
|
285
|
+
? `its error's ${bad[0]} is not one the runner makes`
|
|
286
|
+
: typeof r.error.message !== 'string'
|
|
287
|
+
? 'its error has no message'
|
|
288
|
+
: null;
|
|
289
|
+
}
|
|
290
|
+
const extra = Object.keys(r).find((k) => !REPLY.includes(k));
|
|
291
|
+
if (extra) return `it has a field "${extra}" the runner doesn't send`;
|
|
292
|
+
if (!Array.isArray(r.parts)) return 'it has no list of parts';
|
|
293
|
+
for (const p of r.parts) {
|
|
294
|
+
if (!plain(p)) return 'a part is not an object';
|
|
295
|
+
const bad = Object.entries(p).find(
|
|
296
|
+
([k, x]) => !(PART_FACES.includes(k) ? faceList(x) : k in PART && typeof x === PART[k]),
|
|
297
|
+
);
|
|
298
|
+
if (bad) return `a part's ${bad[0]} is not one the runner makes`;
|
|
299
|
+
if (typeof p.name !== 'string' || PART_FACES.some((k) => !(k in p))) return 'a part has no name or no faces';
|
|
300
|
+
}
|
|
301
|
+
if (!Array.isArray(r.read) || !r.read.every((n) => typeof n === 'string'))
|
|
302
|
+
return 'what it read is not a list of names';
|
|
303
|
+
if (r.mechanism != null && !plain(r.mechanism)) return 'its mechanism is not an object';
|
|
304
|
+
if (r.fixings != null && !(Array.isArray(r.fixings) && r.fixings.every(plain)))
|
|
305
|
+
return 'its fixings are not a list of findings';
|
|
306
|
+
if (r.stages != null) {
|
|
307
|
+
if (!plain(r.stages)) return 'its stages are not an object';
|
|
308
|
+
const bad = Object.entries(r.stages).find(([k, text]) => !STAGE_KEY.test(k) || typeof text !== 'string');
|
|
309
|
+
if (bad) return STAGE_KEY.test(bad[0]) ? 'a stage is not text' : "a stage's key is not one the stage cache makes";
|
|
310
|
+
const over = overCap(r.stages, stagesMost, 'slow stages');
|
|
311
|
+
if (over) return over;
|
|
312
|
+
}
|
|
313
|
+
if (r.board != null) {
|
|
314
|
+
const bad = checkBoard(r.board);
|
|
315
|
+
if (bad) return bad;
|
|
316
|
+
if (r.parts.length) return "a board's reply has parts of its own";
|
|
317
|
+
}
|
|
318
|
+
if (r.mounted != null && typeof r.mounted !== 'boolean') return 'its "mounted" is not true or false';
|
|
319
|
+
if (r.routes != null) {
|
|
320
|
+
if (r.board == null) return 'it has routes but no board';
|
|
321
|
+
if (!plain(r.routes)) return 'its routes are not an object';
|
|
322
|
+
const bad = Object.entries(r.routes).find(([k, text]) => !ROUTE_KEY.test(k) || typeof text !== 'string');
|
|
323
|
+
if (bad) return ROUTE_KEY.test(bad[0]) ? 'a route is not text' : "a route's key is not one the route cache makes";
|
|
324
|
+
const over = overCap(r.routes, ROUTES_MOST, 'routes');
|
|
325
|
+
if (over) return over;
|
|
326
|
+
}
|
|
327
|
+
if (r.mechanism != null && polluting(r.mechanism)) return 'its mechanism has a field named __proto__';
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Whether designs can be sandboxed here at all: Node has the permission model. */
|
|
332
|
+
export const canSandbox = () => !!flag;
|
|
333
|
+
|
|
334
|
+
// How long a design may run and how much memory it may use, in the sandbox. A design with an endless loop would
|
|
335
|
+
// otherwise hang every command that builds it, with no word said, and one that fills memory without end would grow
|
|
336
|
+
// until the system stopped it, taking other work with it. Past either limit the design's process is stopped, and the
|
|
337
|
+
// build fails with design.time or design.memory, naming the design. The time limit was set from the kit's slowest
|
|
338
|
+
// example built from nothing: the launcher's in-line action (examples/projects/launcher, its physics and flooded
|
|
339
|
+
// frame) took 2210 s, 1766 s of it working, on an 8 GB laptop shared with other work (November 2026), so an hour
|
|
340
|
+
// leaves room; the memory limit is the most the design's JavaScript may hold, and its process as a whole may hold
|
|
341
|
+
// MEMORY_ROOM more (Node itself, and what lies outside the JavaScript: typed arrays, WebAssembly memory, output not
|
|
342
|
+
// yet sent), watched from here. What the design sends back or prints is kept here only up to a bound, so it can't
|
|
343
|
+
// fill this process instead. A workspace's cad.config.json that raises a limit above the default is used once the
|
|
344
|
+
// workspace is trusted (cad trust), as "sandbox": false is: until then the default holds. A trusted workspace
|
|
345
|
+
// ("sandbox": false) runs its designs in the tool's own process, without either limit.
|
|
346
|
+
export { DESIGN_TIMEOUT, DESIGN_MEMORY };
|
|
347
|
+
/** How much more than the design's memory limit its process as a whole may hold, in megabytes. */
|
|
348
|
+
export const MEMORY_ROOM = 512;
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* The time and memory limits a design runs under in the sandbox: CAD_DESIGN_TIMEOUT (seconds) and CAD_DESIGN_MEMORY
|
|
352
|
+
* (megabytes) if set, else cad.config.json's "designTimeout" and "designMemory", else 3600 s and 4096 MB. A value that
|
|
353
|
+
* is not a number above nothing is refused, with what to write, rather than left to run without a limit. A value in
|
|
354
|
+
* cad.config.json above the default is used only once the workspace is trusted; until then the default is, and held
|
|
355
|
+
* says what the workspace asked for.
|
|
356
|
+
* @param {Record<string, string | undefined>} [env] @param {{ designTimeout?: unknown, designMemory?: unknown }} [cfg]
|
|
357
|
+
* @param {() => boolean} [ok] whether the workspace is trusted for what it asks
|
|
358
|
+
* @returns {{ timeout: number, memory: number, held?: { timeout?: number, memory?: number } }} timeout in seconds, memory in megabytes
|
|
359
|
+
*/
|
|
360
|
+
export function designLimits(env = process.env, cfg = config, ok = () => trusted(cfg)) {
|
|
361
|
+
const held = {};
|
|
362
|
+
const one = (name, key, fallback, unit, least, which) => {
|
|
363
|
+
const fromEnv = env[name] != null && env[name] !== '';
|
|
364
|
+
const raw = fromEnv ? env[name] : cfg[key];
|
|
365
|
+
if (raw == null) return fallback;
|
|
366
|
+
const n = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() ? Number(raw) : NaN;
|
|
367
|
+
if (Number.isFinite(n) && n >= least) {
|
|
368
|
+
if (fromEnv || n <= fallback || ok()) return n;
|
|
369
|
+
held[which] = n; // (a cloned workspace can't take the limits away by itself: cad trust)
|
|
370
|
+
return fallback;
|
|
371
|
+
}
|
|
372
|
+
const where = fromEnv ? name : `"${key}" in cad.config.json`;
|
|
373
|
+
throw Object.assign(
|
|
374
|
+
new Error(
|
|
375
|
+
`${where} is ${JSON.stringify(raw)}: it should be a number of ${unit} (at least ${least}), as ${fallback}, the default`,
|
|
376
|
+
),
|
|
377
|
+
{ code: 'design.limit', ...(fromEnv ? {} : { file: 'cad.config.json', path: key }) },
|
|
378
|
+
);
|
|
379
|
+
};
|
|
380
|
+
const timeout = one('CAD_DESIGN_TIMEOUT', 'designTimeout', DESIGN_TIMEOUT, 'seconds', 0.1, 'timeout'),
|
|
381
|
+
memory = Math.round(one('CAD_DESIGN_MEMORY', 'designMemory', DESIGN_MEMORY, 'megabytes', 16, 'memory'));
|
|
382
|
+
return { timeout, memory, ...(Object.keys(held).length ? { held } : {}) };
|
|
383
|
+
}
|
|
384
|
+
// What a workspace's raised limit, held back until it is trusted, adds to the message of a design stopped at the limit
|
|
385
|
+
const heldBack = (n, unit) =>
|
|
386
|
+
n != null
|
|
387
|
+
? ` (this workspace's cad.config.json asks for ${n} ${unit}: that is used once you trust it, with cad trust)`
|
|
388
|
+
: '';
|
|
389
|
+
|
|
61
390
|
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
* @param {
|
|
65
|
-
* @param {{ salt: string, get: (k: string) => string | undefined, put: (k: string, text: string) => void } | null} [stages] where a lamina's slow stages are kept: the child reads them from the cache (it may read the workspace) and hands back what it made, which is written here
|
|
66
|
-
* @param {{ frames?: object, fixings?: { sets?: object, printer?: object, material?: string | null } | null }} [bound] what the design's helpers are bound to: frames, the workspace's profile sets (lib/frames.mjs framesContext); fixings, what v.fixings is bound to (design.mjs fixingsContext), whose calls come back as fixings
|
|
391
|
+
* The memory a process holds, in bytes (its resident set: what it has in the machine's memory), or null where that
|
|
392
|
+
* can't be told. Read from /proc on Linux, from ps on other Unix systems and from tasklist on Windows.
|
|
393
|
+
* @param {number} pid @returns {Promise<number | null>}
|
|
67
394
|
*/
|
|
68
|
-
export function
|
|
395
|
+
export function processMemory(pid) {
|
|
396
|
+
return new Promise((resolve) => {
|
|
397
|
+
if (process.platform === 'linux') {
|
|
398
|
+
try {
|
|
399
|
+
const m = /VmRSS:\s*(\d+)\s*kB/.exec(fs.readFileSync(`/proc/${pid}/status`, 'utf8'));
|
|
400
|
+
return resolve(m ? Number(m[1]) * 1024 : null);
|
|
401
|
+
} catch {
|
|
402
|
+
return resolve(null);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
const [cmd, args, read] =
|
|
406
|
+
process.platform === 'win32'
|
|
407
|
+
? [
|
|
408
|
+
'tasklist',
|
|
409
|
+
['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'],
|
|
410
|
+
(t) => /"([\d.,\s\u00a0]+)\s*K"\s*$/m.exec(t)?.[1],
|
|
411
|
+
]
|
|
412
|
+
: ['ps', ['-o', 'rss=', '-p', String(pid)], (t) => /^\s*(\d+)\s*$/.exec(t)?.[1]];
|
|
413
|
+
execFile(cmd, args, { windowsHide: true, timeout: 5000 }, (e, text) => {
|
|
414
|
+
const kb = e ? null : read(String(text));
|
|
415
|
+
resolve(kb ? Number(kb.replace(/\D/g, '')) * 1024 : null);
|
|
416
|
+
});
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
// How often the design's process's memory is looked at, in milliseconds
|
|
420
|
+
const WATCH_EVERY = 250;
|
|
421
|
+
// On a Mac, memory the system has squeezed (compressed) or set aside on disk leaves the resident set, so a process can
|
|
422
|
+
// hold far more than ps says once the machine is short of memory: footprint (the Mac's own tool) counts it, once a
|
|
423
|
+
// second as it runs
|
|
424
|
+
const FOOTPRINT = '/usr/bin/footprint';
|
|
425
|
+
/**
|
|
426
|
+
* Look at a process's memory until told to stop, and call over() once it holds more than most bytes.
|
|
427
|
+
* @param {number} pid @param {number} most @param {() => void} over @returns {() => void} stops looking
|
|
428
|
+
*/
|
|
429
|
+
function watchMemory(pid, most, over) {
|
|
430
|
+
let looking = false,
|
|
431
|
+
ended = false;
|
|
432
|
+
const past = (held) => {
|
|
433
|
+
if (!ended && held != null && held > most) {
|
|
434
|
+
ended = true;
|
|
435
|
+
over();
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
const every = setInterval(() => {
|
|
439
|
+
if (looking || ended) return;
|
|
440
|
+
looking = true;
|
|
441
|
+
processMemory(pid).then((held) => {
|
|
442
|
+
looking = false;
|
|
443
|
+
past(held);
|
|
444
|
+
});
|
|
445
|
+
}, WATCH_EVERY);
|
|
446
|
+
every.unref();
|
|
447
|
+
let deep = null;
|
|
448
|
+
if (process.platform === 'darwin' && fs.existsSync(FOOTPRINT)) {
|
|
449
|
+
deep = spawn(FOOTPRINT, ['--sample', '1', '--noCategories', '-f', 'bytes', '-p', String(pid)], {
|
|
450
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
451
|
+
});
|
|
452
|
+
deep.on('error', () => {}); // (without it, ps alone)
|
|
453
|
+
let text = '';
|
|
454
|
+
deep.stdout.on('data', (b) => {
|
|
455
|
+
text += b;
|
|
456
|
+
const lines = text.split('\n');
|
|
457
|
+
text = lines.pop();
|
|
458
|
+
for (const l of lines) past(Number(/^\s*phys_footprint:\s*(\d+)\s*B/.exec(l)?.[1] ?? NaN) || null);
|
|
459
|
+
});
|
|
460
|
+
deep.unref();
|
|
461
|
+
deep.stdout.unref?.();
|
|
462
|
+
}
|
|
463
|
+
return () => {
|
|
464
|
+
ended = true;
|
|
465
|
+
clearInterval(every);
|
|
466
|
+
if (deep && deep.exitCode == null) deep.kill();
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
// The most of what the design prints that is kept, to pass on after it (its last lines: a crash's own words are there)
|
|
470
|
+
const PRINT_KEPT = 1 << 20;
|
|
471
|
+
// What Node prints as it stops a process whose JavaScript ran out of the memory it may hold (V8's own words)
|
|
472
|
+
const HEAP_DEATH = /JavaScript heap out of memory|Reached heap limit|Ineffective mark-compacts near heap limit/;
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Run a design's main(values) in the sandbox: { parts, read, mechanism, fixings } as the build makes them, and for a
|
|
476
|
+
* board design (board set) its { board: { circuit, matrix?, source? }, mounted } too, parts empty: the tool makes the
|
|
477
|
+
* board's solid from its circuit.
|
|
478
|
+
* The design shares the runner's process and can print anything, so every field of the reply is checked as untrusted
|
|
479
|
+
* input (checkReply), and only stage and route files of the caches are written from it.
|
|
480
|
+
* @param {object} request
|
|
481
|
+
* @param {{ js: string }} request.d the design
|
|
482
|
+
* @param {object} request.values @param {object} request.meta the .json's parts
|
|
483
|
+
* @param {'jscad' | 'manifold'} [request.engine] v.ops's booleans
|
|
484
|
+
* @param {string[]} [request.optional] names main may read that aren't among the values (the display's own inputs)
|
|
485
|
+
* @param {{ dir: string, salt: string, get: (k: string) => string | undefined, put: (k: string, text: string) => void } | null} [request.stages] where a lamina's slow stages are kept: the child reads them from this design's own folder of the cache, dir (it may read the workspace), and hands back what it made, which is written there
|
|
486
|
+
* @param {{ frames?: object, fixings?: { sets?: object, printer?: object, material?: string | null } | null }} [request.bound] what the design's helpers are bound to: frames, the workspace's profile sets (lib/frames.mjs framesContext); fixings, what v.fixings is bound to (design.mjs fixingsContext), whose calls come back as fixings. A board's v.pcb.mount reads fixings.sets too
|
|
487
|
+
* @param {{ routes?: { dir: string, shared?: string | null, put: (k: string, text: string) => void } | null } | null} [request.board] set for a board design (engine pcb): routes, where the autorouter's results are kept (the child reads this design's own folder, dir, then the route cache the tool's own process writes, shared; what it routes is handed back and put in dir only)
|
|
488
|
+
* @param {string[]} [request.read] more folders the sandbox may read (a copy of a workspace held in memory)
|
|
489
|
+
* @returns {Promise<{ parts: object[], read: Set<string>, mechanism: object | null, fixings: object[] | null, board?: { circuit: object[], matrix?: object, source?: object }, mounted?: boolean }>}
|
|
490
|
+
*/
|
|
491
|
+
export function runSandboxed({
|
|
492
|
+
d,
|
|
493
|
+
values,
|
|
494
|
+
meta,
|
|
495
|
+
engine = 'jscad',
|
|
496
|
+
optional = [],
|
|
497
|
+
stages = null,
|
|
498
|
+
bound = {},
|
|
499
|
+
board = null,
|
|
500
|
+
read: more = [],
|
|
501
|
+
}) {
|
|
69
502
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
70
|
-
const
|
|
503
|
+
const routes = board?.routes?.shared ? [path.resolve(board.routes.shared)] : []; // (a route cache the user put outside the workspace, RULECAD_ROUTE_CACHE: read there, or every build routes again)
|
|
504
|
+
let limits;
|
|
505
|
+
try {
|
|
506
|
+
limits = designLimits();
|
|
507
|
+
} catch (e) {
|
|
508
|
+
return Promise.reject(located(e, d.js, 'design.limit'));
|
|
509
|
+
}
|
|
510
|
+
const args = [
|
|
511
|
+
flag,
|
|
512
|
+
`--max-old-space-size=${limits.memory}`,
|
|
513
|
+
...readable({ board: !!board, extra: [...more, ...routes] }).map((p) => `--allow-fs-read=${p}`),
|
|
514
|
+
...(inThread ? [] : ['--allow-worker']),
|
|
515
|
+
'--import',
|
|
516
|
+
pathToFileURL(path.join(here, 'sandbox-preload.mjs')).href,
|
|
517
|
+
path.join(here, 'sandbox-run.mjs'),
|
|
518
|
+
];
|
|
71
519
|
// (real paths: Node names an imported file by where it really is, so a workspace reached through a link still matches)
|
|
72
|
-
const js = fs.realpathSync(d.js),
|
|
520
|
+
const js = fs.realpathSync(d.js),
|
|
521
|
+
project = pathToFileURL(path.dirname(path.dirname(js)) + path.sep).href;
|
|
73
522
|
// The child gets none of this process's environment but what Node needs to start: tokens and keys stay out of it
|
|
74
|
-
const env = Object.fromEntries(
|
|
523
|
+
const env = Object.fromEntries(
|
|
524
|
+
['PATH', 'SystemRoot', 'windir', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL', 'PHYS_DEBUG', 'LAMINA_TIMES']
|
|
525
|
+
.filter((k) => process.env[k] != null)
|
|
526
|
+
.map((k) => [k, process.env[k]]),
|
|
527
|
+
);
|
|
75
528
|
return new Promise((resolve, reject) => {
|
|
76
|
-
const child = spawn(process.execPath, args, {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
529
|
+
const child = spawn(process.execPath, args, {
|
|
530
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
531
|
+
env: { ...env, CAD_SANDBOX_PROJECT: project, NODE_NO_WARNINGS: '1' },
|
|
532
|
+
}); // (its stderr is passed on: what the design prints, not Node's notes on its own flags)
|
|
533
|
+
const MB = 1024 * 1024,
|
|
534
|
+
memoryMessage = (what) =>
|
|
535
|
+
`the design ${what}, so it was stopped: it may make shapes or lists without end. If it needs more, raise the limit: "designMemory" (megabytes) in cad.config.json, or CAD_DESIGN_MEMORY${heldBack(limits.held?.memory, 'MB')}`;
|
|
536
|
+
// What it sends back is kept up to what its JavaScript could hold (a reply is made there), and never past the
|
|
537
|
+
// longest text this process can read; what it prints, only its last PRINT_KEPT bytes
|
|
538
|
+
const replyMost = Math.min(limits.memory * MB, bufferConstants.MAX_STRING_LENGTH);
|
|
539
|
+
const out = [],
|
|
540
|
+
err = [];
|
|
541
|
+
let sent = 0,
|
|
542
|
+
kept = 0,
|
|
543
|
+
dropped = 0,
|
|
544
|
+
over = null; // (why the process was stopped: 'time', 'memory', 'reply')
|
|
545
|
+
const stop = (why) => {
|
|
546
|
+
if (over) return;
|
|
547
|
+
over = why;
|
|
548
|
+
child.kill('SIGKILL');
|
|
549
|
+
};
|
|
550
|
+
child.stdout.on('data', (b) => {
|
|
551
|
+
if (over) return;
|
|
552
|
+
sent += b.length;
|
|
553
|
+
if (sent > replyMost) return stop('reply');
|
|
554
|
+
out.push(b);
|
|
555
|
+
});
|
|
556
|
+
child.stderr.on('data', (b) => {
|
|
557
|
+
err.push(b);
|
|
558
|
+
kept += b.length;
|
|
559
|
+
while (kept - err[0].length >= PRINT_KEPT) {
|
|
560
|
+
kept -= err[0].length;
|
|
561
|
+
dropped += err.shift().length;
|
|
562
|
+
}
|
|
563
|
+
});
|
|
564
|
+
// The time limit: past it the process is stopped outright (a design can't catch SIGKILL, nor delay it with a loop)
|
|
565
|
+
// (a timer holds at most about 24 days: a longer limit would fire at once, so it waits that long instead)
|
|
566
|
+
const timer = setTimeout(() => stop('time'), Math.min(limits.timeout * 1000, 2 ** 31 - 1));
|
|
567
|
+
// The memory of the process as a whole, looked at from here (the design can't stop that)
|
|
568
|
+
const unwatch = watchMemory(child.pid, (limits.memory + MEMORY_ROOM) * MB, () => stop('memory'));
|
|
569
|
+
const done = () => {
|
|
570
|
+
clearTimeout(timer);
|
|
571
|
+
unwatch();
|
|
572
|
+
};
|
|
573
|
+
// Why the process was stopped from here, said as an error naming the design and the limit
|
|
574
|
+
const stopped = (why) =>
|
|
575
|
+
why === 'time'
|
|
576
|
+
? located(
|
|
577
|
+
new Error(
|
|
578
|
+
`the design ran for longer than ${limits.timeout} s, so it was stopped: it may loop for ever. If it is only slow, raise the limit: "designTimeout" (seconds) in cad.config.json, or CAD_DESIGN_TIMEOUT${heldBack(limits.held?.timeout, 's')}`,
|
|
579
|
+
),
|
|
580
|
+
d.js,
|
|
581
|
+
'design.time',
|
|
582
|
+
)
|
|
583
|
+
: located(
|
|
584
|
+
new Error(
|
|
585
|
+
memoryMessage(
|
|
586
|
+
why === 'memory'
|
|
587
|
+
? `held more than ${limits.memory + MEMORY_ROOM} MB in all (${limits.memory} MB for its JavaScript, and ${MEMORY_ROOM} MB more for the rest: typed arrays, WebAssembly memory, output)`
|
|
588
|
+
: `sent back more than ${Math.floor(replyMost / MB)} MB, more than a reply it could make`,
|
|
589
|
+
),
|
|
590
|
+
),
|
|
591
|
+
d.js,
|
|
592
|
+
'design.memory',
|
|
593
|
+
);
|
|
594
|
+
child.on('error', (e) => {
|
|
595
|
+
done();
|
|
596
|
+
reject(e);
|
|
597
|
+
});
|
|
81
598
|
child.on('close', () => {
|
|
599
|
+
done();
|
|
600
|
+
if (over) return reject(stopped(over));
|
|
82
601
|
let r;
|
|
83
|
-
try {
|
|
84
|
-
|
|
602
|
+
try {
|
|
603
|
+
r = JSON.parse(Buffer.concat(out).toString('utf8'));
|
|
604
|
+
} catch {
|
|
605
|
+
// No reply: the process stopped before it gave one. Node's own words say whether it ran out of memory
|
|
606
|
+
const said = Buffer.concat(err).toString('utf8');
|
|
607
|
+
if (HEAP_DEATH.test(said))
|
|
608
|
+
return reject(
|
|
609
|
+
located(
|
|
610
|
+
new Error(memoryMessage(`used more than the ${limits.memory} MB of memory it may`)),
|
|
611
|
+
d.js,
|
|
612
|
+
'design.memory',
|
|
613
|
+
),
|
|
614
|
+
);
|
|
615
|
+
return reject(
|
|
616
|
+
located(
|
|
617
|
+
new Error(`the design's sandbox stopped: ${said.trim().split('\n').slice(-3).join(' ') || 'no output'}`),
|
|
618
|
+
d.js,
|
|
619
|
+
'design.sandbox',
|
|
620
|
+
),
|
|
621
|
+
);
|
|
85
622
|
}
|
|
623
|
+
if (dropped) process.stderr.write(`(the design printed ${dropped} bytes more before this, not kept)\n`);
|
|
86
624
|
if (err.length) process.stderr.write(Buffer.concat(err)); // what the design printed
|
|
87
|
-
|
|
625
|
+
const wrong =
|
|
626
|
+
checkReply(r) ||
|
|
627
|
+
(!board && r.board != null
|
|
628
|
+
? 'it has a board, and the design is not one'
|
|
629
|
+
: board && r.board == null && !r.error
|
|
630
|
+
? "a board design's reply has no board"
|
|
631
|
+
: null); // (every field is untrusted: see checkReply)
|
|
632
|
+
if (wrong)
|
|
633
|
+
return reject(
|
|
634
|
+
located(
|
|
635
|
+
new Error(
|
|
636
|
+
`the design's reply was not one rulecad makes (${wrong}), so none of it was used and nothing it sent was written. A design gives back its shapes from main(v); one that writes to the process's output itself or ends the process is refused`,
|
|
637
|
+
),
|
|
638
|
+
d.js,
|
|
639
|
+
'design.sandbox',
|
|
640
|
+
),
|
|
641
|
+
);
|
|
642
|
+
if (r.error)
|
|
643
|
+
return reject(
|
|
644
|
+
located(
|
|
645
|
+
Object.assign(new Error(refused(r.error)), {
|
|
646
|
+
code: r.error.code,
|
|
647
|
+
...(r.error.line ? { line: r.error.line } : {}),
|
|
648
|
+
...(r.error.syntax ? { name: 'SyntaxError' } : {}),
|
|
649
|
+
}),
|
|
650
|
+
d.js,
|
|
651
|
+
r.error.code || 'design.run',
|
|
652
|
+
),
|
|
653
|
+
);
|
|
88
654
|
if (stages) for (const [k, text] of Object.entries(r.stages || {})) stages.put(k, text);
|
|
89
|
-
|
|
655
|
+
if (board?.routes) for (const [k, text] of Object.entries(r.routes || {})) board.routes.put(k, text);
|
|
656
|
+
resolve({
|
|
657
|
+
parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })),
|
|
658
|
+
read: new Set(r.read),
|
|
659
|
+
mechanism: r.mechanism || null,
|
|
660
|
+
fixings: r.fixings || null,
|
|
661
|
+
...(board ? { board: r.board, mounted: r.mounted === true } : {}),
|
|
662
|
+
});
|
|
90
663
|
});
|
|
91
|
-
child.stdin.end(
|
|
664
|
+
child.stdin.end(
|
|
665
|
+
JSON.stringify({
|
|
666
|
+
js: `${pathToFileURL(js).href}?t=${fs.statSync(js).mtimeMs}`,
|
|
667
|
+
values,
|
|
668
|
+
meta,
|
|
669
|
+
engine,
|
|
670
|
+
optional,
|
|
671
|
+
...(stages ? { stages: { dir: ownFolder(path.resolve(stages.dir)), salt: stages.salt } } : {}),
|
|
672
|
+
bound,
|
|
673
|
+
...(board
|
|
674
|
+
? {
|
|
675
|
+
board: {
|
|
676
|
+
...(board.routes
|
|
677
|
+
? {
|
|
678
|
+
routes: [board.routes.dir, board.routes.shared]
|
|
679
|
+
.filter(Boolean)
|
|
680
|
+
.map((dir) => ownFolder(path.resolve(dir)))
|
|
681
|
+
.filter(Boolean),
|
|
682
|
+
}
|
|
683
|
+
: {}),
|
|
684
|
+
},
|
|
685
|
+
}
|
|
686
|
+
: {}),
|
|
687
|
+
}),
|
|
688
|
+
);
|
|
92
689
|
});
|
|
93
690
|
}
|