@faicad/faijs-fcstd 0.17.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.
Files changed (87) hide show
  1. package/LICENSE +29 -0
  2. package/NOTICE +20 -0
  3. package/dist/attachment.d.ts +72 -0
  4. package/dist/attachment.d.ts.map +1 -0
  5. package/dist/attachment.js +93 -0
  6. package/dist/attachment.js.map +1 -0
  7. package/dist/bspline.d.ts +58 -0
  8. package/dist/bspline.d.ts.map +1 -0
  9. package/dist/bspline.js +93 -0
  10. package/dist/bspline.js.map +1 -0
  11. package/dist/build-fai-zip.d.ts +40 -0
  12. package/dist/build-fai-zip.d.ts.map +1 -0
  13. package/dist/build-fai-zip.js +111 -0
  14. package/dist/build-fai-zip.js.map +1 -0
  15. package/dist/cli.d.ts +3 -0
  16. package/dist/cli.d.ts.map +1 -0
  17. package/dist/cli.js +37 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/codegen.d.ts +83 -0
  20. package/dist/codegen.d.ts.map +1 -0
  21. package/dist/codegen.js +618 -0
  22. package/dist/codegen.js.map +1 -0
  23. package/dist/container.d.ts +75 -0
  24. package/dist/container.d.ts.map +1 -0
  25. package/dist/container.js +36 -0
  26. package/dist/container.js.map +1 -0
  27. package/dist/contour.d.ts +43 -0
  28. package/dist/contour.d.ts.map +1 -0
  29. package/dist/contour.js +132 -0
  30. package/dist/contour.js.map +1 -0
  31. package/dist/convert.d.ts +69 -0
  32. package/dist/convert.d.ts.map +1 -0
  33. package/dist/convert.js +303 -0
  34. package/dist/convert.js.map +1 -0
  35. package/dist/document.d.ts +48 -0
  36. package/dist/document.d.ts.map +1 -0
  37. package/dist/document.js +140 -0
  38. package/dist/document.js.map +1 -0
  39. package/dist/expressions.d.ts +79 -0
  40. package/dist/expressions.d.ts.map +1 -0
  41. package/dist/expressions.js +162 -0
  42. package/dist/expressions.js.map +1 -0
  43. package/dist/external-geo.d.ts +49 -0
  44. package/dist/external-geo.d.ts.map +1 -0
  45. package/dist/external-geo.js +140 -0
  46. package/dist/external-geo.js.map +1 -0
  47. package/dist/feature-translate.d.ts +193 -0
  48. package/dist/feature-translate.d.ts.map +1 -0
  49. package/dist/feature-translate.js +1441 -0
  50. package/dist/feature-translate.js.map +1 -0
  51. package/dist/fillet-edges.d.ts +26 -0
  52. package/dist/fillet-edges.d.ts.map +1 -0
  53. package/dist/fillet-edges.js +36 -0
  54. package/dist/fillet-edges.js.map +1 -0
  55. package/dist/index.d.ts +23 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +19 -0
  58. package/dist/index.js.map +1 -0
  59. package/dist/placement.d.ts +93 -0
  60. package/dist/placement.d.ts.map +1 -0
  61. package/dist/placement.js +117 -0
  62. package/dist/placement.js.map +1 -0
  63. package/dist/planegcs-backend.d.ts +34 -0
  64. package/dist/planegcs-backend.d.ts.map +1 -0
  65. package/dist/planegcs-backend.js +665 -0
  66. package/dist/planegcs-backend.js.map +1 -0
  67. package/dist/sketch-parse.d.ts +199 -0
  68. package/dist/sketch-parse.d.ts.map +1 -0
  69. package/dist/sketch-parse.js +263 -0
  70. package/dist/sketch-parse.js.map +1 -0
  71. package/dist/sketch-solver.d.ts +63 -0
  72. package/dist/sketch-solver.d.ts.map +1 -0
  73. package/dist/sketch-solver.js +28 -0
  74. package/dist/sketch-solver.js.map +1 -0
  75. package/dist/sketch-verify.d.ts +53 -0
  76. package/dist/sketch-verify.d.ts.map +1 -0
  77. package/dist/sketch-verify.js +71 -0
  78. package/dist/sketch-verify.js.map +1 -0
  79. package/dist/structural-types.d.ts +96 -0
  80. package/dist/structural-types.d.ts.map +1 -0
  81. package/dist/structural-types.js +155 -0
  82. package/dist/structural-types.js.map +1 -0
  83. package/dist/unpack.d.ts +44 -0
  84. package/dist/unpack.d.ts.map +1 -0
  85. package/dist/unpack.js +64 -0
  86. package/dist/unpack.js.map +1 -0
  87. package/package.json +65 -0
