mcp-3d-printer-server 1.2.9 → 1.2.12

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.
Files changed (86) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/CONTRIBUTORS.md +56 -0
  3. package/README.md +528 -811
  4. package/dist/3mf_parser.js +8 -8
  5. package/dist/blender-mcp-bridge.d.ts +1 -0
  6. package/dist/blender-mcp-bridge.js +209 -21
  7. package/dist/fulu-orca.js +29 -5
  8. package/dist/index.js +614 -110
  9. package/dist/printers/bambu-node-guard.d.ts +2 -0
  10. package/dist/printers/bambu-node-guard.js +38 -0
  11. package/dist/printers/bambu.d.ts +53 -7
  12. package/dist/printers/bambu.js +420 -126
  13. package/dist/printers/creality.d.ts +15 -6
  14. package/dist/printers/creality.js +42 -9
  15. package/dist/printers/duet.d.ts +11 -6
  16. package/dist/printers/duet.js +57 -34
  17. package/dist/printers/generic-base.d.ts +69 -0
  18. package/dist/printers/generic-base.js +209 -0
  19. package/dist/printers/klipper.d.ts +17 -6
  20. package/dist/printers/klipper.js +63 -16
  21. package/dist/printers/octoprint.d.ts +18 -6
  22. package/dist/printers/octoprint.js +64 -9
  23. package/dist/printers/printer-factory.d.ts +11 -2
  24. package/dist/printers/printer-factory.js +9 -8
  25. package/dist/printers/prusa.d.ts +14 -6
  26. package/dist/printers/prusa.js +56 -9
  27. package/dist/printers/repetier.d.ts +18 -6
  28. package/dist/printers/repetier.js +48 -6
  29. package/dist/safety/archive.d.ts +11 -0
  30. package/dist/safety/archive.js +214 -0
  31. package/dist/safety/artifact.d.ts +6 -0
  32. package/dist/safety/artifact.js +66 -0
  33. package/dist/safety/confirmation.d.ts +22 -0
  34. package/dist/safety/confirmation.js +43 -0
  35. package/dist/safety/expected-peaks.d.ts +24 -0
  36. package/dist/safety/expected-peaks.js +24 -0
  37. package/dist/safety/gcode-thermal.d.ts +64 -0
  38. package/dist/safety/gcode-thermal.js +382 -0
  39. package/dist/safety/limits.d.ts +31 -0
  40. package/dist/safety/limits.js +105 -0
  41. package/dist/safety/print-file.d.ts +25 -0
  42. package/dist/safety/print-file.js +610 -0
  43. package/dist/safety/printer-state.d.ts +51 -0
  44. package/dist/safety/printer-state.js +371 -0
  45. package/dist/slicer/bambu-cli.d.ts +110 -0
  46. package/dist/slicer/bambu-cli.js +547 -0
  47. package/dist/slicer/profile-flatten.d.ts +104 -0
  48. package/dist/slicer/profile-flatten.js +676 -0
  49. package/dist/slicer/run-slicer.d.ts +18 -0
  50. package/dist/slicer/run-slicer.js +102 -0
  51. package/dist/slicer/slicer-error.d.ts +27 -0
  52. package/dist/slicer/slicer-error.js +53 -0
  53. package/dist/slicer/templates.d.ts +126 -0
  54. package/dist/slicer/templates.js +255 -0
  55. package/dist/stl/stl-manipulator.d.ts +25 -3
  56. package/dist/stl/stl-manipulator.js +214 -232
  57. package/package.json +16 -9
  58. package/server.json +56 -0
  59. package/src/3mf_parser.ts +8 -8
  60. package/src/blender-mcp-bridge.ts +200 -19
  61. package/src/fulu-orca.ts +36 -6
  62. package/src/index.ts +686 -137
  63. package/src/printers/bambu-node-guard.ts +44 -0
  64. package/src/printers/bambu.ts +458 -164
  65. package/src/printers/creality.ts +40 -9
  66. package/src/printers/duet.ts +64 -53
  67. package/src/printers/generic-base.ts +286 -0
  68. package/src/printers/klipper.ts +83 -28
  69. package/src/printers/octoprint.ts +74 -21
  70. package/src/printers/printer-factory.ts +21 -11
  71. package/src/printers/prusa.ts +53 -10
  72. package/src/printers/repetier.ts +55 -17
  73. package/src/safety/archive.ts +181 -0
  74. package/src/safety/artifact.ts +58 -0
  75. package/src/safety/confirmation.ts +56 -0
  76. package/src/safety/expected-peaks.ts +47 -0
  77. package/src/safety/gcode-thermal.ts +404 -0
  78. package/src/safety/limits.ts +98 -0
  79. package/src/safety/print-file.ts +429 -0
  80. package/src/safety/printer-state.ts +344 -0
  81. package/src/slicer/bambu-cli.ts +633 -0
  82. package/src/slicer/profile-flatten.ts +830 -0
  83. package/src/slicer/run-slicer.ts +126 -0
  84. package/src/slicer/slicer-error.ts +72 -0
  85. package/src/slicer/templates.ts +288 -0
  86. package/src/stl/stl-manipulator.ts +247 -275