@@ -0,0 +1,1441 @@
1
+ import { parseExpressionEngine, evalWithDoc } from './expressions.js';
2
+ import { placementOf, quatToMatrix } from './placement.js';
3
+ import { shapeBrpFile } from './external-geo.js';
4
+ /**
5
+ * Wrap raw JS source as a verbatim argument (`JsExpr`).
6
+ *
7
+ * @param code - the JS expression source to emit in the argument position.
8
+ * @returns the `JsExpr` marker carrying that source.
9
+ */
10
+ export function jsExpr(code) {
11
+ return { __jsExpr: code };
12
+ }
13
+ /**
14
+ * True for a `JsExpr` marker (used by M5 to render verbatim).
15
+ *
16
+ * @param v - the value to test.
17
+ * @returns true when `v` is a `JsExpr` marker.
18
+ */
19
+ export function isJsExpr(v) {
20
+ return typeof v === 'object' && v !== null && typeof v.__jsExpr === 'string';
21
+ }
22
+ /**
23
+ * H7 (hole_puzzle corpus, 2026-09-20): marker input for a subtract whose base
24
+ * is implied by the Body's feature order (no explicit BaseFeature property).
25
+ * Codegen retargets this at the chain head when folding the feature into its
26
+ * Body chain. Never a legal variable name (contains `::`), so it cannot be
27
+ * confused with a real input.
28
+ */
29
+ export const BODY_CHAIN_BASE = '::body-chain-base::';
30
+ /** M4.1 whitelist (plan §5.5.5 measurable types only). */
31
+ const WHITELIST = new Set([
32
+ 'Part::Box',
33
+ 'Part::Cylinder',
34
+ 'Part::Cut',
35
+ 'Part::MultiFuse',
36
+ 'Part::Extrusion',
37
+ 'PartDesign::Pad',
38
+ 'PartDesign::Pocket',
39
+ 'PartDesign::Revolution',
40
+ // P2-2 (2026-09-24): Groove is Revolution + subtractive — same Profile/
41
+ // ReferenceAxis/Angle shape as Revolution, but cuts from the base feature
42
+ // instead of fusing. Previously absent from the whitelist it silently fell
43
+ // to preservedOnly (26 objects in Mannequin_mp alone).
44
+ 'PartDesign::Groove',
45
+ 'PartDesign::LinearPattern',
46
+ 'PartDesign::PolarPattern',
47
+ 'PartDesign::Fillet',
48
+ 'PartDesign::Chamfer',
49
+ // M13.1 (probed on real corpus — fcstd-port/tools/probe-m13-types.ts):
50
+ // Part::Compound carries a Links PropertyLinkList; Part::Sphere carries
51
+ // Radius (+ optional Angle like Cylinder).
52
+ 'Part::Compound',
53
+ 'Part::Sphere',
54
+ // P5 (2026-09-24): Part::Mirroring mirrors its Source across the plane
55
+ // through Base with normal Normal (253 corpus occurrences).
56
+ 'Part::Mirroring',
57
+ // P6 (2026-09-24): Part::Revolution revolves Source around the axis
58
+ // through Base with direction Axis by Angle degrees (425 corpus
59
+ // occurrences — highest-frequency untranslated Part::* type after P5).
60
+ 'Part::Revolution',
61
+ // P7 (2026-09-24): Part::Fuse fuses Base + Tool (two PropertyLinks, same
62
+ // serialization shape as Part::Cut — 42 corpus occurrences).
63
+ 'Part::Fuse',
64
+ // P8 (2026-09-24): Part::Chamfer — Base link + edge selection AND sizes in
65
+ // the binary PropertyFilletEdges ZIP member (109 corpus occurrences).
66
+ 'Part::Chamfer',
67
+ // P9 (2026-09-24): Part::Fillet — same binary PropertyFilletEdges member as
68
+ // Part::Chamfer (196 corpus occurrences). cad.fillet (M1) takes ONE uniform
69
+ // radius for all edges, so per-edge / two-distance differences bake.
70
+ 'Part::Fillet',
71
+ // P2-3 (2026-09-24): sweep/loft/helix translation branch. The kernel ops
72
+ // `cad.sweep` / `cad.loft` / `cad.helix` (core, a4f9f30 / b0c4a92) are
73
+ // already implemented; this wires the FCStd translator to emit them.
74
+ // Corpus (library-profile.md): Part::Sweep 268, Part::Loft 107, Part::Helix <63.
75
+ 'Part::Sweep',
76
+ 'Part::Loft',
77
+ 'Part::Helix',
78
+ ]);
79
+ /**
80
+ * True when the object type is on the M4.1 translation whitelist.
81
+ *
82
+ * @param type - the FCStd object type, e.g. "Part::Box".
83
+ * @returns true when the type is whitelisted for translation.
84
+ */
85
+ export function isWhitelisted(type) {
86
+ return WHITELIST.has(type);
87
+ }
88
+ /**
89
+ * H10 (plan §3.1/§3.5): C4's Python exception, decided by PROPERTY presence —
90
+ * NOT by the `Python` type-name suffix. Matches the library profile's
91
+ * pythonObjects口径 (profile.mjs: type contains "Python" or carries
92
+ * Python/Proxy properties); here only the property evidence qualifies, so a
93
+ * Python-suffixed type without the property stays a plain translation gap.
94
+ * @param obj - the FCStd object to inspect.
95
+ * @returns true when the object is a Python-scripted feature whose serialized
96
+ * shape is opaque (legitimate `python-baked` under C4).
97
+ */
98
+ export function isPythonOpaque(obj) {
99
+ for (const [name, prop] of obj.properties) {
100
+ if (name === 'Python' || name === 'Proxy')
101
+ return true;
102
+ if (prop.type === 'App::PropertyPythonObject')
103
+ return true;
104
+ }
105
+ return false;
106
+ }
107
+ function propNum(obj, name) {
108
+ // M11.1: an ExpressionEngine binding overrides the stored <Float> value
109
+ // (FreeCAD recomputes bound properties from expressions on load). A
110
+ // non-constant binding is reported via exprBindingOf, not guessed here.
111
+ const bound = expressionBindingOf(obj, name);
112
+ if (bound && bound.value !== undefined)
113
+ return bound.value;
114
+ const p = obj.properties.get(name);
115
+ if (!p)
116
+ return undefined;
117
+ const el = p.children[0];
118
+ const v = el?.attributes['value'];
119
+ return v === undefined ? undefined : Number(v);
120
+ }
121
+ /**
122
+ * M11.1/M11.2: the ExpressionEngine binding for `name`, if any. `value` is
123
+ * undefined for non-constant expressions (references/arithmetic) — the caller
124
+ * must bake with an explicit reason instead of estimating.
125
+ *
126
+ * @param obj - the FCStd object whose ExpressionEngine to inspect.
127
+ * @param name - the property name to look up.
128
+ * @returns the binding for `name`, or undefined when the object has no
129
+ * ExpressionEngine binding for it.
130
+ */
131
+ export function expressionBindingOf(obj, name) {
132
+ const bindings = parseExpressionEngine(obj.properties.get('ExpressionEngine'));
133
+ if (bindings.length === 0)
134
+ return undefined;
135
+ const norm = (p) => (p.startsWith('.') ? p.slice(1) : p);
136
+ const b = bindings.find((b) => norm(b.path) === name);
137
+ // P1-1(参数载体):非常量绑定尝试三跳解析(<<Label>>.Alias → 单元格值)。
138
+ // docObjects 由 translateObject 入口注入(模块级上下文,见 docContext)。
139
+ if (b && b.value === undefined && docContext) {
140
+ const v = evalWithDoc(b.expression, docContext);
141
+ if (v !== undefined)
142
+ return { ...b, value: v };
143
+ }
144
+ return b;
145
+ }
146
+ /** P1-1: translateObject 入口注入的文档对象上下文(表达式的引用解析需要全文档)。 */
147
+ let docContext;
148
+ /**
149
+ * M11.2: detect a non-constant expression binding on a property.
150
+ *
151
+ * @param obj - the FCStd object whose ExpressionEngine to inspect.
152
+ * @param name - the property name to look up.
153
+ * @returns true when `name` has a binding that is NOT a constant expression.
154
+ */
155
+ export function hasNonConstantBinding(obj, name) {
156
+ const b = expressionBindingOf(obj, name);
157
+ return b !== undefined && b.value === undefined;
158
+ }
159
+ function propBool(obj, name) {
160
+ const el = obj.properties.get(name)?.children[0];
161
+ return el?.attributes['value'] === 'true';
162
+ }
163
+ function propLink(obj, name) {
164
+ const el = obj.properties.get(name)?.children[0];
165
+ const v = el?.attributes['value'];
166
+ return v && v.length > 0 ? v : undefined;
167
+ }
168
+ /** Read a string-valued property (e.g. ReferenceAxis). */
169
+ function propStr(obj, name) {
170
+ const el = obj.properties.get(name)?.children[0];
171
+ const v = el?.attributes['value'];
172
+ return v && v.length > 0 ? v : undefined;
173
+ }
174
+ const PAD_TYPES = {
175
+ '0': 'Length', '1': 'UpToLast', '2': 'UpToFirst', '3': 'UpToFace', '4': 'TwoLengths',
176
+ Length: 'Length', UpToLast: 'UpToLast', UpToFirst: 'UpToFirst', UpToFace: 'UpToFace', TwoLengths: 'TwoLengths',
177
+ };
178
+ const POCKET_TYPES = {
179
+ '0': 'Length', '1': 'ThroughAll', '2': 'UpToFirst', '3': 'UpToFace', '4': 'TwoLengths',
180
+ Length: 'Length', ThroughAll: 'ThroughAll', UpToFirst: 'UpToFirst', UpToFace: 'UpToFace', TwoLengths: 'TwoLengths',
181
+ };
182
+ /**
183
+ * Read the Pad/Pocket `Type` enumeration of an object (M9.1).
184
+ *
185
+ * @param obj - the FCStd Pad or Pocket object.
186
+ * @param kind - which type-enum table to apply (Pad vs Pocket labels differ).
187
+ * @returns the parsed feature type; 'Length' when Type is missing, 'unknown'
188
+ * when the stored label/index is not recognized.
189
+ */
190
+ export function featureTypeOf(obj, kind) {
191
+ const el = obj.properties.get('Type')?.children[0];
192
+ const raw = el?.attributes['value'];
193
+ if (raw === undefined || raw === '')
194
+ return 'Length';
195
+ const table = kind === 'pad' ? PAD_TYPES : POCKET_TYPES;
196
+ return table[raw] ?? 'unknown';
197
+ }
198
+ /** Read an App::PropertyVector (`value="x y z"`) as a Vec3. */
199
+ function propVec(obj, name) {
200
+ const raw = propStr(obj, name);
201
+ if (!raw)
202
+ return undefined;
203
+ const parts = raw.trim().split(/\s+/).map(Number);
204
+ if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n)))
205
+ return undefined;
206
+ return [parts[0], parts[1], parts[2]];
207
+ }
208
+ /**
209
+ * Read an App::PropertyVector serialized as a `<PropertyVector valueX= valueY=
210
+ * valueZ=/>` child element (P5: Part::Mirroring Base/Normal use this form —
211
+ * GOTCHA: propVec expects `value="x y z"`, a DIFFERENT serialization).
212
+ */
213
+ function propVecXYZ(obj, name) {
214
+ const a = obj.properties.get(name)?.children[0]?.attributes;
215
+ if (!a)
216
+ return undefined;
217
+ const x = Number(a['valueX']), y = Number(a['valueY']), z = Number(a['valueZ']);
218
+ if (![x, y, z].every(Number.isFinite))
219
+ return undefined;
220
+ return [x, y, z];
221
+ }
222
+ /** Normalize a Vec3 to unit length (zero-safe: returns input if |v| = 0). */
223
+ function normalize3(v) {
224
+ const mag = Math.hypot(v[0], v[1], v[2]);
225
+ if (mag <= 0)
226
+ return v;
227
+ return [v[0] / mag, v[1] / mag, v[2] / mag];
228
+ }
229
+ /**
230
+ * Read an `App::PropertyLinkSub`: the target object name plus its sub-element
231
+ * names. FreeCAD serializes this as
232
+ * `<LinkSub value="Pad001" count="2"><Sub value="Edge17"/><Sub value="Edge18"/></LinkSub>`.
233
+ */
234
+ function propLinkSub(obj, name) {
235
+ const el = obj.properties.get(name)?.children[0];
236
+ if (!el)
237
+ return undefined;
238
+ const target = el.attributes['value'];
239
+ if (!target || target.length === 0)
240
+ return undefined;
241
+ const subs = [];
242
+ for (const sub of el.children) {
243
+ const v = sub.attributes['value'];
244
+ if (v)
245
+ subs.push(v);
246
+ }
247
+ return { obj: target, subs };
248
+ }
249
+ /**
250
+ * Parse FreeCAD edge sub-element names (`Edge17`) into 1-based ordinals.
251
+ * Returns undefined when any entry is not an `EdgeN` reference (a Face/Vertex
252
+ * selection cannot be expressed as a faijs `EdgeTopoRef`).
253
+ */
254
+ function parseEdgeSubs(subs) {
255
+ const out = [];
256
+ for (const s of subs) {
257
+ const m = /^Edge(\d+)$/.exec(s);
258
+ if (!m)
259
+ return undefined;
260
+ const n = Number(m[1]);
261
+ if (!Number.isInteger(n) || n < 1)
262
+ return undefined;
263
+ out.push(n);
264
+ }
265
+ return out;
266
+ }
267
+ /**
268
+ * Parse a FreeCAD face sub-element name (`Face3`) into a 1-based ordinal.
269
+ * Returns undefined when the selection is not a plain `FaceN` reference (e.g. a
270
+ * TNaming-modified name `"Face__20f_..."`, an `Edge*`/`Vertex*` selection, or a
271
+ * multi-face set) so the caller can bake with an explicit reason instead of
272
+ * guessing. The ordinal is consumed by `cad.faceRef`, whose face enumeration
273
+ * order is calibrated to match FreeCAD's `FaceN` (plan §4.3-C2 / R-A).
274
+ */
275
+ function parseFaceSub(subs) {
276
+ if (subs.length !== 1)
277
+ return undefined;
278
+ const m = /^Face(\d+)$/.exec(subs[0]);
279
+ if (!m)
280
+ return undefined;
281
+ const n = Number(m[1]);
282
+ return Number.isInteger(n) && n >= 1 ? n : undefined;
283
+ }
284
+ /**
285
+ * Build the `edges` argument for a fillet/chamfer call: one `cad.edgeRef(base, N)`
286
+ * expression per FreeCAD edge ordinal. The refs must be resolved against the
287
+ * live base shape at run time (an `EdgeTopoRef` is a two-face role pair, which
288
+ * only the runtime naming layer knows), so they enter the IR as `JsExpr`.
289
+ */
290
+ function edgeRefArgs(baseVar, ordinals) {
291
+ return ordinals.map((n) => jsExpr(`cad.edgeRef(${baseVar}, ${n})`));
292
+ }
293
+ /**
294
+ * Parse a PartDesign ReferenceAxis reference into a 3D axis + pivot point.
295
+ *
296
+ * FreeCAD stores this as an `App::PropertyLinkSub` string that either names a
297
+ * standard body axis (`V_Axis` / `H_Axis` / `N_Axis`, or the generic `Axis`
298
+ * that PartDesign revolves around = +Z) or an edge/vertex of another feature.
299
+ * Edge/vertex axes require resolving referenced geometry, which the port does
300
+ * not yet do (explicit downgrade, no silent loss).
301
+ *
302
+ * @param ref - the ReferenceAxis (or Direction) LinkSub string, may be undefined.
303
+ * @returns a unit axis and pivot point, or undefined when the reference names
304
+ * edge/vertex geometry (unsupported).
305
+ */
306
+ export function parseReferenceAxis(ref) {
307
+ const at = [0, 0, 0];
308
+ if (!ref)
309
+ return { axis: [0, 0, 1], at };
310
+ if (/Edge|Vertex/i.test(ref))
311
+ return undefined; // geometry-referenced axis: unsupported
312
+ // Standard body axes. PartDesign LinearPattern stores Direction as a LinkSub
313
+ // naming X_Axis/Y_Axis/Z_Axis; older ReferenceAxis uses V_Axis/H_Axis/N_Axis.
314
+ if (/X_Axis|H_Axis/i.test(ref))
315
+ return { axis: [1, 0, 0], at };
316
+ if (/Y_Axis/i.test(ref))
317
+ return { axis: [0, 1, 0], at };
318
+ if (/Z_Axis|V_Axis/i.test(ref))
319
+ return { axis: [0, 0, 1], at };
320
+ if (/N_Axis/i.test(ref))
321
+ return { axis: [1, 0, 0], at }; // legacy mapping, keep stable
322
+ // The generic "Axis" or anything else defaults to +Z (sketch normal)
323
+ return { axis: [0, 0, 1], at };
324
+ }
325
+ /**
326
+ * Resolve a Pad/Pocket profile link. Modern files use `Profile`; files saved
327
+ * by FreeCAD ≤ 0.19 store the sketch directly under `Sketch` (observed in
328
+ * PadTest.fcstd, ProgramVersion 0.14/0.17 era).
329
+ */
330
+ function profileLink(obj) {
331
+ return propLink(obj, 'Profile') ?? propLink(obj, 'Sketch');
332
+ }
333
+ /**
334
+ * Placement position (translation) of an object.
335
+ *
336
+ * @param obj - the FCStd object to read.
337
+ * @returns the (Px, Py, Pz) translation from its Placement, or (0,0,0) when absent.
338
+ */
339
+ export function placementPos(obj) {
340
+ // Property → <PropertyPlacement Px=... Py=... Pz=.../>
341
+ const pp = obj.properties.get('Placement')?.children[0];
342
+ if (!pp)
343
+ return [0, 0, 0];
344
+ return [
345
+ Number(pp.attributes['Px'] ?? 0),
346
+ Number(pp.attributes['Py'] ?? 0),
347
+ Number(pp.attributes['Pz'] ?? 0),
348
+ ];
349
+ }
350
+ /**
351
+ * A frozen `.brp` shape delivered through the container's `assets/` becomes an
352
+ * addressable Shape via `cad.import_brep` — the **platform** BREP-asset import
353
+ * op (`api/import-brep.ts`), which reads through the host asset resolver and
354
+ * returns a BREP-backed Shape the rest of the chain can consume.
355
+ *
356
+ * GOTCHA (2026-09-21, found while verifying ArchDetail): the shape-asset rounds
357
+ * used to emit a made-up `cad.import_shape`, which is **not** in the cad
358
+ * namespace. 42 of the 50 corpus products therefore parsed clean but could not
359
+ * RUN — `cliCheck` validates syntax and script-local references, never the
360
+ * callee's existence, so only a real `run --mode brep` exposes this.
361
+ *
362
+ * Contract details:
363
+ * - asset: the asset file name WITHOUT extension — that is the key rule of the
364
+ * documented directory mode of `FsAssetResolver` (`key = basename(file)`),
365
+ * which is how a container's `assets/` directory is exposed.
366
+ *
367
+ * C6 (non-solid first-class): `cad.import_brep` always imports with
368
+ * `allowNonSolid` (wire/face/shell are first-class). There is no `format`
369
+ * hint — the op goes straight to `loadBrep` on the OCCT kernel, which needs
370
+ * no format detection. Booleans / up-to targets that require a solid still
371
+ * fail at the **use site**, never at the import site.
372
+ *
373
+ * @param obj - the FCStd object whose frozen shape is being imported.
374
+ * @param assetFile - the `.brp` member name recorded on the object's Shape/SubShape property.
375
+ * @returns the `cad.import_brep` call binding `obj.name` to the imported geometry.
376
+ */
377
+ function shapeAssetCall(obj, assetFile) {
378
+ const asset = assetFile.replace(/^.*[/\\]/, '').replace(/\.brp$/i, '');
379
+ return {
380
+ out: obj.name, op: 'cad.import_brep', source: obj.name, inputs: [],
381
+ params: { asset },
382
+ };
383
+ }
384
+ /**
385
+ * M4 translate one object. `inputVar` maps a dependency object name to the
386
+ * variable holding its geometry (sketch contours or prior solid).
387
+ *
388
+ * `docObjects` (optional) is the full document object list — needed by the
389
+ * UpToFace datum-plane path to read the target plane's Placement (plan
390
+ * extrude-upto-face §4.3-C1). When absent, UpToFace keeps the explicit bake.
391
+ *
392
+ * @param obj - the FCStd object to translate.
393
+ * @param inputVar - resolves a dependency object name to the variable holding
394
+ * its geometry (sketch contours or prior solid).
395
+ * @param docObjects - the full document object list, needed by the UpToFace
396
+ * datum-plane path; optional.
397
+ * @param shapeCarriers - objects whose Shape is stored as a .brp member; optional.
398
+ * @param brokenShapeAssets - objects whose Shape `file` attribute points at a missing/empty member (explicit gap); optional.
399
+ * @param filletEdgesData - parsed PropertyFilletEdges binaries keyed by object name (Part::Chamfer/Fillet); optional.
400
+ * @returns the cad-op call plan, or an explicit bake/preserve verdict with reason.
401
+ */
402
+ export function translateObject(obj, inputVar, docObjects,
403
+ /** H7: names of objects whose Shape is stored as a .brp member (probed from the ZIP). */
404
+ shapeCarriers,
405
+ /** E4: objects whose Shape `file` attribute points at a missing/empty member. */
406
+ brokenShapeAssets,
407
+ /** P8: parsed PropertyFilletEdges binaries keyed by object name (Part::Chamfer/Fillet). */
408
+ filletEdgesData) {
409
+ // P1-1(参数载体):注入文档上下文,让 expressionBindingOf 能做
410
+ // <<Label>>.Alias 三跳解析(引用算术需要全文档找 Spreadsheet 数据源)。
411
+ if (docObjects)
412
+ docContext = docObjects;
413
+ // E4 (H12): a Shape/SubShape `file` attribute whose member is missing or
414
+ // zero-bytes in the archive is a BROKEN asset, not a shape-asset — surface
415
+ // it as an explicit convert-time gap instead of letting the object fall
416
+ // through to python-opaque (which would silently swallow the defect).
417
+ if (brokenShapeAssets?.has(obj.name)) {
418
+ return { kind: 'baked', reason: 'shape-asset-broken: frozen .brp member missing or empty' };
419
+ }
420
+ // H7 follow-up (Body-less CAM corpus, 2026-09-20): a SubShape property whose
421
+ // .brp member exists is the feature's own RESULT cache — the pocketed/
422
+ // filleted geometry is already a fact delivered via assets/. shape-asset
423
+ // beats an honest-but-useless dependency gap for Body-less files. Only
424
+ // SubShape qualifies (Pads also carry Shape in these files — they must keep
425
+ // the normal translation path).
426
+ if (shapeCarriers?.has(obj.name) && obj.properties.has('SubShape')) {
427
+ // The result cache is a real, addressable solid: downstream features
428
+ // (Fillet Base→Pocket, Cut Base→…) must resolve it as a variable, so the
429
+ // verdict emits a real load call instead of zero calls (hole_puzzle
430
+ // GOTCHA: zero-call objects got no codegen variable and consumers gapped
431
+ // with fillet-missing-base / cut-missing-dependency).
432
+ const assetFile = obj.properties.get('SubShape')?.children[0]?.attributes['file'] ?? `${obj.name}.SubShape.brp`;
433
+ return {
434
+ kind: 'translated',
435
+ calls: [shapeAssetCall(obj, assetFile)],
436
+ reason: 'shape-asset',
437
+ };
438
+ }
439
+ if (!isWhitelisted(obj.type)) {
440
+ // GOTCHA (EngineBlock corpus, 2026-09-20): Shape-asset evidence PRECEDES
441
+ // python-opaque. Draft circles carry Proxy (python evidence) AND a real
442
+ // Shape .brp member; python-opaque baked them silently and downstream
443
+ // Part::Extrusion gapped with extrusion-missing-base. Geometry is an
444
+ // existing fact — import it.
445
+ if (shapeCarriers?.has(obj.name)) {
446
+ const assetFile = shapeBrpFile(obj) ?? `${obj.name}.Shape.brp`;
447
+ return {
448
+ kind: 'translated',
449
+ calls: [shapeAssetCall(obj, assetFile)],
450
+ reason: 'shape-asset',
451
+ };
452
+ }
453
+ // H10: property-evidenced Python features bake legitimately (C4) —
454
+ // auditMapping renames this reason to `python-baked`. Everything else is
455
+ // a plain translation gap.
456
+ if (isPythonOpaque(obj))
457
+ return { kind: 'baked', reason: 'python-opaque' };
458
+ // H7 first cut: a Part::Feature is a pure Shape carrier (corpus probe:
459
+ // property surface is Shape [+ShapeMaterial] only; geometry lives in the
460
+ // ZIP's .brp member). With shape evidence there is nothing to translate —
461
+ // the geometry is delivered via assets/ (build-fai-zip M2.3 already copies
462
+ // it), so record `translated` with no cad calls. Without evidence it is an
463
+ // explicit gap, never a silent bake.
464
+ if (obj.type === 'Part::Feature') {
465
+ if (shapeCarriers?.has(obj.name))
466
+ return { kind: 'translated', calls: [], reason: 'shape-asset' };
467
+ return { kind: 'baked', reason: 'shape-asset-missing' };
468
+ }
469
+ return { kind: 'baked', reason: `type-not-whitelisted: ${obj.type}` };
470
+ }
471
+ /** Map FreeCAD Part::Sweep `Transition` (enum label or index) → cad.sweep transitionMode. */
472
+ function normalizeSweepTransition(raw) {
473
+ if (raw === undefined)
474
+ return undefined;
475
+ if (raw === 'RightAngle' || raw === '0')
476
+ return 'right';
477
+ if (raw === 'Transformed' || raw === '1')
478
+ return 'transformed';
479
+ if (raw === 'Round' || raw === '2')
480
+ return 'round';
481
+ return undefined;
482
+ }
483
+ const out = obj.name; // M5 renames to partN
484
+ switch (obj.type) {
485
+ case 'Part::Box': {
486
+ const l = propNum(obj, 'Length') ?? 0;
487
+ const w = propNum(obj, 'Width') ?? 0;
488
+ const h = propNum(obj, 'Height') ?? 0;
489
+ // FCStd Box: corner at Placement, extends +X/+Y/+Z
490
+ const [x, y, z] = placementPos(obj);
491
+ return {
492
+ kind: 'translated',
493
+ calls: [{
494
+ out, op: 'cad.box', source: obj.name, inputs: [],
495
+ params: { width: w, depth: l, height: h, at: [x, y, z], centered: false },
496
+ }],
497
+ };
498
+ }
499
+ case 'Part::Cylinder': {
500
+ const r = propNum(obj, 'Radius') ?? 0;
501
+ const h = propNum(obj, 'Height') ?? 0;
502
+ const [x, y, z] = placementPos(obj);
503
+ const angle = propNum(obj, 'Angle') ?? 360;
504
+ if (angle !== 360)
505
+ return { kind: 'baked', reason: 'cylinder-partial-angle' };
506
+ return {
507
+ kind: 'translated',
508
+ calls: [{
509
+ out, op: 'cad.cylinder', source: obj.name, inputs: [],
510
+ params: { radius: r, height: h, at: [x, y, z], centered: false },
511
+ }],
512
+ };
513
+ }
514
+ case 'Part::Compound': {
515
+ // M13.1 probe (ArchDetail.FCStd): members live in a `Links`
516
+ // PropertyLinkList; every corpus instance also stores a baked .brp,
517
+ // but translating the member group keeps the chain explicit.
518
+ const linksEl = obj.properties.get('Links')?.children[0];
519
+ const members = [];
520
+ for (const link of linksEl?.children ?? []) {
521
+ const v = link.attributes['value'];
522
+ if (v)
523
+ members.push(v);
524
+ }
525
+ const vars = members.map((m) => inputVar(m));
526
+ if (vars.length === 0 || vars.some((v) => v === undefined)) {
527
+ return { kind: 'baked', reason: 'compound-missing-members' };
528
+ }
529
+ // `Part::Compound` 是几何对象(`Part::Feature` 子类,带 Shape + Placement)。
530
+ // 用平台几何 compound(`cad.compound`,内核 `makeCompound`,持 OCCT 句柄,
531
+ // 可变换/可导出),不再借用 ../3d_editor 的结构分组 op `cad.group`。
532
+ // members 经 `params.members` 传递;`inputs` 仅作依赖登记(consumed / 变量重映射),
533
+ // 由 `noPositionalArgs` 保证不被 renderArgs 当作位置参数渲染。
534
+ return {
535
+ kind: 'translated',
536
+ calls: [{
537
+ out, op: 'cad.compound', source: obj.name, inputs: vars,
538
+ noPositionalArgs: true, params: { members: vars },
539
+ }],
540
+ };
541
+ }
542
+ case 'Part::Sphere': {
543
+ const r = propNum(obj, 'Radius');
544
+ if (r === undefined || r <= 0)
545
+ return { kind: 'baked', reason: 'sphere-missing-radius' };
546
+ const angle1 = propNum(obj, 'Angle1') ?? -90;
547
+ const angle2 = propNum(obj, 'Angle2') ?? 90;
548
+ const angle3 = propNum(obj, 'Angle3') ?? 360;
549
+ if (angle1 !== -90 || angle2 !== 90 || angle3 !== 360) {
550
+ return { kind: 'baked', reason: 'sphere-partial-angle' };
551
+ }
552
+ const [x, y, z] = placementPos(obj);
553
+ return {
554
+ kind: 'translated',
555
+ calls: [{
556
+ out, op: 'cad.sphere', source: obj.name, inputs: [],
557
+ params: { radius: r, at: [x, y, z] },
558
+ }],
559
+ };
560
+ }
561
+ case 'Part::Mirroring': {
562
+ // P5: mirror Source across the plane through Base with normal Normal.
563
+ // The result is the mirrored copy alone (FreeCAD does NOT fuse the
564
+ // original in Part::Mirroring — the corpus pairs it with explicit
565
+ // fusion features when needed), so this maps to `cad.mirror`, not
566
+ // `cad.mirrorJoin`.
567
+ const src = propLink(obj, 'Source');
568
+ const s = src ? inputVar(src) : undefined;
569
+ if (!s)
570
+ return { kind: 'baked', reason: 'mirroring-missing-source' };
571
+ const base = propVecXYZ(obj, 'Base') ?? [0, 0, 0];
572
+ const normalRaw = propVecXYZ(obj, 'Normal');
573
+ if (!normalRaw || Math.hypot(...normalRaw) <= 0) {
574
+ return { kind: 'baked', reason: 'mirroring-missing-normal' };
575
+ }
576
+ const normal = normalize3(normalRaw);
577
+ // FreeCAD mirrors across the plane through (Base + Placement translation)
578
+ // — Placement here is a pure translation in all corpus samples; the
579
+ // plane point is Base shifted by it.
580
+ const [px, py, pz] = placementPos(obj);
581
+ const at = [base[0] + px, base[1] + py, base[2] + pz];
582
+ return {
583
+ kind: 'translated',
584
+ calls: [{
585
+ out, op: 'cad.mirror', source: obj.name, inputs: [s],
586
+ noPositionalArgs: true, params: { normal, at },
587
+ }],
588
+ };
589
+ }
590
+ case 'Part::Cut': {
591
+ const base = propLink(obj, 'Base');
592
+ const tool = propLink(obj, 'Tool');
593
+ const b = base ? inputVar(base) : undefined;
594
+ const t = tool ? inputVar(tool) : undefined;
595
+ if (!b || !t)
596
+ return { kind: 'baked', reason: 'cut-missing-dependency' };
597
+ return {
598
+ kind: 'translated',
599
+ calls: [{ out, op: 'cad.subtract', source: obj.name, inputs: [b, t], params: {} }],
600
+ };
601
+ }
602
+ case 'Part::Fuse': {
603
+ // P7: same Base/Tool PropertyLink serialization as Part::Cut, but
604
+ // fuses instead of cutting.
605
+ const fuseBase = propLink(obj, 'Base');
606
+ const fuseTool = propLink(obj, 'Tool');
607
+ const fb = fuseBase ? inputVar(fuseBase) : undefined;
608
+ const ft = fuseTool ? inputVar(fuseTool) : undefined;
609
+ if (!fb || !ft)
610
+ return { kind: 'baked', reason: 'fuse-missing-dependency' };
611
+ return {
612
+ kind: 'translated',
613
+ calls: [{ out, op: 'cad.union', source: obj.name, inputs: [fb, ft], params: {} }],
614
+ };
615
+ }
616
+ case 'Part::MultiFuse': {
617
+ // <LinkList count="N"><Link value="A"/>...</LinkList>
618
+ const shapes = propLinkList(obj, 'Shapes');
619
+ const inputs = shapes.map(inputVar);
620
+ if (shapes.length < 2 || inputs.some((i) => i === undefined)) {
621
+ return { kind: 'baked', reason: 'multifuse-missing-dependency' };
622
+ }
623
+ return {
624
+ kind: 'translated',
625
+ calls: [{ out, op: 'cad.union', source: obj.name, inputs: inputs, params: {} }],
626
+ };
627
+ }
628
+ case 'PartDesign::Pad': {
629
+ const profile = profileLink(obj);
630
+ const len = propNum(obj, 'Length') ?? 0;
631
+ const reversed = propBool(obj, 'Reversed');
632
+ const midplane = propBool(obj, 'Midplane');
633
+ const profileVar = profile ? inputVar(profile) : undefined;
634
+ if (!profileVar)
635
+ return { kind: 'baked', reason: 'pad-missing-profile' };
636
+ // M11.2: a non-constant expression binding (cross-object reference /
637
+ // identifier arithmetic) leaves the length unknown — explicit bake,
638
+ // never estimate (plan §12).
639
+ if (hasNonConstantBinding(obj, 'Length')) {
640
+ return { kind: 'baked', reason: 'pad-length-expression-non-constant' };
641
+ }
642
+ // M9.1/M9.2: Type-driven semantics — no silent Length fallback.
643
+ const ftype = featureTypeOf(obj, 'pad');
644
+ if (ftype === 'TwoLengths') {
645
+ const len2 = propNum(obj, 'Length2') ?? 0;
646
+ // TwoLengths: Length forward + Length2 backward, fused. Named
647
+ // intermediate vars so mapping/debug can locate each segment.
648
+ const pos = `${out}__pos`;
649
+ const neg = `${out}__neg`;
650
+ const calls = [
651
+ { out: pos, op: 'cad.extrude', source: obj.name, inputs: [profileVar], literals: [[0, 0, len]], params: {} },
652
+ { out: neg, op: 'cad.extrude', source: obj.name, inputs: [profileVar], literals: [[0, 0, -len2]], params: {} },
653
+ { out, op: 'cad.union', source: obj.name, inputs: [pos, neg], params: {} },
654
+ ];
655
+ return { kind: 'translated', calls };
656
+ }
657
+ if (ftype === 'UpToFace') {
658
+ // extrude-upto-face plan §4.3-C1: when the target is a datum plane
659
+ // (PartDesign::Plane — an infinite plane, not a solid face), the
660
+ // extrude length is the exact signed distance from the profile plane
661
+ // to the datum plane. Zero bake, no faceRef needed.
662
+ const upTo = propLinkSub(obj, 'UpToFace');
663
+ if (upTo && docObjects) {
664
+ const target = docObjects.find((o) => o.name === upTo.obj);
665
+ // C1 (extrude-upto-face §4.3-C1): datum plane (infinite plane) →
666
+ // exact signed distance → cad.extrude({ length }). No faceRef needed.
667
+ if (target && target.type === 'PartDesign::Plane') {
668
+ const pl = placementOf(target);
669
+ // datum plane normal = placement R * local +Z
670
+ const m = quatToMatrix(pl.q);
671
+ const normal = [m[2], m[5], m[8]];
672
+ // sketch normal (the extrude direction); the profile sketch lies on
673
+ // its own placement, and the feature extrudes along it.
674
+ const skPl = placementOf(docObjects.find((o) => o.name === (profile ?? '')) ?? target);
675
+ const skM = quatToMatrix(skPl.q);
676
+ const dir = [skM[2], skM[5], skM[8]];
677
+ // GOTCHA (probe-upto-padtest-verify.ts, PadTest Pad001): the datum
678
+ // plane is an arbitrary plane, NOT axis-aligned to the extrude
679
+ // direction. The signed distance to reach it along `dir` is
680
+ // t = ((pl.p - skPl.p) · n) / (dir · n)
681
+ // where n is the datum plane normal — NOT the naive (Δp · dir),
682
+ // which only works when n ∥ dir (axis-aligned). The naive form
683
+ // yields −50 for PadTest while the true distance is +10; the
684
+ // corrected form matches FreeCAD's Tip bbox exactly (diag 156.84).
685
+ const denom = dir[0] * normal[0] + dir[1] * normal[1] + dir[2] * normal[2];
686
+ // plane parallel to the extrude direction → no finite intersection
687
+ if (!Number.isFinite(denom) || Math.abs(denom) < 1e-9) {
688
+ return { kind: 'baked', reason: 'uptoface-datum-plane-parallel' };
689
+ }
690
+ const dpn = (pl.p[0] - skPl.p[0]) * normal[0] +
691
+ (pl.p[1] - skPl.p[1]) * normal[1] +
692
+ (pl.p[2] - skPl.p[2]) * normal[2];
693
+ const t = dpn / denom;
694
+ if (Number.isFinite(t) && Math.abs(t) > 1e-9) {
695
+ // GOTCHA (PadTest V6 residual, relErr 3.02%): the datum plane may
696
+ // be TILTED relative to the extrude direction (Pad001: datum
697
+ // normal (−0.038·…) not parallel to the sketch normal). A fixed
698
+ // length `signed` gives a FLAT top; FreeCAD's Pad reaches the
699
+ // PLANE, producing a slanted top (truth AddShape 4860.42 vs flat
700
+ // disc 1874.83). Emit an explicit plane target instead and let
701
+ // the kernel's half-space intersection produce the slanted cut.
702
+ // The extrude runs in sketch-local coords, so transform the
703
+ // global plane into the sketch frame: p_local = R⁻¹(p_g − sk.p),
704
+ // n_local = R⁻¹(n_g) (R⁻¹ = Rᵀ).
705
+ const inv = [0, 1, 2].map((c) => [
706
+ skM[c], skM[3 + c], skM[6 + c],
707
+ ]);
708
+ const d = [
709
+ pl.p[0] - skPl.p[0], pl.p[1] - skPl.p[1], pl.p[2] - skPl.p[2],
710
+ ];
711
+ const ptLocal = [
712
+ inv[0][0] * d[0] + inv[0][1] * d[1] + inv[0][2] * d[2],
713
+ inv[1][0] * d[0] + inv[1][1] * d[1] + inv[1][2] * d[2],
714
+ inv[2][0] * d[0] + inv[2][1] * d[1] + inv[2][2] * d[2],
715
+ ];
716
+ const nLocal = [
717
+ inv[0][0] * normal[0] + inv[0][1] * normal[1] + inv[0][2] * normal[2],
718
+ inv[1][0] * normal[0] + inv[1][1] * normal[1] + inv[1][2] * normal[2],
719
+ inv[2][0] * normal[0] + inv[2][1] * normal[1] + inv[2][2] * normal[2],
720
+ ];
721
+ return {
722
+ kind: 'translated',
723
+ reason: 'uptoface-via-datum-plane-distance',
724
+ calls: [{
725
+ out, op: 'cad.extrude', source: obj.name, inputs: [profileVar],
726
+ params: { upTo: { plane: { point: ptLocal, normal: nLocal } } },
727
+ }],
728
+ };
729
+ }
730
+ return { kind: 'baked', reason: 'uptoface-datum-plane-degenerate-distance' };
731
+ }
732
+ // C2.2 (extrude-upto-face §4.3-C2 point 2): solid-feature target →
733
+ // reference its face by ordinal via `cad.extrude({ upTo:
734
+ // cad.faceRef(targetVar, N) })`. faceRef's ordinal is calibrated to
735
+ // match FreeCAD's `FaceN` (R-A, same TopExp::MapShapes + IndexedMap
736
+ // enumeration as edgeRef); the runtime naming layer resolves the ref
737
+ // against the live target shape, so it enters the IR as a JsExpr.
738
+ if (target) {
739
+ const targetVar = inputVar(upTo.obj);
740
+ if (targetVar) {
741
+ const faceN = parseFaceSub(upTo.subs);
742
+ if (faceN !== undefined) {
743
+ return {
744
+ kind: 'translated',
745
+ reason: 'uptoface-via-faceRef',
746
+ calls: [{
747
+ out, op: 'cad.extrude', source: obj.name, inputs: [profileVar],
748
+ params: { upTo: jsExpr(`cad.faceRef(${targetVar}, ${faceN})`) },
749
+ }],
750
+ };
751
+ }
752
+ // sub present but not a plain FaceN reference → explicit bake
753
+ return { kind: 'baked', reason: 'uptoface-sub-unparseable' };
754
+ }
755
+ }
756
+ }
757
+ return { kind: 'baked', reason: 'uptoface-solid-face-unsupported' };
758
+ }
759
+ if (ftype === 'UpToLast' || ftype === 'UpToFirst') {
760
+ // plan §4.3-C2: UpToLast/UpToFirst extrude to the far/near face of the
761
+ // support (BaseFeature) via `cad.extrude({ upTo: 'last' | 'first' })`
762
+ // (up-to lives on the platform op cad.extrude, never on fai_extrude).
763
+ // The kernel up-to does the truncation; baseFeature must be resolvable
764
+ // or we bake explicitly — no silent bbox-derived length guess.
765
+ const base = propLink(obj, 'BaseFeature');
766
+ const baseVar = base ? inputVar(base) : undefined;
767
+ if (!baseVar)
768
+ return { kind: 'baked', reason: 'pad-upTo-missing-base' };
769
+ const upTo = ftype === 'UpToLast' ? 'last' : 'first';
770
+ return {
771
+ kind: 'translated',
772
+ reason: `pad-${ftype}-via-baseFeature`,
773
+ calls: [{
774
+ out, op: 'cad.extrude', source: obj.name, inputs: [profileVar],
775
+ params: { upTo, baseFeature: jsExpr(baseVar) },
776
+ }],
777
+ };
778
+ }
779
+ if (ftype !== 'Length') {
780
+ // anything still non-Length (e.g. 'unknown') → explicit bake, never guess
781
+ return { kind: 'baked', reason: `pad-type-${ftype}-unsupported` };
782
+ }
783
+ // cad.extrude extrudes the sketch face into a prism along +Z (the sketch
784
+ // normal in body-local frame); length sign encodes direction.
785
+ if (midplane) {
786
+ // symmetric about the sketch plane: two half-prisms fused
787
+ const pos = `${out}__pos`;
788
+ const neg = `${out}__neg`;
789
+ const calls = [
790
+ { out: pos, op: 'cad.extrude', source: obj.name, inputs: [profileVar], literals: [[0, 0, len / 2]], params: {} },
791
+ { out: neg, op: 'cad.extrude', source: obj.name, inputs: [profileVar], literals: [[0, 0, -len / 2]], params: {} },
792
+ { out, op: 'cad.union', source: obj.name, inputs: [pos, neg], params: {} },
793
+ ];
794
+ return { kind: 'translated', calls };
795
+ }
796
+ const signed = reversed ? -len : len;
797
+ return {
798
+ kind: 'translated',
799
+ calls: [{ out, op: 'cad.extrude', source: obj.name, inputs: [profileVar], literals: [[0, 0, signed]], params: {} }],
800
+ };
801
+ }
802
+ case 'PartDesign::Pocket': {
803
+ const profile = profileLink(obj);
804
+ const len = propNum(obj, 'Length') ?? 0;
805
+ const reversed = propBool(obj, 'Reversed');
806
+ const midplane = propBool(obj, 'Midplane');
807
+ const base = propLink(obj, 'BaseFeature');
808
+ const profileVar = profile ? inputVar(profile) : undefined;
809
+ // GOTCHA (hole_puzzle corpus, 2026-09-20): FreeCAD 0.20+ PartDesign
810
+ // files routinely OMIT BaseFeature on interior features — the base is
811
+ // implied by the Body's feature order (chain head). A MISSING property
812
+ // is "no explicit base" → emit the subtract with the BODY_CHAIN_BASE
813
+ // marker; codegen retargets it at the chain head when folding. Only an
814
+ // EXPLICIT base that fails to resolve is a dependency gap.
815
+ const baseVar = base ? inputVar(base) : BODY_CHAIN_BASE;
816
+ if (!profileVar || !baseVar)
817
+ return { kind: 'baked', reason: 'pocket-missing-dependency' };
818
+ if (hasNonConstantBinding(obj, 'Length')) {
819
+ return { kind: 'baked', reason: 'pocket-length-expression-non-constant' };
820
+ }
821
+ // M9.1/M9.2/M9.3: Type-driven semantics — explicit bake for anything
822
+ // beyond the supported set (no silent downgrade).
823
+ const ftype = featureTypeOf(obj, 'pocket');
824
+ if (ftype === 'UpToFace') {
825
+ // C2.3 (extrude-upto-face §4.3-C2 point 4): Pocket UpToFace — same
826
+ // datum-plane path as Pad (plane target in sketch-local frame); the
827
+ // cut direction is handled by the kernel's auto-orientation toward
828
+ // the plane (GOTCHA: Pocket cuts INTO the material, the plane lies
829
+ // on the far side, and the kernel flips the extrude direction).
830
+ const upTo = propLinkSub(obj, 'UpToFace');
831
+ if (upTo && docObjects) {
832
+ const target = docObjects.find((o) => o.name === upTo.obj);
833
+ if (target && target.type === 'PartDesign::Plane') {
834
+ const pl = placementOf(target);
835
+ const m = quatToMatrix(pl.q);
836
+ const normal = [m[2], m[5], m[8]];
837
+ const skPl = placementOf(docObjects.find((o) => o.name === (profile ?? '')) ?? target);
838
+ const skM = quatToMatrix(skPl.q);
839
+ const dir = [skM[2], skM[5], skM[8]];
840
+ const denom = dir[0] * normal[0] + dir[1] * normal[1] + dir[2] * normal[2];
841
+ if (!Number.isFinite(denom) || Math.abs(denom) < 1e-9) {
842
+ return { kind: 'baked', reason: 'pocket-uptoface-datum-plane-parallel' };
843
+ }
844
+ // plane → sketch-local frame (p_local = R⁻¹(p_g − sk.p), n_local = R⁻¹ n)
845
+ const inv = [0, 1, 2].map((c) => [skM[c], skM[3 + c], skM[6 + c]]);
846
+ const d = [pl.p[0] - skPl.p[0], pl.p[1] - skPl.p[1], pl.p[2] - skPl.p[2]];
847
+ const ptLocal = [
848
+ inv[0][0] * d[0] + inv[0][1] * d[1] + inv[0][2] * d[2],
849
+ inv[1][0] * d[0] + inv[1][1] * d[1] + inv[1][2] * d[2],
850
+ inv[2][0] * d[0] + inv[2][1] * d[1] + inv[2][2] * d[2],
851
+ ];
852
+ const nLocal = [
853
+ inv[0][0] * normal[0] + inv[0][1] * normal[1] + inv[0][2] * normal[2],
854
+ inv[1][0] * normal[0] + inv[1][1] * normal[1] + inv[1][2] * normal[2],
855
+ inv[2][0] * normal[0] + inv[2][1] * normal[1] + inv[2][2] * normal[2],
856
+ ];
857
+ const cutVar = `${out}_cut`;
858
+ const calls = [
859
+ {
860
+ out: cutVar, op: 'cad.extrude', source: obj.name, inputs: [profileVar],
861
+ params: { upTo: { plane: { point: ptLocal, normal: nLocal } } },
862
+ },
863
+ { out, op: 'cad.subtract', source: obj.name, inputs: [baseVar, cutVar], params: {} },
864
+ ];
865
+ return { kind: 'translated', reason: 'pocket-uptoface-via-datum-plane', calls };
866
+ }
867
+ return { kind: 'baked', reason: 'pocket-uptoface-solid-face-unsupported' };
868
+ }
869
+ return { kind: 'baked', reason: 'pocket-uptoface-sub-unparseable' };
870
+ }
871
+ if (ftype === 'UpToFirst') {
872
+ // C2.3: Pocket UpToFirst — cut prism to the support's NEAR face along
873
+ // the cut direction; the kernel truncates the prism against the
874
+ // baseFeature (chain head), then the result is subtracted.
875
+ const baseVarUp = baseVar;
876
+ const cutVar = `${out}_cut`;
877
+ const calls = [
878
+ {
879
+ out: cutVar, op: 'cad.extrude', source: obj.name, inputs: [profileVar],
880
+ params: { upTo: 'first', baseFeature: jsExpr(baseVarUp) },
881
+ },
882
+ { out, op: 'cad.subtract', source: obj.name, inputs: [baseVarUp, cutVar], params: {} },
883
+ ];
884
+ return { kind: 'translated', reason: 'pocket-uptofirst-via-baseFeature', calls };
885
+ }
886
+ if (ftype !== 'Length' && ftype !== 'TwoLengths' && ftype !== 'ThroughAll') {
887
+ return { kind: 'baked', reason: `pocket-type-${ftype}-unsupported` };
888
+ }
889
+ // P1-1b (2026-09-23): Pocket Midplane — symmetric cut prism about the
890
+ // sketch plane (same construction as the Pad midplane branch: two
891
+ // half-prisms fused, then subtracted). Direction sign is irrelevant
892
+ // (symmetric); ThroughAll keeps its far-beyond-extent depth.
893
+ if (midplane) {
894
+ const THROUGH_ALL_DEPTH = 1e6;
895
+ const depth = ftype === 'ThroughAll' ? THROUGH_ALL_DEPTH : len;
896
+ const half = depth / 2;
897
+ const pos = `${out}_cut_pos`;
898
+ const neg = `${out}_cut_neg`;
899
+ const cutVar = `${out}_cut`;
900
+ const calls = [
901
+ { out: pos, op: 'cad.extrude', source: obj.name, inputs: [profileVar], literals: [[0, 0, half]], params: {} },
902
+ { out: neg, op: 'cad.extrude', source: obj.name, inputs: [profileVar], literals: [[0, 0, -half]], params: {} },
903
+ { out: cutVar, op: 'cad.union', source: obj.name, inputs: [pos, neg], params: {} },
904
+ { out, op: 'cad.subtract', source: obj.name, inputs: [baseVar, cutVar], params: {} },
905
+ ];
906
+ return { kind: 'translated', calls };
907
+ }
908
+ // Pocket cuts INTO the material: extrude the profile opposite the normal
909
+ // (or along it when Reversed), then subtract from base.
910
+ // ThroughAll (hole_puzzle corpus, 2026-09-20): FreeCAD truncates the
911
+ // prism against the base solid, so a depth far beyond any realistic
912
+ // base extent is safe — the subtract is exact either way.
913
+ const THROUGH_ALL_DEPTH = 1e6;
914
+ const depth = ftype === 'ThroughAll' ? THROUGH_ALL_DEPTH : len;
915
+ const signed = reversed ? depth : -depth;
916
+ const cutVar = `${out}_cut`;
917
+ const calls = [{
918
+ out: cutVar, op: 'cad.extrude', source: obj.name, inputs: [profileVar], literals: [[0, 0, signed]], params: {},
919
+ }];
920
+ calls.push({ out, op: 'cad.subtract', source: obj.name, inputs: [baseVar, cutVar], params: {} });
921
+ return { kind: 'translated', calls };
922
+ }
923
+ case 'Part::Extrusion': {
924
+ const base = propLink(obj, 'Base');
925
+ const baseVar = base ? inputVar(base) : undefined;
926
+ if (!baseVar)
927
+ return { kind: 'baked', reason: 'extrusion-missing-base' };
928
+ const dir = propVecXYZ(obj, 'Dir') ?? propVec(obj, 'Dir') ?? [0, 0, 1];
929
+ // FreeCAD 0.20+ serializes the flag as `Reversed`; older files used
930
+ // `Reverse`. Accept both.
931
+ const reversed = propBool(obj, 'Reversed') || propBool(obj, 'Reverse');
932
+ // E4 (2026-09-23): Part::Extrusion serializes in three shapes. New
933
+ // format: LengthFwd/LengthRev (unit Dir). Old format: only Dir, whose
934
+ // magnitude IS the extrusion length. Legacy: Length + Dir. The previous
935
+ // code only knew the legacy shape → len=0 → E_EXTRUDE_ZERO_VECTOR on
936
+ // 918 corpus runs.
937
+ const lengthFwd = propNum(obj, 'LengthFwd');
938
+ const lengthRev = propNum(obj, 'LengthRev');
939
+ const taperAngle = propNum(obj, 'TaperAngle') ?? 0;
940
+ if (taperAngle !== 0) {
941
+ // No-heuristic-fallback: silently ignoring a taper would produce wrong
942
+ // geometry. Bake with an explicit reason instead.
943
+ return { kind: 'baked', reason: 'extrusion-taper-unsupported' };
944
+ }
945
+ const unitDir = normalize3(dir);
946
+ const calls = [];
947
+ const emitExtrude = (outName, fwdLen, revLen) => {
948
+ if (fwdLen > 0) {
949
+ calls.push({
950
+ out: revLen > 0 ? `${outName}_fwd` : outName,
951
+ op: 'cad.extrude', source: obj.name, inputs: [baseVar],
952
+ literals: [[unitDir[0] * fwdLen, unitDir[1] * fwdLen, unitDir[2] * fwdLen]], params: {},
953
+ });
954
+ }
955
+ if (revLen > 0) {
956
+ // `|| 0` normalizes -0 to +0 (JSON/对拍 noise otherwise).
957
+ calls.push({
958
+ out: fwdLen > 0 ? `${outName}_rev` : outName,
959
+ op: 'cad.extrude', source: obj.name, inputs: [baseVar],
960
+ literals: [[(-unitDir[0] * revLen) || 0, (-unitDir[1] * revLen) || 0, (-unitDir[2] * revLen) || 0]], params: {},
961
+ });
962
+ }
963
+ };
964
+ if (lengthFwd !== undefined || lengthRev !== undefined) {
965
+ const symmetric = propBool(obj, 'Symmetric');
966
+ const fwd = lengthFwd ?? 0;
967
+ const revRaw = lengthRev ?? 0;
968
+ // FreeCAD semantics: Symmetric extrudes LengthFwd on BOTH sides;
969
+ // Reversed swaps the fwd/rev sides (same magnitudes).
970
+ const fwdLen = symmetric ? fwd : (reversed ? revRaw : fwd);
971
+ const revLen = symmetric ? fwd : (reversed ? fwd : revRaw);
972
+ if (fwdLen > 0 && revLen > 0) {
973
+ emitExtrude(out, fwdLen, revLen);
974
+ calls.push({ out, op: 'cad.union', source: obj.name, inputs: [`${out}_fwd`, `${out}_rev`], params: {} });
975
+ }
976
+ else {
977
+ emitExtrude(out, fwdLen, revLen);
978
+ }
979
+ if (calls.length === 0)
980
+ return { kind: 'baked', reason: 'extrusion-zero-length' };
981
+ return { kind: 'translated', calls };
982
+ }
983
+ const legacyLen = propNum(obj, 'Length');
984
+ if (legacyLen !== undefined) {
985
+ // Legacy shape: Length + unit Dir.
986
+ const s = reversed ? -1 : 1;
987
+ return {
988
+ kind: 'translated',
989
+ calls: [{
990
+ out, op: 'cad.extrude', source: obj.name, inputs: [baseVar],
991
+ literals: [[s * dir[0] * legacyLen, s * dir[1] * legacyLen, s * dir[2] * legacyLen]], params: {},
992
+ }],
993
+ };
994
+ }
995
+ // Old format: |Dir| IS the extrusion length; Dir is the vector.
996
+ const mag = Math.hypot(dir[0], dir[1], dir[2]);
997
+ if (mag <= 0)
998
+ return { kind: 'baked', reason: 'extrusion-zero-length' };
999
+ return {
1000
+ kind: 'translated',
1001
+ calls: [{
1002
+ out, op: 'cad.extrude', source: obj.name, inputs: [baseVar],
1003
+ literals: [reversed ? [-dir[0], -dir[1], -dir[2]] : dir], params: {},
1004
+ }],
1005
+ };
1006
+ }
1007
+ case 'Part::Revolution': {
1008
+ // P6: Part-workbench revolve — Source profile + axis given DIRECTLY as
1009
+ // Base/Axis PropertyVector (GOTCHA: valueX/Y/Z child-element form, NOT
1010
+ // the value="x y z" attribute form propVec reads; PartDesign::Revolution
1011
+ // instead stores a ReferenceAxis string — different serialization, so
1012
+ // this is a separate branch, not a shared one).
1013
+ const revSrc = propLink(obj, 'Source');
1014
+ const revVar = revSrc ? inputVar(revSrc) : undefined;
1015
+ if (!revVar) {
1016
+ return { kind: 'baked', reason: revSrc ? `part-revolution-source-baked-upstream:${revSrc}` : 'part-revolution-missing-source' };
1017
+ }
1018
+ const axisRaw = propVecXYZ(obj, 'Axis');
1019
+ if (!axisRaw || Math.hypot(...axisRaw) <= 0) {
1020
+ return { kind: 'baked', reason: 'part-revolution-missing-axis' };
1021
+ }
1022
+ const axis = normalize3(axisRaw);
1023
+ const base = propVecXYZ(obj, 'Base') ?? [0, 0, 0];
1024
+ const [rpx, rpy, rpz] = placementPos(obj);
1025
+ const at = [base[0] + rpx, base[1] + rpy, base[2] + rpz];
1026
+ const revAngleDeg = propNum(obj, 'Angle') ?? 360;
1027
+ if (revAngleDeg <= 0 || revAngleDeg > 360) {
1028
+ return { kind: 'baked', reason: 'part-revolution-angle-out-of-range' };
1029
+ }
1030
+ const revAngle = (revAngleDeg * Math.PI) / 180;
1031
+ if (propStr(obj, 'Symmetric') === 'true') {
1032
+ return { kind: 'baked', reason: 'part-revolution-symmetric-unsupported' };
1033
+ }
1034
+ return {
1035
+ kind: 'translated',
1036
+ calls: [{
1037
+ out, op: 'cad.revolve', source: obj.name, inputs: [revVar],
1038
+ noPositionalArgs: true, params: { axis, at, angle: revAngle },
1039
+ }],
1040
+ };
1041
+ }
1042
+ case 'PartDesign::Revolution': {
1043
+ const profile = profileLink(obj);
1044
+ const profileVar = profile ? inputVar(profile) : undefined;
1045
+ if (!profileVar) {
1046
+ // P2-1 (2026-09-24, Mannequin_mp): a `revolution-missing-profile`
1047
+ // cascade lie — 13 Revolutions had a VALID Profile link (e.g.
1048
+ // Revolution033 → Sketch061) whose target sketch was baked upstream
1049
+ // (unsupported-geometry), so inputVar resolved undefined. Distinguish
1050
+ // "no link at all" from "link exists but upstream not translated".
1051
+ return { kind: 'baked', reason: profile ? `revolution-profile-baked-upstream:${profile}` : 'revolution-missing-profile' };
1052
+ }
1053
+ const angleDeg = propNum(obj, 'Angle') ?? 360;
1054
+ const angle = (angleDeg * Math.PI) / 180;
1055
+ const axisInfo = parseReferenceAxis(propStr(obj, 'ReferenceAxis'));
1056
+ if (!axisInfo)
1057
+ return { kind: 'baked', reason: 'revolution-edge-axis-unsupported' };
1058
+ return {
1059
+ kind: 'translated',
1060
+ calls: [{
1061
+ out, op: 'cad.revolve', source: obj.name, inputs: [profileVar],
1062
+ params: { axis: axisInfo.axis, at: axisInfo.at, angle },
1063
+ }],
1064
+ };
1065
+ }
1066
+ case 'PartDesign::Groove': {
1067
+ // P2-2 (2026-09-24): Groove = Revolution + subtract — revolve the
1068
+ // profile around the axis, then cut it from the base feature. Same
1069
+ // Profile/ReferenceAxis/Angle serialization as Revolution.
1070
+ const grooveProfile = profileLink(obj);
1071
+ const grooveProfileVar = grooveProfile ? inputVar(grooveProfile) : undefined;
1072
+ if (!grooveProfileVar) {
1073
+ return {
1074
+ kind: 'baked',
1075
+ reason: grooveProfile ? `groove-profile-baked-upstream:${grooveProfile}` : 'groove-missing-profile',
1076
+ };
1077
+ }
1078
+ const baseVar = inputVar(propLink(obj, 'BaseFeature') ?? '');
1079
+ if (!baseVar)
1080
+ return { kind: 'baked', reason: 'groove-missing-base' };
1081
+ const gAngleDeg = propNum(obj, 'Angle') ?? 360;
1082
+ const gAngle = (gAngleDeg * Math.PI) / 180;
1083
+ const gAxis = parseReferenceAxis(propStr(obj, 'ReferenceAxis'));
1084
+ if (!gAxis)
1085
+ return { kind: 'baked', reason: 'groove-edge-axis-unsupported' };
1086
+ const grooveVar = `${out}_groove`;
1087
+ return {
1088
+ kind: 'translated',
1089
+ calls: [
1090
+ {
1091
+ out: grooveVar, op: 'cad.revolve', source: obj.name, inputs: [grooveProfileVar],
1092
+ params: { axis: gAxis.axis, at: gAxis.at, angle: gAngle },
1093
+ },
1094
+ { out, op: 'cad.subtract', source: obj.name, inputs: [baseVar, grooveVar], params: {} },
1095
+ ],
1096
+ };
1097
+ }
1098
+ case 'PartDesign::LinearPattern': {
1099
+ // P3-1 (2026-09-23): FreeCAD serializes Transformed features with the
1100
+ // patterned features in `Originals` (PropertyLinkList); `Source` only
1101
+ // exists on some versions. Read Source first, then fall back to
1102
+ // Originals[0] (multi-original → fuse the patterned copies below).
1103
+ const source = propLink(obj, 'Source') ?? propLinkList(obj, 'Originals')[0];
1104
+ const originals = source ? [source] : [];
1105
+ const sourceVar = originals.length > 0 ? inputVar(originals[0]) : undefined;
1106
+ if (!sourceVar)
1107
+ return { kind: 'baked', reason: 'linear-pattern-missing-source' };
1108
+ const dirInfo = parseReferenceAxis(propStr(obj, 'Direction'));
1109
+ if (!dirInfo)
1110
+ return { kind: 'baked', reason: 'linear-pattern-edge-dir-unsupported' };
1111
+ const occ = Math.max(2, Math.round(propNum(obj, 'Occurrences') ?? 2));
1112
+ const length = propNum(obj, 'Length') ?? 0;
1113
+ const spacing = occ > 1 ? length / (occ - 1) : 0;
1114
+ if (originals.length === 1) {
1115
+ return {
1116
+ kind: 'translated',
1117
+ calls: [{
1118
+ out, op: 'cad.linearPattern', source: obj.name, inputs: [sourceVar],
1119
+ literals: [dirInfo.axis, occ, spacing], params: {},
1120
+ }],
1121
+ };
1122
+ }
1123
+ // Multi-original: pattern each, then fuse.
1124
+ const calls = originals.map((o, i) => {
1125
+ const v = inputVar(o);
1126
+ if (!v)
1127
+ return null;
1128
+ return {
1129
+ out: i === 0 ? `${out}_p0` : `${out}_p${i}`, op: 'cad.linearPattern', source: obj.name, inputs: [v],
1130
+ literals: [dirInfo.axis, occ, spacing], params: {},
1131
+ };
1132
+ }).filter((c) => c !== null);
1133
+ for (let i = 1; i < calls.length; i++) {
1134
+ calls.push({
1135
+ out: i === calls.length - 1 ? out : `${out}_u${i}`,
1136
+ op: 'cad.union', source: obj.name,
1137
+ inputs: [i === 1 ? calls[0].out : `${out}_u${i - 1}`, calls[i].out], params: {},
1138
+ });
1139
+ }
1140
+ return { kind: 'translated', calls };
1141
+ }
1142
+ case 'PartDesign::PolarPattern': {
1143
+ const sourcePolar = propLink(obj, 'Source') ?? propLinkList(obj, 'Originals')[0];
1144
+ const sourceVar = sourcePolar ? inputVar(sourcePolar) : undefined;
1145
+ if (!sourceVar)
1146
+ return { kind: 'baked', reason: 'polar-pattern-missing-source' };
1147
+ const axisInfo = parseReferenceAxis(propStr(obj, 'Axis'));
1148
+ if (!axisInfo)
1149
+ return { kind: 'baked', reason: 'polar-pattern-edge-axis-unsupported' };
1150
+ const occ = Math.max(2, Math.round(propNum(obj, 'Occurrences') ?? 2));
1151
+ const angle = propNum(obj, 'Angle') ?? 360;
1152
+ return {
1153
+ kind: 'translated',
1154
+ calls: [{
1155
+ out, op: 'cad.circularPattern', source: obj.name, inputs: [sourceVar],
1156
+ literals: [axisInfo.axis, occ, angle], params: {},
1157
+ }],
1158
+ };
1159
+ }
1160
+ case 'PartDesign::Fillet': {
1161
+ const base = propLinkSub(obj, 'Base');
1162
+ const baseVar = base ? inputVar(base.obj) : undefined;
1163
+ if (!baseVar)
1164
+ return { kind: 'baked', reason: 'fillet-missing-base' };
1165
+ if (propBool(obj, 'UseAllEdges'))
1166
+ return { kind: 'baked', reason: 'fillet-all-edges-unsupported' };
1167
+ if (!base || base.subs.length === 0)
1168
+ return { kind: 'baked', reason: 'fillet-no-edges' };
1169
+ const ordinals = parseEdgeSubs(base.subs);
1170
+ if (!ordinals)
1171
+ return { kind: 'baked', reason: 'fillet-non-edge-sub' };
1172
+ const radius = propNum(obj, 'Radius');
1173
+ if (radius === undefined || !(radius > 0))
1174
+ return { kind: 'baked', reason: 'fillet-bad-radius' };
1175
+ return {
1176
+ kind: 'translated',
1177
+ calls: [{
1178
+ out, op: 'cad.fillet', source: obj.name, inputs: [baseVar],
1179
+ params: { edges: edgeRefArgs(baseVar, ordinals), radius },
1180
+ }],
1181
+ };
1182
+ }
1183
+ case 'PartDesign::Chamfer': {
1184
+ const base = propLinkSub(obj, 'Base');
1185
+ const baseVar = base ? inputVar(base.obj) : undefined;
1186
+ if (!baseVar)
1187
+ return { kind: 'baked', reason: 'chamfer-missing-base' };
1188
+ if (propBool(obj, 'UseAllEdges'))
1189
+ return { kind: 'baked', reason: 'chamfer-all-edges-unsupported' };
1190
+ if (!base || base.subs.length === 0)
1191
+ return { kind: 'baked', reason: 'chamfer-no-edges' };
1192
+ const ordinals = parseEdgeSubs(base.subs);
1193
+ if (!ordinals)
1194
+ return { kind: 'baked', reason: 'chamfer-non-edge-sub' };
1195
+ const edges = edgeRefArgs(baseVar, ordinals);
1196
+ // ChamferType enum (FeatureChamfer.cpp:55): 0 "Equal distance" (the
1197
+ // default when the property is absent, i.e. files predating it),
1198
+ // 1 "Two distances", 2 "Distance and Angle".
1199
+ const type = Math.round(propNum(obj, 'ChamferType') ?? 0);
1200
+ const size = propNum(obj, 'Size');
1201
+ if (type === 1) {
1202
+ const size2 = propNum(obj, 'Size2');
1203
+ if (size === undefined || !(size > 0) || size2 === undefined || !(size2 > 0)) {
1204
+ return { kind: 'baked', reason: 'chamfer-bad-two-distances' };
1205
+ }
1206
+ return {
1207
+ kind: 'translated',
1208
+ calls: [{
1209
+ out, op: 'cad.chamfer', source: obj.name, inputs: [baseVar],
1210
+ params: { edges, type: 'twoDistances', width1: size, width2: size2 },
1211
+ }],
1212
+ };
1213
+ }
1214
+ if (type === 2) {
1215
+ // FreeCAD's Angle is degrees, range 0–180 (floatAngle); cad.chamfer
1216
+ // accepts degrees in the open interval (0, 90) only.
1217
+ const angle = propNum(obj, 'Angle');
1218
+ if (size === undefined || !(size > 0) || angle === undefined || !(angle > 0 && angle < 90)) {
1219
+ return { kind: 'baked', reason: 'chamfer-bad-distance-angle' };
1220
+ }
1221
+ return {
1222
+ kind: 'translated',
1223
+ calls: [{
1224
+ out, op: 'cad.chamfer', source: obj.name, inputs: [baseVar],
1225
+ params: { edges, type: 'distanceAngle', width: size, angle },
1226
+ }],
1227
+ };
1228
+ }
1229
+ if (type !== 0)
1230
+ return { kind: 'baked', reason: `chamfer-unknown-type: ${type}` };
1231
+ if (size === undefined || !(size > 0))
1232
+ return { kind: 'baked', reason: 'chamfer-bad-size' };
1233
+ return {
1234
+ kind: 'translated',
1235
+ calls: [{
1236
+ out, op: 'cad.chamfer', source: obj.name, inputs: [baseVar],
1237
+ params: { edges, type: 'equal', width: size },
1238
+ }],
1239
+ };
1240
+ }
1241
+ case 'Part::Chamfer': {
1242
+ // P8: Part-workbench chamfer. GOTCHA: edge selection AND sizes do NOT
1243
+ // live in Document.xml — the `Edges` property points at a binary
1244
+ // PropertyFilletEdges ZIP member (parsed by convert, passed in via
1245
+ // filletEdgesData). XML-only reading yields no size at all.
1246
+ const chBase = propLink(obj, 'Base');
1247
+ const chBaseVar = chBase ? inputVar(chBase) : undefined;
1248
+ if (!chBaseVar)
1249
+ return { kind: 'baked', reason: 'chamfer-missing-base' };
1250
+ const chEntries = filletEdgesData?.get(obj.name);
1251
+ if (!chEntries || chEntries.length === 0) {
1252
+ return { kind: 'baked', reason: 'chamfer-edges-data-missing' };
1253
+ }
1254
+ // cad.chamfer 'equal' takes ONE width for ALL edges. Mixed sizes across
1255
+ // edges cannot be emitted as sequential calls either: after the first
1256
+ // chamfer the shape's edge ordinals shift, so the second call's
1257
+ // EdgeN refs would point at the wrong edges (corpus: 1/109 objects).
1258
+ const chSizes = new Set(chEntries.map((e) => e.size1));
1259
+ if (chSizes.size > 1)
1260
+ return { kind: 'baked', reason: 'chamfer-mixed-sizes' };
1261
+ // Asymmetric size1 != size2 (two-distance chamfer): 0 corpus
1262
+ // occurrences; the Size1/Size2 face-side correspondence to
1263
+ // cad.chamfer twoDistances width1/width2 is unverified — honest bake.
1264
+ if (chEntries.some((e) => e.size1 !== e.size2)) {
1265
+ return { kind: 'baked', reason: 'chamfer-asymmetric-sizes' };
1266
+ }
1267
+ const chSize = chEntries[0].size1;
1268
+ if (!(chSize > 0))
1269
+ return { kind: 'baked', reason: 'chamfer-bad-size' };
1270
+ return {
1271
+ kind: 'translated',
1272
+ calls: [{
1273
+ out, op: 'cad.chamfer', source: obj.name, inputs: [chBaseVar],
1274
+ params: { edges: edgeRefArgs(chBaseVar, chEntries.map((e) => e.edge)), type: 'equal', width: chSize },
1275
+ }],
1276
+ };
1277
+ }
1278
+ case 'Part::Fillet': {
1279
+ // P9: Part-workbench fillet. Same binary PropertyFilletEdges member as
1280
+ // Part::Chamfer (parsed by convert, passed in via filletEdgesData). The
1281
+ // radius lives ONLY in that binary member — Document.xml carries no
1282
+ // usable radius.
1283
+ const fBase = propLink(obj, 'Base');
1284
+ const fBaseVar = fBase ? inputVar(fBase) : undefined;
1285
+ if (!fBaseVar)
1286
+ return { kind: 'baked', reason: 'fillet-missing-base' };
1287
+ const fEntries = filletEdgesData?.get(obj.name);
1288
+ if (!fEntries || fEntries.length === 0) {
1289
+ return { kind: 'baked', reason: 'fillet-edges-data-missing' };
1290
+ }
1291
+ // cad.fillet (M1) supports ONE uniform radius for all edges. A constant
1292
+ // fillet stores radius in both size1 and size2; anything else (size1 !=
1293
+ // size2, or differing radius across edges) is a variable-radius fillet
1294
+ // that M1 cannot emit as a single call — and sequential calls would shift
1295
+ // edge ordinals (same hazard as chamfer). Honest bake, no silent loss.
1296
+ if (fEntries.some((e) => e.size1 !== e.size2)) {
1297
+ return { kind: 'baked', reason: 'fillet-asymmetric-sizes' };
1298
+ }
1299
+ const fRadii = new Set(fEntries.map((e) => e.size1));
1300
+ if (fRadii.size > 1)
1301
+ return { kind: 'baked', reason: 'fillet-variable-radius' };
1302
+ const fRadius = fEntries[0].size1;
1303
+ if (!(fRadius > 0))
1304
+ return { kind: 'baked', reason: 'fillet-bad-radius' };
1305
+ return {
1306
+ kind: 'translated',
1307
+ calls: [{
1308
+ out, op: 'cad.fillet', source: obj.name, inputs: [fBaseVar],
1309
+ params: { edges: edgeRefArgs(fBaseVar, fEntries.map((e) => e.edge)), radius: fRadius },
1310
+ }],
1311
+ };
1312
+ }
1313
+ case 'Part::Sweep': {
1314
+ // P2-3: FreeCAD Part::Sweep → cad.sweep(profile, spine, opts).
1315
+ // Real FCStd (corpus-verified 2026-09-24): the section is carried in
1316
+ // `Sections` (App::PropertyLinkList, usually length 1) — NOT `Profile`,
1317
+ // which is absent in the corpus. We accept either, preferring the
1318
+ // standard `Profile` and falling back to `Sections[0]`.
1319
+ // The path is `Spine` (App::PropertyLinkSub): { obj: sketch, subs: edges }.
1320
+ // We pass the base object as the spine; cad.sweep now tolerates a face
1321
+ // argument and takes its outer-ring wire as the path (api/sweep.ts
1322
+ // toProfileWireView), which is exact for the dominant case where the
1323
+ // selected sub-edges ARE the full outline. Multi-edge sub-path selection
1324
+ // that is a strict subset is a P4-1 refinement (curve/attachment).
1325
+ // Mode: Frenet (0, default) / Binormal (1) / Auxiliary (2). Auxiliary
1326
+ // needs a second supporting spine we do not carry → honest bake. Check
1327
+ // this BEFORE dependency resolution: an unsupported mode is a property of
1328
+ // this object alone, independent of whether its profile/spine resolved
1329
+ // (cf. the "Auxiliary mode" test where inputVar is stubbed away).
1330
+ const modeRaw = propStr(obj, 'Mode');
1331
+ if (modeRaw === 'Auxiliary' || modeRaw === '2') {
1332
+ return { kind: 'baked', reason: 'sweep-auxiliary-unsupported' };
1333
+ }
1334
+ const sweepProfile = propLink(obj, 'Profile') ?? propLinkList(obj, 'Sections')[0];
1335
+ const sweepSpineSub = propLinkSub(obj, 'Spine');
1336
+ const sweepSpine = sweepSpineSub?.obj;
1337
+ const profileVar = sweepProfile ? inputVar(sweepProfile) : undefined;
1338
+ const spineVar = sweepSpine ? inputVar(sweepSpine) : undefined;
1339
+ if (!profileVar) {
1340
+ return { kind: 'baked', reason: sweepProfile ? `sweep-profile-baked-upstream:${sweepProfile}` : 'sweep-missing-profile' };
1341
+ }
1342
+ if (!spineVar) {
1343
+ return { kind: 'baked', reason: sweepSpine ? `sweep-spine-baked-upstream:${sweepSpine}` : 'sweep-missing-spine' };
1344
+ }
1345
+ const frenet = modeRaw === undefined || modeRaw === 'Frenet' || modeRaw === '0' || propBool(obj, 'Frenet');
1346
+ const transition = normalizeSweepTransition(propStr(obj, 'Transition'));
1347
+ const opts = {};
1348
+ if (frenet)
1349
+ opts.frenet = true;
1350
+ if (transition)
1351
+ opts.transitionMode = transition;
1352
+ return {
1353
+ kind: 'translated',
1354
+ calls: [{
1355
+ out, op: 'cad.sweep', source: obj.name, inputs: [profileVar, spineVar], params: opts,
1356
+ }],
1357
+ };
1358
+ }
1359
+ case 'Part::Loft': {
1360
+ // P2-3: FreeCAD Part::Loft → cad.loft([sections], opts). `Sections` is a
1361
+ // PropertyLinkList of already-translated profile faces/wires; cad.loft
1362
+ // adapts each face → outer-ring wire (api/loft.ts toProfileWireView).
1363
+ const sections = propLinkList(obj, 'Sections');
1364
+ // Closed loft needs a `closed` option cad.loft does not expose → honest
1365
+ // bake. Check this BEFORE dependency resolution: an unsupported option is
1366
+ // a property of this object alone, independent of whether its sections
1367
+ // resolved (cf. the "Closed=true" test where inputVar is stubbed away).
1368
+ if (propBool(obj, 'Closed'))
1369
+ return { kind: 'baked', reason: 'loft-closed-unsupported' };
1370
+ const sectionVars = sections.map((s) => inputVar(s));
1371
+ if (sections.length < 2) {
1372
+ // Genuinely fewer than two profiles → not a loft, no upstream involvement.
1373
+ return { kind: 'baked', reason: 'loft-missing-sections' };
1374
+ }
1375
+ const missingIdx = sectionVars.findIndex((v) => v === undefined);
1376
+ if (missingIdx >= 0) {
1377
+ // A section resolved to an object that itself got baked upstream → we
1378
+ // cannot reconstruct its geometry here → honest bake with the culprit.
1379
+ return { kind: 'baked', reason: `loft-section-baked-upstream:${sections[missingIdx]}` };
1380
+ }
1381
+ const ruled = propBool(obj, 'Ruled'); // FC default true; emit only when false
1382
+ const params = {};
1383
+ if (ruled === false)
1384
+ params.ruled = false;
1385
+ // Sections rendered as a positional array literal. Remap-safe: inputVar
1386
+ // already returns the renamed var (deps are processed before dependents,
1387
+ // cf. the fillet edgeRefArgs JsExpr precedent).
1388
+ return {
1389
+ kind: 'translated',
1390
+ calls: [{
1391
+ out, op: 'cad.loft', source: obj.name, inputs: [],
1392
+ literals: [jsExpr(`[${sectionVars.join(', ')}]`)], params,
1393
+ }],
1394
+ };
1395
+ }
1396
+ case 'Part::Helix': {
1397
+ // P2-3: FreeCAD Part::Helix (3D curve primitive) → cad.helix({radius,pitch,turns}).
1398
+ // cad.helix yields a 1D curve usable as a sweep spine. FC Helix props:
1399
+ // Radius / Pitch / Height (+ optional Angle cone taper, Turns alias).
1400
+ // The object's own Placement is applied by codegen's normal cad.place step,
1401
+ // so we do NOT bake origin here (that would double-place).
1402
+ const hRadius = propNum(obj, 'Radius');
1403
+ const hPitch = propNum(obj, 'Pitch');
1404
+ const hHeight = propNum(obj, 'Height');
1405
+ const hTurns = propNum(obj, 'Turns');
1406
+ const hAngle = propNum(obj, 'Angle') ?? 0;
1407
+ if (!(hRadius !== undefined && hRadius > 0))
1408
+ return { kind: 'baked', reason: 'helix-missing-radius' };
1409
+ if (!(hPitch !== undefined && hPitch !== 0))
1410
+ return { kind: 'baked', reason: 'helix-missing-pitch' };
1411
+ // cad.helix is cylindrical; a cone-taper helix is unsupported → honest bake.
1412
+ if (hAngle !== 0)
1413
+ return { kind: 'baked', reason: 'helix-cone-unsupported' };
1414
+ const turns = hHeight !== undefined ? hHeight / hPitch : hTurns;
1415
+ if (!(turns !== undefined && turns > 0))
1416
+ return { kind: 'baked', reason: 'helix-missing-turns' };
1417
+ return {
1418
+ kind: 'translated',
1419
+ calls: [{
1420
+ out, op: 'cad.helix', source: obj.name, inputs: [],
1421
+ params: { radius: hRadius, pitch: hPitch, turns },
1422
+ }],
1423
+ };
1424
+ }
1425
+ default:
1426
+ return { kind: 'baked', reason: `type-not-implemented: ${obj.type}` };
1427
+ }
1428
+ }
1429
+ function propLinkList(obj, name) {
1430
+ const listEl = obj.properties.get(name)?.children[0];
1431
+ if (!listEl)
1432
+ return [];
1433
+ const out = [];
1434
+ for (const link of listEl.children) {
1435
+ const v = link.attributes['value'];
1436
+ if (v)
1437
+ out.push(v);
1438
+ }
1439
+ return out;
1440
+ }
1441
+ //# sourceMappingURL=feature-translate.js.map