@@ -0,0 +1,830 @@
1
+ /**
2
+ * BambuStudio CLI profile flattener.
3
+ *
4
+ * Background: BambuStudio's bundled profile JSONs (Resources/profiles/BBL/...)
5
+ * use an `inherits` chain that the GUI resolves at runtime but the CLI does
6
+ * not. Passing a leaf profile straight to `--load-settings` / `--load-filaments`
7
+ * yields a partial config and the slicer asserts (e.g. `nozzle_volume_type
8
+ * not found` -> SIGSEGV / assertion in MutablePolygon.cpp / Geometry.hpp).
9
+ * See https://github.com/bambulab/BambuStudio/issues/9636 and #9968.
10
+ *
11
+ * This module:
12
+ * 1. Indexes every BBL profile JSON by its `name` field.
13
+ * 2. Recursively walks `inherits`, deep-merging parent into child, and
14
+ * applies each level's `include` templates (G-code templates for
15
+ * machines, per-variant defaults for filaments) the way the GUI does.
16
+ * 3. Derives `nozzle_volume_type` from `default_nozzle_volume_type[0]`
17
+ * (the GUI does this implicitly; the CLI doesn't).
18
+ * 4. Validates the model in `BBL/cli_config.json` and merges its CLI-specific
19
+ * machine_limits where supplied for safe accelerations / jerks.
20
+ * 5. Writes the flattened JSON to a temp file the caller passes to
21
+ * BambuStudio CLI.
22
+ *
23
+ * BBL only. Other vendors are out of scope and rejected explicitly so we
24
+ * fail loud rather than producing dangerous gcode for hardware we don't own.
25
+ */
26
+
27
+ import fs from "node:fs/promises";
28
+ import { existsSync, realpathSync } from "node:fs";
29
+ import path from "node:path";
30
+ import crypto from "node:crypto";
31
+
32
+ export type ProfileKind = "machine" | "process" | "filament";
33
+
34
+ export interface FlattenedProfiles {
35
+ machinePath: string;
36
+ processPath: string;
37
+ filamentPaths: string[];
38
+ /** Diagnostics for callers / logs. Not part of the slicer invocation. */
39
+ meta: {
40
+ profilesRoot: string;
41
+ machineLeafName: string;
42
+ processLeafName: string;
43
+ filamentLeafNames: string[];
44
+ /** False only for an explicit standalone custom machine. */
45
+ cliConfigValidated: boolean;
46
+ /** Some validated official model configs intentionally have no limits. */
47
+ cliOverlayApplied: boolean;
48
+ };
49
+ }
50
+
51
+ export interface FlattenOptions {
52
+ /** e.g. "Bambu Lab H2S 0.4 nozzle" */
53
+ machineLeaf: string;
54
+ /** e.g. "0.20mm Standard @BBL H2S" */
55
+ processLeaf: string;
56
+ /** e.g. ["Bambu PLA Basic @BBL H2S"] */
57
+ filamentLeaves: string[];
58
+ /** Absolute path to `.../Resources/profiles`. */
59
+ profilesRoot: string;
60
+ /** Configured BBL directories for custom process/filament dependencies only. */
61
+ userProfileRoots?: string[];
62
+ /** Where to write flattened temp files. */
63
+ tempDir: string;
64
+ /** Vendor subdir under profilesRoot. Currently only "BBL" supported. */
65
+ vendor?: string;
66
+ /**
67
+ * Override for installed nozzle flow type. The printer reports this on
68
+ * boot from its physical nozzle scan; both nozzles always match (you
69
+ * can't mix Standard + High Flow, just like you can't mix 0.2 + 0.4).
70
+ * If omitted we use `default_nozzle_volume_type` from the profile tree
71
+ * (= "Standard" on stock BBL machines). Pass "High Flow" when HF
72
+ * nozzles are installed.
73
+ */
74
+ nozzleVolumeType?: "Standard" | "High Flow";
75
+ /** BambuStudio display name, e.g. "Textured PEI Plate" or "Cool Plate". */
76
+ bedType?: string;
77
+ /** Actual input configs, including user overrides on top of BBL parents. */
78
+ sourceProfiles?: {
79
+ machine?: Record<string, unknown>;
80
+ process?: Record<string, unknown>;
81
+ filaments?: (Record<string, unknown> | undefined)[];
82
+ };
83
+ /**
84
+ * Positional `#RRGGBB` colour per filament slot (e.g. from the input 3MF
85
+ * project or the caller). Missing entries keep the profile's own colour or
86
+ * fall back to DEFAULT_FILAMENT_COLOUR.
87
+ */
88
+ filamentColours?: (string | undefined)[];
89
+ /** Saved per-plate positions, used only when the process sets no position. */
90
+ projectTowerPosition?: { wipe_tower_x?: unknown; wipe_tower_y?: unknown };
91
+ }
92
+
93
+ interface IndexedProfile {
94
+ filePath: string;
95
+ data: Record<string, unknown>;
96
+ }
97
+
98
+ /** Name index plus unreadable JSON files, reported when a name is missing. */
99
+ type NameIndex = Map<string, IndexedProfile> & { malformed?: string[] };
100
+
101
+ /* -------------------------------------------------------------------------- */
102
+ /* Indexing */
103
+ /* -------------------------------------------------------------------------- */
104
+
105
+ /**
106
+ * Build a name -> {filePath, data} map for every JSON in
107
+ * <profilesRoot>/<vendor>/{machine,process,filament}/.
108
+ *
109
+ * The `name` field inside each JSON is the lookup key (this is what
110
+ * `inherits` references). We index every file, including non-instantiable
111
+ * abstract bases like `fdm_machine_common` and `fdm_bbl_3dp_001_common`,
112
+ * because those are the parents we'll walk to.
113
+ */
114
+ async function buildNameIndex(
115
+ profilesRoot: string,
116
+ vendor: string,
117
+ userProfileRoots: string[] = []
118
+ ): Promise<NameIndex> {
119
+ const index: NameIndex = new Map();
120
+ index.malformed = [];
121
+ const subdirs: ProfileKind[] = ["machine", "process", "filament"];
122
+
123
+ const directories = [
124
+ ...subdirs.map(sub => path.join(profilesRoot, vendor, sub)),
125
+ ...userProfileRoots.flatMap(root => ['process', 'filament'].map(sub => path.join(root, sub))),
126
+ ];
127
+ for (const dir of directories) {
128
+ let entries: string[];
129
+ try {
130
+ entries = await fs.readdir(dir);
131
+ } catch {
132
+ // Vendor or subdir missing -- skip silently; flatten will fail later
133
+ // with a precise "name not found" error.
134
+ continue;
135
+ }
136
+ for (const entry of entries) {
137
+ if (!entry.endsWith(".json")) continue;
138
+ const filePath = path.join(dir, entry);
139
+ let raw: string;
140
+ try {
141
+ raw = await fs.readFile(filePath, "utf8");
142
+ } catch {
143
+ continue;
144
+ }
145
+ let data: Record<string, unknown>;
146
+ try {
147
+ data = JSON.parse(raw) as Record<string, unknown>;
148
+ } catch {
149
+ // Malformed profile -- skip, don't poison the index. A reference to
150
+ // it still fails, and the error names the skipped file.
151
+ index.malformed!.push(filePath);
152
+ continue;
153
+ }
154
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
155
+ index.malformed!.push(filePath);
156
+ continue;
157
+ }
158
+ const name = data["name"];
159
+ if (typeof name !== "string" || name.length === 0) continue;
160
+ // First-write wins. BBL doesn't have name collisions in practice;
161
+ // log if it ever does so we notice.
162
+ if (!index.has(name)) {
163
+ index.set(name, { filePath, data });
164
+ }
165
+ }
166
+ }
167
+
168
+ return index;
169
+ }
170
+
171
+ /* -------------------------------------------------------------------------- */
172
+ /* Inheritance walk + merge */
173
+ /* -------------------------------------------------------------------------- */
174
+
175
+ /**
176
+ * Resolve the full inheritance chain for `leafName` and return a single
177
+ * deep-merged object. Child wins on key collision.
178
+ *
179
+ * Throws on:
180
+ * - Unknown name (broken `inherits` reference).
181
+ * - Cycles (A -> B -> A).
182
+ */
183
+ function flattenByName(
184
+ leafName: string,
185
+ index: NameIndex,
186
+ visiting = new Set<string>()
187
+ ): Record<string, unknown> {
188
+ if (visiting.has(leafName)) {
189
+ throw new Error(`Profile inheritance cycle detected (inherits/include): ${[...visiting, leafName].join(" -> ")}`);
190
+ }
191
+ const entry = index.get(leafName);
192
+ if (!entry) {
193
+ throw new Error(`Profile "${leafName}" not found in index. The profile tree is incomplete or the name is misspelled.${describeMalformed(index)}`);
194
+ }
195
+ visiting.add(leafName);
196
+ try {
197
+ return flattenData(entry.data, index, visiting);
198
+ } finally {
199
+ visiting.delete(leafName);
200
+ }
201
+ }
202
+
203
+ function describeMalformed(index: NameIndex): string {
204
+ const malformed = index.malformed ?? [];
205
+ if (malformed.length === 0) return "";
206
+ const shown = malformed.slice(0, 5).map((file) => path.basename(file)).join(", ");
207
+ return ` Skipped ${malformed.length} unreadable or malformed profile file(s): ${shown}${malformed.length > 5 ? ", ..." : ""}.`;
208
+ }
209
+
210
+ function flattenData(
211
+ data: Record<string, unknown>,
212
+ index: NameIndex,
213
+ visiting = new Set<string>()
214
+ ): Record<string, unknown> {
215
+ const parent = data["inherits"];
216
+ const merged = typeof parent === "string" && parent.length > 0
217
+ ? flattenByName(parent, index, visiting)
218
+ : {};
219
+ // Includes may themselves inherit or include templates. Each level wins
220
+ // over its parent, then the including profile's own settings win last.
221
+ applyIncludes(merged, data, index, visiting);
222
+ Object.assign(merged, data);
223
+ delete merged["include"];
224
+ return merged;
225
+ }
226
+
227
+ /** Resolve bundled machine defaults before choosing process and filament leaves. */
228
+ export async function resolveBblMachineProfile(
229
+ profilesRoot: string,
230
+ machineLeaf: string
231
+ ): Promise<Record<string, unknown>> {
232
+ return flattenByName(machineLeaf, await buildNameIndex(profilesRoot, 'BBL'));
233
+ }
234
+
235
+ /** Keys of an include template that describe the template, not the config. */
236
+ const INCLUDE_METADATA_KEYS = new Set(["name", "type", "from", "instantiation", "inherits", "include", "setting_id"]);
237
+
238
+ /**
239
+ * Recent BBL profiles (e.g. "Bambu Lab P2S 0.4 nozzle") no longer carry
240
+ * their G-code inline: `machine_start_gcode`, `machine_end_gcode`,
241
+ * `change_filament_gcode`, ... live in separate "... template <key>"
242
+ * profiles listed under `include`. Skipping them silently falls back to
243
+ * the generic G-code inherited from `fdm_machine_common` & co, which is
244
+ * wrong for the printer (no AMS filament load, other printer's moves).
245
+ */
246
+ function applyIncludes(
247
+ target: Record<string, unknown>,
248
+ profile: Record<string, unknown>,
249
+ index: NameIndex,
250
+ visiting: Set<string>
251
+ ): void {
252
+ const raw = profile["include"];
253
+ if (raw === undefined || raw === null) return;
254
+ if (typeof raw !== "string" && !Array.isArray(raw)) {
255
+ throw new Error(`Profile "${String(profile["name"])}" has an invalid include; expected a name or array of names.`);
256
+ }
257
+ const names = typeof raw === "string" ? [raw] : Array.isArray(raw) ? raw : [];
258
+ for (const name of names) {
259
+ if (typeof name !== "string" || name.trim().length === 0) {
260
+ throw new Error(`Profile "${String(profile["name"])}" has an invalid include reference; every entry must be a nonempty name.`);
261
+ }
262
+ const entry = index.get(name);
263
+ if (!entry) {
264
+ throw new Error(
265
+ `Profile "${String(profile["name"])}" includes "${name}", which is not in the index. ` +
266
+ `Refusing to fall back to inherited defaults (wrong G-code for this printer).${describeMalformed(index)}`
267
+ );
268
+ }
269
+ for (const [key, value] of Object.entries(flattenByName(name, index, visiting))) {
270
+ if (!INCLUDE_METADATA_KEYS.has(key)) target[key] = value;
271
+ }
272
+ }
273
+ }
274
+
275
+ /* -------------------------------------------------------------------------- */
276
+ /* CLI post-processing */
277
+ /* -------------------------------------------------------------------------- */
278
+
279
+ /**
280
+ * Bambu's CLI looks up `nozzle_volume_type`, but the profile tree only
281
+ * defines `default_nozzle_volume_type`. The GUI propagates the latter
282
+ * (or the value reported by the printer's nozzle scan on boot) into the
283
+ * former at runtime. We do the same.
284
+ *
285
+ * Shape: array of strings, one entry per physical nozzle. Hardware
286
+ * invariant from Bambu: BOTH nozzles must match (same diameter, same
287
+ * flow type) -- you cannot install 0.2 + 0.4, and you cannot install
288
+ * Standard + High Flow. So the array always contains identical entries.
289
+ *
290
+ * Verified against a GUI-sliced H2D project_settings.config:
291
+ * ["High Flow", "High Flow"] (dual-nozzle, HF installed)
292
+ * ["Standard", "Standard"] (dual-nozzle, stock)
293
+ * ["Standard"] (single-extruder default)
294
+ *
295
+ * Override priority:
296
+ * 1. Caller-supplied `nozzleVolumeType` (e.g. printer reported HF).
297
+ * 2. Existing `nozzle_volume_type` already in the flattened profile.
298
+ * 3. `default_nozzle_volume_type` from the profile tree.
299
+ * 4. ["Standard"] x extruder count.
300
+ */
301
+ function deriveNozzleVolumeType(
302
+ flat: Record<string, unknown>,
303
+ override?: "Standard" | "High Flow"
304
+ ): void {
305
+ if (override) {
306
+ const count = inferExtruderCount(flat);
307
+ flat["nozzle_volume_type"] = Array(count).fill(override);
308
+ return;
309
+ }
310
+
311
+ if (Array.isArray(flat["nozzle_volume_type"])) {
312
+ enforceMatchingNozzles(flat["nozzle_volume_type"] as unknown[]);
313
+ return;
314
+ }
315
+
316
+ const def = flat["default_nozzle_volume_type"];
317
+ if (Array.isArray(def) && def.every((v) => typeof v === "string")) {
318
+ enforceMatchingNozzles(def);
319
+ flat["nozzle_volume_type"] = [...def];
320
+ return;
321
+ }
322
+
323
+ const extruderCount = inferExtruderCount(flat);
324
+ flat["nozzle_volume_type"] = Array(extruderCount).fill("Standard");
325
+ }
326
+
327
+ /**
328
+ * Hardware invariant: all nozzles on a Bambu printer have identical flow
329
+ * type (and diameter). If a profile somehow declares mixed types it's
330
+ * either bad input or a future mistake -- fail loud so we don't ship
331
+ * gcode that could damage the printer.
332
+ */
333
+ function enforceMatchingNozzles(arr: unknown[]): void {
334
+ if (arr.length <= 1) return;
335
+ const first = arr[0];
336
+ for (let i = 1; i < arr.length; i++) {
337
+ if (arr[i] !== first) {
338
+ throw new Error(
339
+ `nozzle_volume_type entries must all match (Bambu hardware invariant). ` +
340
+ `Got: ${JSON.stringify(arr)}. ` +
341
+ `Both nozzles on H2-series printers always have identical flow type.`
342
+ );
343
+ }
344
+ }
345
+ }
346
+
347
+ /** Best-effort extruder count for fallback nozzle_volume_type sizing. */
348
+ /** BambuStudio's built-in filament_colour default. */
349
+ export const DEFAULT_FILAMENT_COLOUR = "#00AE42";
350
+ const FILAMENT_COLOUR_RE = /^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$/;
351
+
352
+ /**
353
+ * No BBL filament profile defines `filament_colour`; the GUI fills it from
354
+ * the AMS. Without it the CLI keeps a single-entry colour vector however many
355
+ * filaments are loaded and crashes (access violation) as soon as a slice uses
356
+ * any filament after the first. Give every slot exactly one colour.
357
+ */
358
+ function ensureFilamentColour(flat: Record<string, unknown>, colour?: string): void {
359
+ if (colour !== undefined) {
360
+ if (!FILAMENT_COLOUR_RE.test(colour)) {
361
+ throw new Error(`Invalid filament colour "${colour}"; expected #RRGGBB.`);
362
+ }
363
+ flat["filament_colour"] = [colour];
364
+ return;
365
+ }
366
+ const own = flat["filament_colour"];
367
+ if (Array.isArray(own) && typeof own[0] === "string" && FILAMENT_COLOUR_RE.test(own[0])) {
368
+ flat["filament_colour"] = [own[0]];
369
+ return;
370
+ }
371
+ flat["filament_colour"] = [DEFAULT_FILAMENT_COLOUR];
372
+ }
373
+
374
+ // BambuStudio's defaults when a process sets no prime tower position/width.
375
+ const DEFAULT_WIPE_TOWER_X = 15;
376
+ const DEFAULT_WIPE_TOWER_Y = 220;
377
+ const DEFAULT_PRIME_TOWER_WIDTH = 35;
378
+ // Clearance inside the shared nozzle area for the auto-sized tower brim and
379
+ // the CLI's own safety margin (X2D fails at 5 mm from the edge, passes at 6).
380
+ const WIPE_TOWER_MARGIN = 15;
381
+
382
+ interface Rect { minX: number; maxX: number; minY: number; maxY: number }
383
+
384
+ function parseArea(area: string): Rect {
385
+ const points = area.split(",").map((p) => p.trim().split("x").map(Number));
386
+ if (points.length < 3 || points.some((p) => p.length !== 2 || p.some((n) => !Number.isFinite(n)))) {
387
+ throw new Error(`Malformed extruder_printable_area entry "${area}".`);
388
+ }
389
+ const xs = points.map((p) => p[0]);
390
+ const ys = points.map((p) => p[1]);
391
+ return { minX: Math.min(...xs), maxX: Math.max(...xs), minY: Math.min(...ys), maxY: Math.max(...ys) };
392
+ }
393
+
394
+ /**
395
+ * On multi-nozzle machines (H2D, X2D) each nozzle reaches only part of the
396
+ * bed (`extruder_printable_area`), and the prime tower must be reachable by
397
+ * every nozzle. The CLI's default tower position (x=15) lies outside the
398
+ * X2D/H2D right-nozzle area, so slicing fails with "G-code outside of the
399
+ * printable area". When the process sets no position and the default does
400
+ * not fit, move the tower inside the area all nozzles share.
401
+ */
402
+ function placePrimeTowerForAllNozzles(
403
+ machineFlat: Record<string, unknown>,
404
+ processFlat: Record<string, unknown>
405
+ ): void {
406
+ if (processFlat["wipe_tower_x"] !== undefined || processFlat["wipe_tower_y"] !== undefined) return;
407
+ if (["0", "false"].includes(String(processFlat["enable_prime_tower"]).toLowerCase())) return;
408
+ const areas = machineFlat["extruder_printable_area"];
409
+ if (!Array.isArray(areas) || areas.length < 2) return;
410
+ const rects = areas.map((a) => {
411
+ if (typeof a !== "string") throw new Error("Malformed extruder_printable_area in machine profile.");
412
+ return parseArea(a);
413
+ });
414
+ const shared: Rect = {
415
+ minX: Math.max(...rects.map((r) => r.minX)) + WIPE_TOWER_MARGIN,
416
+ maxX: Math.min(...rects.map((r) => r.maxX)) - WIPE_TOWER_MARGIN,
417
+ minY: Math.max(...rects.map((r) => r.minY)) + WIPE_TOWER_MARGIN,
418
+ maxY: Math.min(...rects.map((r) => r.maxY)) - WIPE_TOWER_MARGIN,
419
+ };
420
+ const width = Number(processFlat["prime_tower_width"] ?? DEFAULT_PRIME_TOWER_WIDTH);
421
+ const size = Number.isFinite(width) && width > 0 ? width : DEFAULT_PRIME_TOWER_WIDTH;
422
+ if (shared.maxX - shared.minX < size || shared.maxY - shared.minY < size) {
423
+ throw new Error("No bed area is reachable by every nozzle for the prime tower.");
424
+ }
425
+ const clamp = (v: number, lo: number, hi: number) => Math.min(Math.max(v, lo), hi);
426
+ const x = clamp(DEFAULT_WIPE_TOWER_X, shared.minX, shared.maxX - size);
427
+ const y = clamp(DEFAULT_WIPE_TOWER_Y, shared.minY, shared.maxY - size);
428
+ if (x === DEFAULT_WIPE_TOWER_X && y === DEFAULT_WIPE_TOWER_Y) return;
429
+ processFlat["wipe_tower_x"] = [String(x)];
430
+ processFlat["wipe_tower_y"] = [String(y)];
431
+ }
432
+
433
+ function inferExtruderCount(flat: Record<string, unknown>): number {
434
+ for (const key of ["nozzle_diameter", "extruder_type", "extruder_variant_list"]) {
435
+ const v = flat[key];
436
+ if (Array.isArray(v) && v.length > 0) return v.length;
437
+ }
438
+ return 1;
439
+ }
440
+
441
+ /**
442
+ * Validate the selected model's CLI config before making a bundled profile
443
+ * into a User profile. A1-family models require machine_limits overrides;
444
+ * other official models (including P1S and H2D) intentionally declare only
445
+ * downward_check. Missing config cannot tell us whether limits are required.
446
+ * Returns whether limits were applied, not whether validation succeeded.
447
+ */
448
+ async function applyCliOverlay(
449
+ flat: Record<string, unknown>,
450
+ profilesRoot: string,
451
+ vendor: string
452
+ ): Promise<boolean> {
453
+ const cliConfigPath = path.join(profilesRoot, vendor, "cli_config.json");
454
+ const fail = (reason: string): never => {
455
+ throw new Error(
456
+ `Cannot prepare machine profile "${String(flat["name"])}" ` +
457
+ `(model "${String(flat["printer_model"] ?? stripNozzleSuffix(String(flat["name"])))}"): ` +
458
+ `${cliConfigPath}: ${reason}. Check your BambuStudio installation or BAMBU_PROFILES_ROOT.`
459
+ );
460
+ };
461
+ let raw: string;
462
+ try {
463
+ raw = await fs.readFile(cliConfigPath, "utf8");
464
+ } catch {
465
+ return fail("required CLI configuration is missing or unreadable");
466
+ }
467
+ let cliConfig: unknown;
468
+ try {
469
+ cliConfig = JSON.parse(raw);
470
+ } catch {
471
+ return fail("invalid JSON in required CLI configuration");
472
+ }
473
+ if (!isRecord(cliConfig)) return fail("expected a CLI configuration object");
474
+ const printerSection = cliConfig["printer"];
475
+ if (!isRecord(printerSection)) return fail("expected a printer configuration object");
476
+
477
+ // Match key: cli_config.json keys are bare printer names like
478
+ // "Bambu Lab H2D" / "Bambu Lab A1". If no model is provided, try preset
479
+ // identity with the nozzle suffix stripped, then the name as-is.
480
+ // An explicit model is authoritative; do not silently use another model's
481
+ // limits because a stale preset name happens to match.
482
+ const candidates = typeof flat["printer_model"] === "string" && flat["printer_model"].trim()
483
+ ? [flat["printer_model"]]
484
+ : [
485
+ typeof flat["printer_settings_id"] === "string"
486
+ ? stripNozzleSuffix(flat["printer_settings_id"])
487
+ : undefined,
488
+ typeof flat["name"] === "string" ? stripNozzleSuffix(flat["name"]) : undefined,
489
+ flat["name"],
490
+ ].filter((v): v is string => typeof v === "string" && v.length > 0);
491
+
492
+ const model = candidates.find(key => Object.prototype.hasOwnProperty.call(printerSection, key));
493
+ if (!model) return fail(`selected model is absent (looked for ${candidates.join(", ")})`);
494
+ const block = printerSection[model];
495
+ if (!isRecord(block)) return fail(`printer.${model} must be an object`);
496
+
497
+ const downward = block["downward_check"];
498
+ if (Object.prototype.hasOwnProperty.call(block, "downward_check") && (
499
+ !isRecord(downward) || Object.keys(downward).length === 0 ||
500
+ Object.entries(downward).some(([name, values]) => !name.trim() || !Array.isArray(values) ||
501
+ values.some(value => typeof value !== "string" || !value.trim()))
502
+ )) {
503
+ return fail(`printer.${model}.downward_check must map profile names to arrays of names`);
504
+ }
505
+
506
+ if (!Object.prototype.hasOwnProperty.call(block, "machine_limits")) {
507
+ if (!isRecord(downward)) return fail(`printer.${model} has neither machine_limits nor downward_check`);
508
+ return false;
509
+ }
510
+ const limits = block["machine_limits"];
511
+ if (!isRecord(limits) || Object.keys(limits).length === 0) {
512
+ return fail(`printer.${model}.machine_limits must be a nonempty object`);
513
+ }
514
+ const limitKey = /^cli_safe_(?:acceleration_(?:e|extruding|retracting|travel|x|y|z)|(?:jerk|speed)_(?:e|x|y|z))$/;
515
+ for (const [key, value] of Object.entries(limits)) {
516
+ if (!limitKey.test(key) || typeof value !== "string" ||
517
+ value.split(",").some(part => !part.trim() || !Number.isFinite(Number(part)) || Number(part) < 0)) {
518
+ return fail(`printer.${model}.machine_limits contains an invalid limit "${key}"`);
519
+ }
520
+ }
521
+ // CLI safety values override even explicit values in the selected leaf.
522
+ Object.assign(flat, limits);
523
+ return true;
524
+ }
525
+
526
+ function isRecord(value: unknown): value is Record<string, unknown> {
527
+ return value !== null && typeof value === "object" && !Array.isArray(value);
528
+ }
529
+
530
+ /**
531
+ * Ensure the chosen machine is in the process/filament's
532
+ * `compatible_printers` list. This mirrors what the GUI does when you
533
+ * save a project with a printer/process combo that wasn't in the
534
+ * shipped compat list.
535
+ */
536
+ function ensureMachineInCompatList(
537
+ flat: Record<string, unknown>,
538
+ machineLeaf: string
539
+ ): void {
540
+ const list = flat["compatible_printers"];
541
+ if (!Array.isArray(list)) {
542
+ flat["compatible_printers"] = [machineLeaf];
543
+ return;
544
+ }
545
+ if (!list.includes(machineLeaf)) {
546
+ list.push(machineLeaf);
547
+ }
548
+ }
549
+
550
+ function stripNozzleSuffix(name: string): string {
551
+ return name.replace(/\s+\d+\.\d+\s+nozzle.*$/, "");
552
+ }
553
+
554
+ /**
555
+ * Adjust fields for CLI consumption.
556
+ *
557
+ * - Strip `inherits` and `instantiation` (chain marker, abstract-base flag).
558
+ * The GUI consumes them; the CLI treats anything still present as part of
559
+ * the merged config.
560
+ * - Rewrite `from`. Leaf BBL profiles ship with `"from": "system"`, which
561
+ * the CLI rejects when loaded via `--load-settings` (system presets
562
+ * aren't supposed to be loaded that way). The GUI rewrites this to
563
+ * `"from": "project"` when it embeds the merged config in a 3MF. We do
564
+ * the same so the CLI accepts our flattened temp file.
565
+ * - Strip `setting_id` / `is_custom_defined` (user-registry markers that
566
+ * make no sense on a transient flattened file).
567
+ */
568
+ function normalizeForCli(
569
+ flat: Record<string, unknown>,
570
+ kind: ProfileKind,
571
+ leafName: string
572
+ ): void {
573
+ // Set inherits to the leaf name BEFORE we delete it below, so the
574
+ // CLI's system_name resolution lands on the right value.
575
+ // (See note further down for why this matters.)
576
+ flat["inherits"] = leafName;
577
+ // Identity field. The CLI sets this internally, but we mirror it for
578
+ // consistency with what the GUI's project_settings.config emits.
579
+ switch (kind) {
580
+ case "machine":
581
+ flat["printer_settings_id"] = leafName;
582
+ break;
583
+ case "process":
584
+ flat["print_settings_id"] = leafName;
585
+ break;
586
+ case "filament":
587
+ flat["filament_settings_id"] = [leafName];
588
+ break;
589
+ }
590
+
591
+ // CRITICAL: when from=="User", the CLI computes `system_name = inherits`
592
+ // and the compatibility check compares the *other* configs'
593
+ // `compatible_printers` list against that system_name. The leaf
594
+ // profiles' compat lists contain the leaf machine name (e.g.
595
+ // "Bambu Lab H2S 0.4 nozzle"), so we must set `inherits` on the
596
+ // flattened machine to that same leaf name. For process/filament,
597
+ // `inherits` doesn't drive the compat check we hit, but we set it for
598
+ // symmetry so any future check succeeds the same way.
599
+ // Source: BambuStudio.cpp ~line 2222 (from!="system" -> system_name = inherits).
600
+ // NOTE: do NOT delete inherits -- we just set it above. The CLI uses
601
+ // its value (when from=="User") for the system_name compat check.
602
+ delete flat["instantiation"];
603
+ delete flat["setting_id"];
604
+ delete flat["is_custom_defined"];
605
+ // Always rewrite `from` to "User". "Project" is what the GUI uses when
606
+ // embedding in a 3MF, but the CLI accepts "User" for --load-settings
607
+ // paths and that's semantically what we are.
608
+ flat["from"] = "User";
609
+ // Mirror the GUI's behavior of clearing compatibility constraints in the
610
+ // merged project config. The leaf process/filament profiles ship with
611
+ // `compatible_printers: ["Bambu Lab H2S 0.4 nozzle"]` etc., and the CLI
612
+ // re-validates that list against our flattened machine config -- which
613
+ // has had `from` rewritten and inheritance collapsed, so the equality
614
+ // check fails. The GUI's project_settings.config has these set to null
615
+ // because at that point compatibility is already established by the
616
+ // user. We do the same.
617
+ // Leave compatible_printers / compatible_prints as the leaf declared
618
+ // them. The GUI nulls these in embedded project configs, but the CLI's
619
+ // --load-settings path requires a non-empty list and matches against
620
+ // the machine's `name` / `printer_settings_id`. The leaves ship with
621
+ // the correct list ([machine_leaf_name]) so just preserve.
622
+ // _condition fields can stay null (string-typed, tolerated as null).
623
+ }
624
+
625
+ function applyBedType(processFlat: Record<string, unknown>, bedType?: string): void {
626
+ if (!bedType) return;
627
+ processFlat.curr_bed_type = bedType;
628
+ }
629
+
630
+ function applyMachineModelBedMetadata(
631
+ machineFlat: Record<string, unknown>,
632
+ index: NameIndex
633
+ ): void {
634
+ const modelName = machineFlat.printer_model;
635
+ if (typeof modelName !== "string") return;
636
+
637
+ const model = index.get(modelName)?.data;
638
+ if (!model) return;
639
+
640
+ for (const key of ["default_bed_type", "image_bed_type", "not_support_bed_type"]) {
641
+ if (!(key in machineFlat) && key in model) {
642
+ machineFlat[key] = model[key];
643
+ }
644
+ }
645
+ }
646
+
647
+ /* -------------------------------------------------------------------------- */
648
+ /* Public entry point */
649
+ /* -------------------------------------------------------------------------- */
650
+
651
+ /**
652
+ * Flatten the leaf profiles, post-process for CLI, and write to temp files.
653
+ *
654
+ * Throws on unknown leaf names, missing profilesRoot, or cycles.
655
+ */
656
+ export async function flattenForCli(opts: FlattenOptions): Promise<FlattenedProfiles> {
657
+ const vendor = opts.vendor ?? "BBL";
658
+ if (vendor !== "BBL") {
659
+ throw new Error(
660
+ `profile-flatten: only BBL vendor is supported (got "${vendor}"). ` +
661
+ `Other vendors are out of scope -- contributions welcome but untested.`
662
+ );
663
+ }
664
+
665
+ // Confirm the profiles root looks plausible before doing real work.
666
+ const probe = path.join(opts.profilesRoot, vendor, "machine");
667
+ try {
668
+ await fs.access(probe);
669
+ } catch {
670
+ throw new Error(
671
+ `profile-flatten: profilesRoot "${opts.profilesRoot}" does not contain "${vendor}/machine". ` +
672
+ `Set BAMBU_PROFILES_ROOT or check your BambuStudio install.`
673
+ );
674
+ }
675
+
676
+ // Machine inheritance must never resolve through user process/filament files.
677
+ const machineIndex = await buildNameIndex(opts.profilesRoot, vendor);
678
+ const index = opts.userProfileRoots?.length
679
+ ? await buildNameIndex(opts.profilesRoot, vendor, opts.userProfileRoots)
680
+ : machineIndex;
681
+
682
+ // Flatten each leaf.
683
+ if (opts.sourceProfiles?.filaments && opts.sourceProfiles.filaments.length !== opts.filamentLeaves.length) {
684
+ throw new Error("Every filament slot must have a source profile.");
685
+ }
686
+ const machineFlat = opts.sourceProfiles?.machine
687
+ ? flattenData(opts.sourceProfiles.machine, machineIndex)
688
+ : flattenByName(opts.machineLeaf, machineIndex);
689
+ const processFlat = opts.sourceProfiles?.process
690
+ ? flattenData(opts.sourceProfiles.process, index)
691
+ : flattenByName(opts.processLeaf, index);
692
+ const filamentFlats = opts.filamentLeaves.map((n, i) => {
693
+ const source = opts.sourceProfiles?.filaments?.[i];
694
+ return source ? flattenData(source, index) : flattenByName(n, index);
695
+ });
696
+
697
+ // CLI-specific post-processing on machine profile only.
698
+ deriveNozzleVolumeType(machineFlat, opts.nozzleVolumeType);
699
+ applyMachineModelBedMetadata(machineFlat, machineIndex);
700
+ // A standalone custom machine can accompany process/filament profiles that
701
+ // need BBL resolution; do not impose bundled model config on that machine.
702
+ const sourceMachine = opts.sourceProfiles?.machine;
703
+ const standaloneMachine = sourceMachine && String(sourceMachine.from).toLowerCase() !== "system" &&
704
+ !(typeof sourceMachine.inherits === "string" && sourceMachine.inherits.length > 0) &&
705
+ (sourceMachine.include === undefined || sourceMachine.include === null);
706
+ const cliConfigValidated = !standaloneMachine;
707
+ const cliOverlayApplied = cliConfigValidated
708
+ ? await applyCliOverlay(machineFlat, opts.profilesRoot, vendor)
709
+ : false;
710
+
711
+ // Normalize each flattened profile for CLI consumption.
712
+ normalizeForCli(machineFlat, "machine", opts.machineLeaf);
713
+ normalizeForCli(processFlat, "process", opts.processLeaf);
714
+ filamentFlats.forEach((f, i) => normalizeForCli(f, "filament", opts.filamentLeaves[i]));
715
+ if (opts.filamentColours && opts.filamentColours.length !== filamentFlats.length) {
716
+ throw new Error(
717
+ `${opts.filamentColours.length} filament colours were supplied for ${filamentFlats.length} filament slots.`
718
+ );
719
+ }
720
+ filamentFlats.forEach((f, i) => ensureFilamentColour(f, opts.filamentColours?.[i]));
721
+ applyBedType(processFlat, opts.bedType);
722
+ if (processFlat["wipe_tower_x"] === undefined && processFlat["wipe_tower_y"] === undefined) {
723
+ Object.assign(processFlat, opts.projectTowerPosition);
724
+ }
725
+ placePrimeTowerForAllNozzles(machineFlat, processFlat);
726
+
727
+ // Mirror the GUI's auto-extend behavior: when the caller explicitly
728
+ // chose a process or filament that wasn't pre-declared compatible with
729
+ // the chosen machine (e.g. "0.20mm Standard @BBL P1P" used on a P1S),
730
+ // add the machine name to the process/filament compat list. The GUI
731
+ // does this implicitly when saving a project.
732
+ ensureMachineInCompatList(processFlat, opts.machineLeaf);
733
+ filamentFlats.forEach((f) => ensureMachineInCompatList(f, opts.machineLeaf));
734
+
735
+ // Hash the resolved content so concurrent jobs using the same preset with
736
+ // different overrides never overwrite each other's input files.
737
+ await fs.mkdir(opts.tempDir, { recursive: true });
738
+ const machinePath = await writeTemp(opts.tempDir, "machine", opts.machineLeaf, machineFlat);
739
+ const processPath = await writeTemp(opts.tempDir, "process", opts.processLeaf, processFlat);
740
+ const filamentPaths: string[] = [];
741
+ for (let i = 0; i < filamentFlats.length; i++) {
742
+ filamentPaths.push(
743
+ await writeTemp(opts.tempDir, `filament-${i}`, opts.filamentLeaves[i], filamentFlats[i])
744
+ );
745
+ }
746
+
747
+ return {
748
+ machinePath,
749
+ processPath,
750
+ filamentPaths,
751
+ meta: {
752
+ profilesRoot: opts.profilesRoot,
753
+ machineLeafName: opts.machineLeaf,
754
+ processLeafName: opts.processLeaf,
755
+ filamentLeafNames: opts.filamentLeaves,
756
+ cliConfigValidated,
757
+ cliOverlayApplied,
758
+ },
759
+ };
760
+ }
761
+
762
+ async function writeTemp(
763
+ tempDir: string,
764
+ kind: string,
765
+ leafName: string,
766
+ data: Record<string, unknown>
767
+ ): Promise<string> {
768
+ const serialized = JSON.stringify(data, null, 2);
769
+ const hash = crypto.createHash("sha256").update(leafName).update("\0").update(serialized).digest("hex").slice(0, 16);
770
+ const safe = leafName.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 64);
771
+ const filename = `flat-${kind}-${safe}-${hash}.json`;
772
+ const out = path.join(tempDir, filename);
773
+ // Concurrent slices flatten identical content to the same name; stage a
774
+ // private file and rename so no reader ever sees a partial profile.
775
+ const staging = `${out}.${process.pid}.${crypto.randomUUID()}.tmp`;
776
+ await fs.writeFile(staging, serialized, "utf8");
777
+ await fs.rename(staging, out);
778
+ return out;
779
+ }
780
+
781
+ /* -------------------------------------------------------------------------- */
782
+ /* Profile root detection */
783
+ /* -------------------------------------------------------------------------- */
784
+
785
+ /**
786
+ * Given the SLICER_PATH (path to BambuStudio executable), walk up to the
787
+ * profile directory for that installation (macOS, Windows, or Linux prefix).
788
+ *
789
+ * Override via BAMBU_PROFILES_ROOT env.
790
+ */
791
+ export function detectProfilesRoot(slicerPath?: string, slicerType = 'bambustudio'): string {
792
+ if (process.env["BAMBU_PROFILES_ROOT"]) {
793
+ return process.env["BAMBU_PROFILES_ROOT"];
794
+ }
795
+
796
+ if (slicerPath) {
797
+ let executable = slicerPath;
798
+ if (!slicerPath.includes('/') && !slicerPath.includes('\\')) {
799
+ const located = (process.env.PATH ?? '').split(path.delimiter)
800
+ .map(dir => path.join(dir, slicerPath))
801
+ .find(candidate => existsSync(candidate));
802
+ if (located) executable = located;
803
+ }
804
+ // Package-manager launchers may be symlinks into the installation prefix.
805
+ try { executable = realpathSync(executable); } catch { /* Probe the supplied path below. */ }
806
+ const bin = path.dirname(executable);
807
+ const installNames = slicerType === 'bambustudio'
808
+ ? ['BambuStudio', 'bambu-studio']
809
+ : ['OrcaSlicer', 'orca-slicer', 'OrcaStudio', 'orca-studio'];
810
+ const candidates = path.basename(bin) === 'MacOS'
811
+ ? [path.resolve(bin, '..', 'Resources', 'profiles')]
812
+ : [
813
+ path.join(bin, 'resources', 'profiles'),
814
+ path.join(bin, 'Resources', 'profiles'),
815
+ ...installNames.flatMap(name => [
816
+ path.resolve(bin, '..', 'share', name, 'profiles'),
817
+ path.resolve(bin, '..', 'share', name, 'resources', 'profiles'),
818
+ ]),
819
+ ];
820
+ const found = candidates.find(root => existsSync(path.join(root, 'BBL', 'machine')));
821
+ // Do not select another installation if this executable has no profile tree.
822
+ // flattenForCli reports the missing tree and asks for BAMBU_PROFILES_ROOT.
823
+ return found ?? candidates[0];
824
+ }
825
+
826
+ // Default macOS install.
827
+ return slicerType === 'bambustudio'
828
+ ? '/Applications/BambuStudio.app/Contents/Resources/profiles'
829
+ : '/Applications/OrcaSlicer.app/Contents/Resources/profiles';
830
+ }