@constructorfleet/sketchforge-engine 1.31.0 → 1.33.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/README.md +120 -1
  2. package/dist/apiErrors.d.ts +84 -0
  3. package/dist/apiErrors.d.ts.map +1 -0
  4. package/dist/apiErrors.js +292 -0
  5. package/dist/apiErrors.js.map +1 -0
  6. package/dist/apiParameters.d.ts +426 -0
  7. package/dist/apiParameters.d.ts.map +1 -0
  8. package/dist/apiParameters.js +144 -0
  9. package/dist/apiParameters.js.map +1 -0
  10. package/dist/apiShapeSummary.d.ts +128 -0
  11. package/dist/apiShapeSummary.d.ts.map +1 -0
  12. package/dist/apiShapeSummary.js +96 -0
  13. package/dist/apiShapeSummary.js.map +1 -0
  14. package/dist/apiSketchConstraints.d.ts +80 -0
  15. package/dist/apiSketchConstraints.d.ts.map +1 -0
  16. package/dist/apiSketchConstraints.js +59 -0
  17. package/dist/apiSketchConstraints.js.map +1 -0
  18. package/dist/domain/sketchforge.d.ts +31 -0
  19. package/dist/domain/sketchforge.d.ts.map +1 -1
  20. package/dist/editorHistory.d.ts +25 -4
  21. package/dist/editorHistory.d.ts.map +1 -1
  22. package/dist/editorHistory.js +75 -14
  23. package/dist/editorHistory.js.map +1 -1
  24. package/dist/engine.d.ts +105 -3
  25. package/dist/engine.d.ts.map +1 -1
  26. package/dist/engine.js +1281 -655
  27. package/dist/engine.js.map +1 -1
  28. package/dist/expressionBindings.d.ts +113 -0
  29. package/dist/expressionBindings.d.ts.map +1 -0
  30. package/dist/expressionBindings.js +353 -0
  31. package/dist/expressionBindings.js.map +1 -0
  32. package/dist/index.d.ts +11 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +9 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/parameterBindingPlan.d.ts +64 -0
  37. package/dist/parameterBindingPlan.d.ts.map +1 -0
  38. package/dist/parameterBindingPlan.js +138 -0
  39. package/dist/parameterBindingPlan.js.map +1 -0
  40. package/dist/parameterExpressions.d.ts +128 -0
  41. package/dist/parameterExpressions.d.ts.map +1 -0
  42. package/dist/parameterExpressions.js +666 -0
  43. package/dist/parameterExpressions.js.map +1 -0
  44. package/dist/parametricRecompute.d.ts.map +1 -1
  45. package/dist/parametricRecompute.js +25 -2
  46. package/dist/parametricRecompute.js.map +1 -1
  47. package/dist/projectParameters.d.ts +126 -0
  48. package/dist/projectParameters.d.ts.map +1 -0
  49. package/dist/projectParameters.js +534 -0
  50. package/dist/projectParameters.js.map +1 -0
  51. package/dist/revolveRequests.d.ts +1 -0
  52. package/dist/revolveRequests.d.ts.map +1 -1
  53. package/dist/revolveRequests.js +1 -0
  54. package/dist/revolveRequests.js.map +1 -1
  55. package/dist/sceneExport.d.ts.map +1 -1
  56. package/dist/sceneExport.js +3 -0
  57. package/dist/sceneExport.js.map +1 -1
  58. package/dist/serverProjectDocument.d.ts +7 -2
  59. package/dist/serverProjectDocument.d.ts.map +1 -1
  60. package/dist/serverProjectDocument.js +16 -1
  61. package/dist/serverProjectDocument.js.map +1 -1
  62. package/dist/serverShapeGroups.d.ts +5 -0
  63. package/dist/serverShapeGroups.d.ts.map +1 -1
  64. package/dist/serverShapeGroups.js +45 -0
  65. package/dist/serverShapeGroups.js.map +1 -1
  66. package/dist/shapeRequestExpressions.d.ts +31 -0
  67. package/dist/shapeRequestExpressions.d.ts.map +1 -0
  68. package/dist/shapeRequestExpressions.js +64 -0
  69. package/dist/shapeRequestExpressions.js.map +1 -0
  70. package/dist/shapeRequests.d.ts +1 -1
  71. package/dist/shapeRequests.d.ts.map +1 -1
  72. package/dist/shapeRequests.js +3 -1
  73. package/dist/shapeRequests.js.map +1 -1
  74. package/dist/sketchConstraintBindings.d.ts +131 -0
  75. package/dist/sketchConstraintBindings.d.ts.map +1 -0
  76. package/dist/sketchConstraintBindings.js +353 -0
  77. package/dist/sketchConstraintBindings.js.map +1 -0
  78. package/dist/sketchConstraints.d.ts +34 -0
  79. package/dist/sketchConstraints.d.ts.map +1 -0
  80. package/dist/sketchConstraints.js +919 -0
  81. package/dist/sketchConstraints.js.map +1 -0
  82. package/dist/skfProject.d.ts +41 -4
  83. package/dist/skfProject.d.ts.map +1 -1
  84. package/dist/skfProject.js +154 -16
  85. package/dist/skfProject.js.map +1 -1
  86. package/dist/support/lib/operator-configuration.json +3 -3
  87. package/package.json +1 -1
package/dist/engine.js CHANGED
@@ -41,6 +41,11 @@ import { edgeTreatmentAppliedFrame, findSketchOutput, recompute, replaceSketchOu
41
41
  import { boundsForShapes, footprintCenter, shapeBounds } from "./shapeBounds.js";
42
42
  import { REQUESTABLE_SHAPE_KINDS, shapeFromRequest, shapeWithRequestedChanges, SHAPE_PARAMETERS, withResultAttributes, } from "./shapeRequests.js";
43
43
  import { canonicalizeShape, cleanNearZero, cleanRotationDegrees, cloneWorkplaneShapeTreeWithFreshIds, withHoleMode, } from "./workplaneShapes.js";
44
+ import { boundAncestorSizeFields, boundSketchConstraints, conflictingConstraintBinding, conflictingGroupSizeBinding, groupRefitBindings, echoesSketchConstraints, requestedSketchProfile, profileSizeFields, rebuildableSketch, resolveSketchConstraintBinding, sketchNotRebuildable, sketchConstraintValue, withSketchConstraintValues, } from "./sketchConstraintBindings.js";
45
+ import { planParameterBindings, solvedSketchProfile as solveSharedSketchProfile } from "./parameterBindingPlan.js";
46
+ import { bindableField, GROUP_SIZE_FIELDS, refitsParent, boundFieldsNamedBy, boundFieldValue, resolveShapeBinding, withoutBindings, withoutShapeBindings, } from "./expressionBindings.js";
47
+ import { echoedBindings, parseRequestExpressions, requestedBindingValue } from "./shapeRequestExpressions.js";
48
+ import { activateConfiguration as activateTableConfiguration, addConfiguration as addTableConfiguration, clearConfigurationOverride as clearTableConfigurationOverride, deleteConfiguration as deleteTableConfiguration, renameConfiguration as renameTableConfiguration, setConfigurationOverride as setTableConfigurationOverride, addParameter as addTableParameter, deleteParameter as deleteTableParameter, renameParameter as renameTableParameter, updateParameter as updateTableParameter, } from "./projectParameters.js";
44
49
  const FACE_DRAFT_AXES = new Set(["x", "y", "z", "-x", "-y", "-z"]);
45
50
  function faceDraftInput(value) {
46
51
  if (!value || typeof value !== "object" || Array.isArray(value))
@@ -250,6 +255,133 @@ async function builtShape(request, index) {
250
255
  ? ok(shape)
251
256
  : failed({ reason: "unsupported_kind", index, kinds: [...REQUESTABLE_SHAPE_KINDS, "revolve", "thread"] });
252
257
  }
258
+ function replaceShapeInTree(roots, replacement) {
259
+ const visit = (shape) => {
260
+ if (shape.id === replacement.id)
261
+ return replacement;
262
+ if (!shape.groupedShapes?.length)
263
+ return shape;
264
+ const children = shape.groupedShapes.map(visit);
265
+ return children.some((child, index) => child !== shape.groupedShapes[index]) ? { ...shape, groupedShapes: children } : shape;
266
+ };
267
+ return roots.map(visit);
268
+ }
269
+ /** Finds a shape anywhere in the tree. `locked` names the shape or nearest locked ancestor. */
270
+ function findShapeInTree(roots, id) {
271
+ const pending = roots.map((shape) => ({ shape, topLevel: true }));
272
+ while (pending.length) {
273
+ const next = pending.shift();
274
+ const locked = next.shape.locked ? next.shape.id : next.locked;
275
+ if (next.shape.id === id)
276
+ return { ...next, ...(locked ? { locked } : {}) };
277
+ next.shape.groupedShapes?.forEach((child) => pending.push({ shape: child, topLevel: false, ...(locked ? { locked } : {}) }));
278
+ }
279
+ return undefined;
280
+ }
281
+ /** Separated and exploded parts are new bodies; no binding on the source describes them. */
282
+ function withoutAnyBindings(shape) {
283
+ return withoutBindings(shape, Object.keys(shape.expressions ?? {}));
284
+ }
285
+ /** Refuses a group size binding next to a nested binding that refits the group, either way round. */
286
+ function groupSizeConflict(roots, shape, field, topLevel) {
287
+ if (shape.groupedShapes?.length && GROUP_SIZE_FIELDS.includes(field)) {
288
+ const { constraintIds, fields } = groupRefitBindings(shape);
289
+ if (constraintIds.length || fields.length) {
290
+ return {
291
+ code: "conflictingBinding",
292
+ shapeId: shape.id,
293
+ field,
294
+ ...(constraintIds.length ? { constraintIds } : {}),
295
+ message: `${field} cannot bind: ${[...constraintIds, ...fields].join(", ")} inside ${shape.id} is bound, and its rebuild refits the group. Clear one binding first.`,
296
+ };
297
+ }
298
+ }
299
+ if (topLevel || !refitsParent(field))
300
+ return undefined;
301
+ const sizes = boundAncestorSizeFields(roots, shape.id);
302
+ if (!sizes.length)
303
+ return undefined;
304
+ return {
305
+ code: "conflictingBinding",
306
+ shapeId: shape.id,
307
+ field,
308
+ message: `${field} cannot bind: ${sizes.join(", ")} is bound on a group that holds ${shape.id}, and a rebuild would refit that group. Clear one binding first.`,
309
+ };
310
+ }
311
+ /** Lists bindings present in `before` and gone from `after`, on every shape but `changedId`. */
312
+ function bindingsDropped(before, after, changedId) {
313
+ const kept = new Map();
314
+ const collect = (shape) => {
315
+ kept.set(shape.id, shape.expressions);
316
+ shape.groupedShapes?.forEach(collect);
317
+ };
318
+ after.forEach(collect);
319
+ const dropped = [];
320
+ const compare = (shape) => {
321
+ if (shape.id !== changedId && kept.has(shape.id)) {
322
+ const fields = Object.keys(shape.expressions ?? {}).filter((field) => kept.get(shape.id)?.[field] === undefined);
323
+ if (fields.length)
324
+ dropped.push({ shapeId: shape.id, fields });
325
+ }
326
+ shape.groupedShapes?.forEach(compare);
327
+ };
328
+ before.forEach(compare);
329
+ return dropped;
330
+ }
331
+ const TREATMENT_BINDINGS = new Set(["edgeTreatments.0.amount", "edgeTreatments.0.chamferAngle"]);
332
+ const PLACEMENT_BINDINGS = ["x", "z", "elevation", "rotation", "rotationX", "rotationZ"];
333
+ /**
334
+ * Returns `before`'s values for bound placement fields a rebuild moved.
335
+ * A solve can shift a sketch's centre; the bound placement must still hold.
336
+ */
337
+ function driftedPlacement(before, after) {
338
+ return Object.fromEntries(PLACEMENT_BINDINGS.flatMap((field) => {
339
+ if (before.expressions?.[field] === undefined || after.expressions?.[field] === undefined)
340
+ return [];
341
+ const value = boundFieldValue(before, field);
342
+ return value !== undefined && value !== boundFieldValue(after, field) ? [[field, value]] : [];
343
+ }));
344
+ }
345
+ /**
346
+ * Finds a field whose literal and expression both changed and disagree.
347
+ * A literal equal to `current`'s value is an echo, so its new expression wins.
348
+ */
349
+ function conflictingLiteral(shape, request, expressions, parameters, current) {
350
+ for (const [field, expression] of Object.entries(expressions)) {
351
+ if (expression === null)
352
+ continue;
353
+ const literal = requestedBindingValue(request, field);
354
+ if (literal === undefined || (current && literal === boundFieldValue(current, field)))
355
+ continue;
356
+ const resolved = resolveShapeBinding(shape, field, expression, parameters);
357
+ if (resolved.ok && resolved.value !== literal) {
358
+ return { field, message: `${field} is sent as ${literal}, but expressions.${field} gives ${resolved.value}. Send one or the other.` };
359
+ }
360
+ }
361
+ return undefined;
362
+ }
363
+ /** Returns the lock refusal naming the nearest locked shape. `locked: false` lifts only the shape's own lock. */
364
+ function lockRefusal(roots, found, changes) {
365
+ const locked = found?.locked;
366
+ if (!locked || (locked === found.shape.id && changes.locked === false))
367
+ return undefined;
368
+ if (roots.some((root) => root.id === locked))
369
+ return { reason: "shape_locked", ids: [locked] };
370
+ const topLevelId = roots.find((root) => findShapeInTree([root], locked))?.id;
371
+ return { reason: "shape_locked", ids: [locked], ...(topLevelId ? { topLevelId } : {}) };
372
+ }
373
+ /** Finds a sketch output by its own ID, or by a sketch source ID that names exactly one output. */
374
+ function findSketchOutputShape(roots, id) {
375
+ const byId = findShapeInTree(roots, id);
376
+ if (byId?.shape.sketchProfile)
377
+ return byId;
378
+ const outputs = findSketchOutput([...roots], id);
379
+ return outputs.length === 1 ? findShapeInTree(roots, outputs[0].id) : undefined;
380
+ }
381
+ function solvedSketchProfile(shape, values) {
382
+ const solved = solveSharedSketchProfile(shape, values);
383
+ return solved.ok ? ok(solved.profile) : failed(solved.failure);
384
+ }
253
385
  export function createEngine(store) {
254
386
  /** Read the project under its lock, run `work`, and report a busy project as a failure. */
255
387
  async function mutating(projectId, work) {
@@ -295,9 +427,10 @@ export function createEngine(store) {
295
427
  const locked = lockedIds(resolved.value);
296
428
  if (locked)
297
429
  return failed({ reason: "shape_locked", ids: locked });
298
- const operands = holes
430
+ // Grouping rewrites operand placement into the group frame, a literal change.
431
+ const operands = (holes
299
432
  ? resolved.value.map((shape) => withHoleMode(shape, holes.has(shape.id)))
300
- : resolved.value;
433
+ : resolved.value).map(withoutShapeBindings);
301
434
  const outcome = await buildGroupFromSelection(operands);
302
435
  if ("error" in outcome) {
303
436
  return failed({ reason: "geometry_failed", message: outcome.error, status: outcome.status });
@@ -353,7 +486,9 @@ export function createEngine(store) {
353
486
  }
354
487
  let changed;
355
488
  try {
356
- changed = await run(found.value);
489
+ changed = withoutBindings(await run(found.value), operation === "prism-draft"
490
+ ? ["draftPrismAngle"]
491
+ : ["edgeTreatments.0.amount", "edgeTreatments.0.chamferAngle"]);
357
492
  }
358
493
  catch (error) {
359
494
  return failed(cadFailure(error));
@@ -390,7 +525,7 @@ export function createEngine(store) {
390
525
  const deltaById = new Map(shifts.map((shift) => [shift.id, shift.delta]));
391
526
  const shapes = document.shapes.map((shape) => {
392
527
  const delta = deltaById.get(shape.id);
393
- return delta === undefined ? shape : shapeMovedAlong(shape, axis, delta);
528
+ return delta === undefined ? shape : withoutBindings(shapeMovedAlong(shape, axis, delta), [axis === "y" ? "elevation" : axis]);
394
529
  });
395
530
  const selected = new Set(ids);
396
531
  return ok({
@@ -400,701 +535,1127 @@ export function createEngine(store) {
400
535
  });
401
536
  });
402
537
  }
403
- return {
404
- project: (projectId) => reading(projectId, async (document) => ok({
405
- projectId,
406
- name: document.projectName,
407
- createdAt: document.createdAt,
408
- revision: documentRevision(document),
409
- shapes: document.shapes,
410
- snapGrid: document.snapGrid,
411
- workspace: document.workspace,
412
- })),
413
- addShapes: async (projectId, requests) => {
414
- const built = [];
415
- for (const [index, request] of requests.entries()) {
416
- const shape = await builtShape(request, index);
417
- if (!shape.ok)
418
- return shape;
419
- built.push(shape.value);
420
- }
421
- return mutating(projectId, async (document) => ok({
422
- shapes: built,
423
- revision: await writeShapes(projectId, document, [...document.shapes, ...built]),
424
- }));
425
- },
426
- changeShape: (projectId, shapeId, changes) => mutating(projectId, async (document) => {
427
- const byOutputId = oneShape(document, shapeId);
428
- // A persisted sketch source is an input node, not a renderable shape.
429
- // When a caller edits that node's profile or revolve settings, resolve
430
- // its dependent output and rebuild it before the single project write. The
431
- // output keeps its own stable object ID; SKF export derives the source
432
- // node from the synchronized profile on that output.
433
- const sourceFeatureInputChanged = changes.sketchProfile !== undefined
434
- || changes.draftPrismAngle !== undefined
435
- || Object.hasOwn(changes, "faceDraft")
436
- || REVOLVE_CHANGE_FIELDS.some((field) => changes[field] !== undefined);
437
- const sourceOutputs = !byOutputId.ok && sourceFeatureInputChanged
438
- ? findSketchOutput(document.shapes, shapeId)
439
- : [];
440
- const sourceSketchTarget = !byOutputId.ok && sourceOutputs.length === 1;
441
- const found = byOutputId.ok
442
- ? byOutputId
443
- : sourceSketchTarget
444
- ? ok(sourceOutputs[0])
445
- : byOutputId;
446
- if (!found.ok)
447
- return found;
448
- const existing = found.value;
449
- if (sourceSketchTarget) {
450
- const isRevolveSource = isRevolveShape(existing);
451
- const outputFields = Object.keys(changes).filter((field) => field !== "sketchProfile" && field !== "draftPrismAngle" && field !== "faceDraft"
452
- && !(isRevolveSource && REVOLVE_CHANGE_FIELDS.includes(field)));
453
- if (outputFields.length > 0) {
454
- return failed({ reason: "unapplicable_fields", kind: existing.kind, fields: outputFields, because: "not_this_kind" });
455
- }
456
- }
457
- // A locked shape refuses every change but the one that unlocks it, which
458
- // may arrive in the same request as the rest: `locked: false` alongside a
459
- // new width is one call rather than two.
460
- if (existing.locked && changes.locked !== false)
461
- return failed({ reason: "shape_locked", ids: [shapeId] });
462
- const replacingSketchProfile = changes.sketchProfile !== undefined;
463
- const faceDraftChanged = Object.hasOwn(changes, "faceDraft");
464
- const clearingFaceDraft = faceDraftChanged && changes.faceDraft === null && existing.faceDraft !== undefined;
465
- const requestedFaceDraft = faceDraftChanged
466
- ? changes.faceDraft === null ? undefined : faceDraftInput(changes.faceDraft)
467
- : existing.faceDraft;
468
- const isSketchSweep = existing.sketchOperation === "sweep" && Boolean(existing.sketchProfile);
469
- const isSketchExtrusion = existing.sketchOperation === "extrude" && Boolean(existing.sketchProfile);
470
- const isSketchRevolve = isRevolveShape(existing);
471
- const rebuildsFromSource = replacingSketchProfile || faceDraftChanged || changes.draftPrismAngle !== undefined
472
- || (isSketchRevolve && REVOLVE_CHANGE_FIELDS.some((field) => changes[field] !== undefined));
473
- if (existing.shell && rebuildsFromSource) {
474
- return failed({
475
- reason: "sweep_failed",
476
- message: "This shape was shelled, and a rebuild from its source cannot replay a shell, so the edit would lose it",
477
- });
478
- }
479
- if (faceDraftChanged && changes.faceDraft !== null && !requestedFaceDraft) {
480
- return failed({ reason: "invalid_shape_request", message: "A face draft requires a stable source face ID, a non-zero angle below 45 degrees, and a signed local pull axis." });
481
- }
482
- const isExactSketchRevolve = isPlainFullTurnSketchRevolve(existing);
483
- if ((faceDraftChanged || (replacingSketchProfile && existing.faceDraft))
484
- && !isSketchExtrusion && !isSketchSweep && !isExactSketchRevolve) {
485
- return failed({ reason: "unapplicable_fields", kind: existing.kind, fields: ["faceDraft"], because: "not_this_kind" });
486
- }
487
- const hasExistingTreatment = (existing.edgeTreatments?.length ?? 0) > 0
488
- || (existing.edgeTreatmentHistory?.length ?? 0) > 0;
489
- const canReplayFaceDraftTreatment = existing.faceDraft !== undefined
490
- && existing.draftPrismAngle === undefined
491
- && (!faceDraftChanged || requestedFaceDraft !== undefined && requestedFaceDraft !== null
492
- && requestedFaceDraft.sourceFaceId === existing.faceDraft.sourceFaceId)
493
- && (isPlainFullTurnSketchRevolve(existing)
494
- || isSingleLoopSketchExtrusion(existing)
495
- && (existing.edgeTreatments?.[0]?.kind === "fillet" || existing.edgeTreatments?.[0]?.kind === "chamfer")
496
- || isSingleSectionSketchSweep(existing)
497
- && (existing.edgeTreatments?.[0]?.kind === "fillet" || existing.edgeTreatments?.[0]?.kind === "chamfer"))
498
- && existing.edgeTreatments?.length === 1
499
- && (existing.edgeTreatments[0]?.kind === "chamfer" || existing.edgeTreatments[0]?.kind === "fillet")
500
- && existing.edgeTreatments[0]?.allEdges === true
501
- && existing.edgeTreatmentHistory?.length === 1
502
- && existing.edgeTreatmentHistory[0]?.feature.kind === existing.edgeTreatments[0]?.kind
503
- && existing.edgeTreatmentHistory[0]?.feature.allEdges === true
504
- && (existing.edgeTreatments[0]?.kind !== "chamfer"
505
- || Math.abs((existing.edgeTreatments[0].chamferAngle ?? 45) - 45) < 0.001
506
- && Math.abs((existing.edgeTreatmentHistory[0]?.feature.chamferAngle ?? 45) - 45) < 0.001);
507
- if (requestedFaceDraft
508
- && (existing.draftPrismAngle !== undefined || hasExistingTreatment && !canReplayFaceDraftTreatment)) {
509
- return failed({ reason: "invalid_shape_request", message: "This face draft cannot be combined with the requested persisted draft or treatment history." });
510
- }
511
- const canReselectUntreatedExtrusionFace = isSingleLoopSketchExtrusion(existing)
512
- && existing.draftPrismAngle === undefined
513
- && !hasExistingTreatment;
514
- if (faceDraftChanged && existing.faceDraft && requestedFaceDraft
515
- && requestedFaceDraft.sourceFaceId !== existing.faceDraft.sourceFaceId
516
- && replacingSketchProfile) {
517
- return failed({ reason: "invalid_shape_request", message: "Change the sketch profile and face draft selection in separate edits." });
518
- }
519
- if (faceDraftChanged && existing.faceDraft && requestedFaceDraft
520
- && requestedFaceDraft.sourceFaceId !== existing.faceDraft.sourceFaceId) {
521
- let currentOutputFaces;
522
- try {
523
- currentOutputFaces = await shapeFaces(existing);
524
- }
525
- catch (error) {
526
- return failed(cadFailure(error));
527
- }
528
- if (!canReselectUntreatedExtrusionFace
529
- || !existing.faceDraftSourceFaceIds?.includes(requestedFaceDraft.sourceFaceId)
530
- || currentOutputFaces.filter((face) => face.id === requestedFaceDraft.sourceFaceId && face.surfaceType === "plane").length !== 1) {
531
- return failed({ reason: "invalid_shape_request", message: "Clear the existing face draft before selecting a different source face." });
532
- }
538
+ /** Applies one shape change to `document` without writing. `changeShape` and parameter recompute share it. */
539
+ async function changeShapeIn(document, shapeId, changes) {
540
+ const byOutputId = oneShape(document, shapeId);
541
+ // A persisted sketch source is an input node, not a renderable shape.
542
+ // When a caller edits that node's profile or revolve settings, resolve
543
+ // its dependent output and rebuild it before the single project write. The
544
+ // output keeps its own stable object ID; SKF export derives the source
545
+ // node from the synchronized profile on that output.
546
+ const sourceFeatureInputChanged = changes.sketchProfile !== undefined
547
+ || changes.draftPrismAngle !== undefined
548
+ || Object.hasOwn(changes, "faceDraft")
549
+ || REVOLVE_CHANGE_FIELDS.some((field) => changes[field] !== undefined);
550
+ const sourceOutputs = !byOutputId.ok && sourceFeatureInputChanged
551
+ ? findSketchOutput(document.shapes, shapeId)
552
+ : [];
553
+ const sourceSketchTarget = !byOutputId.ok && sourceOutputs.length === 1;
554
+ const found = byOutputId.ok
555
+ ? byOutputId
556
+ : sourceSketchTarget
557
+ ? ok(sourceOutputs[0])
558
+ : byOutputId;
559
+ if (!found.ok)
560
+ return found;
561
+ const existing = found.value;
562
+ // `locked: false` may unlock in the same request as other changes.
563
+ // A source ID reaches nested outputs, so a locked group refuses first.
564
+ const locked = lockRefusal(document.shapes, findShapeInTree(document.shapes, existing.id), changes);
565
+ if (locked)
566
+ return failed(locked);
567
+ if (sourceSketchTarget) {
568
+ const isRevolveSource = isRevolveShape(existing);
569
+ const outputFields = Object.keys(changes).filter((field) => field !== "sketchProfile" && field !== "draftPrismAngle" && field !== "faceDraft"
570
+ && !(isRevolveSource && REVOLVE_CHANGE_FIELDS.includes(field)));
571
+ if (outputFields.length > 0) {
572
+ return failed({ reason: "unapplicable_fields", kind: existing.kind, fields: outputFields, because: "not_this_kind" });
533
573
  }
534
- const draftPrismChanged = changes.draftPrismAngle !== undefined;
535
- const requestedDraftPrismAngle = typeof changes.draftPrismAngle === "number" ? changes.draftPrismAngle : undefined;
536
- if (draftPrismChanged && (!isSketchExtrusion || requestedDraftPrismAngle === undefined || !Number.isFinite(requestedDraftPrismAngle)
537
- || requestedDraftPrismAngle === 0 || Math.abs(requestedDraftPrismAngle) >= 45)) {
538
- return failed({
539
- reason: "invalid_shape_request",
540
- message: "A draft prism angle must be non-zero and between -45 and 45 degrees on a sketch extrusion.",
541
- });
574
+ }
575
+ const replacingSketchProfile = changes.sketchProfile !== undefined;
576
+ const faceDraftChanged = Object.hasOwn(changes, "faceDraft");
577
+ const clearingFaceDraft = faceDraftChanged && changes.faceDraft === null && existing.faceDraft !== undefined;
578
+ const requestedFaceDraft = faceDraftChanged
579
+ ? changes.faceDraft === null ? undefined : faceDraftInput(changes.faceDraft)
580
+ : existing.faceDraft;
581
+ const isSketchSweep = existing.sketchOperation === "sweep" && Boolean(existing.sketchProfile);
582
+ const isSketchExtrusion = existing.sketchOperation === "extrude" && Boolean(existing.sketchProfile);
583
+ const isSketchRevolve = isRevolveShape(existing);
584
+ const rebuildsFromSource = replacingSketchProfile || faceDraftChanged || changes.draftPrismAngle !== undefined
585
+ || (isSketchRevolve && REVOLVE_CHANGE_FIELDS.some((field) => changes[field] !== undefined));
586
+ if (existing.shell && rebuildsFromSource) {
587
+ return failed({
588
+ reason: "sweep_failed",
589
+ message: "This shape was shelled, and a rebuild from its source cannot replay a shell, so the edit would lose it",
590
+ });
591
+ }
592
+ if (faceDraftChanged && changes.faceDraft !== null && !requestedFaceDraft) {
593
+ return failed({ reason: "invalid_shape_request", message: "A face draft requires a stable source face ID, a non-zero angle below 45 degrees, and a signed local pull axis." });
594
+ }
595
+ const isExactSketchRevolve = isPlainFullTurnSketchRevolve(existing);
596
+ if ((faceDraftChanged || (replacingSketchProfile && existing.faceDraft))
597
+ && !isSketchExtrusion && !isSketchSweep && !isExactSketchRevolve) {
598
+ return failed({ reason: "unapplicable_fields", kind: existing.kind, fields: ["faceDraft"], because: "not_this_kind" });
599
+ }
600
+ const hasExistingTreatment = (existing.edgeTreatments?.length ?? 0) > 0
601
+ || (existing.edgeTreatmentHistory?.length ?? 0) > 0;
602
+ const canReplayFaceDraftTreatment = existing.faceDraft !== undefined
603
+ && existing.draftPrismAngle === undefined
604
+ && (!faceDraftChanged || requestedFaceDraft !== undefined && requestedFaceDraft !== null
605
+ && requestedFaceDraft.sourceFaceId === existing.faceDraft.sourceFaceId)
606
+ && (isPlainFullTurnSketchRevolve(existing)
607
+ || isSingleLoopSketchExtrusion(existing)
608
+ && (existing.edgeTreatments?.[0]?.kind === "fillet" || existing.edgeTreatments?.[0]?.kind === "chamfer")
609
+ || isSingleSectionSketchSweep(existing)
610
+ && (existing.edgeTreatments?.[0]?.kind === "fillet" || existing.edgeTreatments?.[0]?.kind === "chamfer"))
611
+ && existing.edgeTreatments?.length === 1
612
+ && (existing.edgeTreatments[0]?.kind === "chamfer" || existing.edgeTreatments[0]?.kind === "fillet")
613
+ && existing.edgeTreatments[0]?.allEdges === true
614
+ && existing.edgeTreatmentHistory?.length === 1
615
+ && existing.edgeTreatmentHistory[0]?.feature.kind === existing.edgeTreatments[0]?.kind
616
+ && existing.edgeTreatmentHistory[0]?.feature.allEdges === true
617
+ && (existing.edgeTreatments[0]?.kind !== "chamfer"
618
+ || Math.abs((existing.edgeTreatments[0].chamferAngle ?? 45) - 45) < 0.001
619
+ && Math.abs((existing.edgeTreatmentHistory[0]?.feature.chamferAngle ?? 45) - 45) < 0.001);
620
+ if (requestedFaceDraft
621
+ && (existing.draftPrismAngle !== undefined || hasExistingTreatment && !canReplayFaceDraftTreatment)) {
622
+ return failed({ reason: "invalid_shape_request", message: "This face draft cannot be combined with the requested persisted draft or treatment history." });
623
+ }
624
+ const canReselectUntreatedExtrusionFace = isSingleLoopSketchExtrusion(existing)
625
+ && existing.draftPrismAngle === undefined
626
+ && !hasExistingTreatment;
627
+ if (faceDraftChanged && existing.faceDraft && requestedFaceDraft
628
+ && requestedFaceDraft.sourceFaceId !== existing.faceDraft.sourceFaceId
629
+ && replacingSketchProfile) {
630
+ return failed({ reason: "invalid_shape_request", message: "Change the sketch profile and face draft selection in separate edits." });
631
+ }
632
+ if (faceDraftChanged && existing.faceDraft && requestedFaceDraft
633
+ && requestedFaceDraft.sourceFaceId !== existing.faceDraft.sourceFaceId) {
634
+ let currentOutputFaces;
635
+ try {
636
+ currentOutputFaces = await shapeFaces(existing);
542
637
  }
543
- if (draftPrismChanged && requestedFaceDraft) {
544
- return failed({ reason: "invalid_shape_request", message: "Face drafts cannot be combined with prism drafts yet." });
638
+ catch (error) {
639
+ return failed(cadFailure(error));
545
640
  }
546
- if (draftPrismChanged && existing.draftPrismAngle === undefined
547
- && ((existing.edgeTreatments?.length ?? 0) > 0 || (existing.edgeTreatmentHistory?.length ?? 0) > 0)) {
548
- return failed({ reason: "invalid_shape_request", message: "A prism draft cannot be added after an edge treatment." });
641
+ if (!canReselectUntreatedExtrusionFace
642
+ || !existing.faceDraftSourceFaceIds?.includes(requestedFaceDraft.sourceFaceId)
643
+ || currentOutputFaces.filter((face) => face.id === requestedFaceDraft.sourceFaceId && face.surfaceType === "plane").length !== 1) {
644
+ return failed({ reason: "invalid_shape_request", message: "Clear the existing face draft before selecting a different source face." });
549
645
  }
550
- if (replacingSketchProfile && !isSketchSweep && !isSketchExtrusion && !isSketchRevolve) {
551
- return failed({ reason: "unapplicable_fields", kind: existing.kind, fields: ["sketchProfile"], because: "no_sweep" });
646
+ }
647
+ const draftPrismChanged = changes.draftPrismAngle !== undefined;
648
+ const requestedDraftPrismAngle = typeof changes.draftPrismAngle === "number" ? changes.draftPrismAngle : undefined;
649
+ if (draftPrismChanged && (!isSketchExtrusion || requestedDraftPrismAngle === undefined || !Number.isFinite(requestedDraftPrismAngle)
650
+ || requestedDraftPrismAngle === 0 || Math.abs(requestedDraftPrismAngle) >= 45)) {
651
+ return failed({
652
+ reason: "invalid_shape_request",
653
+ message: "A draft prism angle must be non-zero and between -45 and 45 degrees on a sketch extrusion.",
654
+ });
655
+ }
656
+ if (draftPrismChanged && requestedFaceDraft) {
657
+ return failed({ reason: "invalid_shape_request", message: "Face drafts cannot be combined with prism drafts yet." });
658
+ }
659
+ if (draftPrismChanged && existing.draftPrismAngle === undefined
660
+ && ((existing.edgeTreatments?.length ?? 0) > 0 || (existing.edgeTreatmentHistory?.length ?? 0) > 0)) {
661
+ return failed({ reason: "invalid_shape_request", message: "A prism draft cannot be added after an edge treatment." });
662
+ }
663
+ if (replacingSketchProfile && !isSketchSweep && !isSketchExtrusion && !isSketchRevolve) {
664
+ return failed({ reason: "unapplicable_fields", kind: existing.kind, fields: ["sketchProfile"], because: "no_sweep" });
665
+ }
666
+ if (sourceSketchTarget && rebuildsFromSource) {
667
+ if (replacingSketchProfile && isSketchSweep) {
668
+ const invalidProfile = invalidSketchSweepProfile(changes.sketchProfile);
669
+ if (invalidProfile)
670
+ return failed({ reason: "invalid_shape_request", message: invalidProfile });
552
671
  }
553
- if (sourceSketchTarget && rebuildsFromSource) {
554
- if (replacingSketchProfile && isSketchSweep) {
555
- const invalidProfile = invalidSketchSweepProfile(changes.sketchProfile);
556
- if (invalidProfile)
557
- return failed({ reason: "invalid_shape_request", message: invalidProfile });
672
+ let recipeFaceDraft = existing.faceDraft;
673
+ let recipeFaceDraftSourceFaceIds = existing.faceDraftSourceFaceIds;
674
+ let recipeFaceDraftSourceSegmentId = existing.faceDraftSourceSegmentId;
675
+ let recipeFaceDraftSourceFrame = existing.faceDraftSourceFrame;
676
+ if (faceDraftChanged) {
677
+ if (!requestedFaceDraft) {
678
+ recipeFaceDraft = undefined;
679
+ recipeFaceDraftSourceFaceIds = undefined;
680
+ recipeFaceDraftSourceSegmentId = undefined;
681
+ recipeFaceDraftSourceFrame = undefined;
558
682
  }
559
- let recipeFaceDraft = existing.faceDraft;
560
- let recipeFaceDraftSourceFaceIds = existing.faceDraftSourceFaceIds;
561
- let recipeFaceDraftSourceSegmentId = existing.faceDraftSourceSegmentId;
562
- let recipeFaceDraftSourceFrame = existing.faceDraftSourceFrame;
563
- if (faceDraftChanged) {
564
- if (!requestedFaceDraft) {
565
- recipeFaceDraft = undefined;
566
- recipeFaceDraftSourceFaceIds = undefined;
567
- recipeFaceDraftSourceSegmentId = undefined;
568
- recipeFaceDraftSourceFrame = undefined;
569
- }
570
- else if (existing.faceDraft && requestedFaceDraft.sourceFaceId === existing.faceDraft.sourceFaceId) {
571
- recipeFaceDraft = { ...existing.faceDraft, ...requestedFaceDraft };
683
+ else if (existing.faceDraft && requestedFaceDraft.sourceFaceId === existing.faceDraft.sourceFaceId) {
684
+ recipeFaceDraft = { ...existing.faceDraft, ...requestedFaceDraft };
685
+ }
686
+ else {
687
+ try {
688
+ const resolved = await withCadKernel((cad) => resolveRetainedFaceDraft(cad, {
689
+ existing,
690
+ source: existing,
691
+ request: requestedFaceDraft,
692
+ profileChanged: false,
693
+ }, (kernel, shape) => orientedSolidForShape(kernel, unmirroredDraftSource(shape))));
694
+ const retained = retainedFaceDraftFields(existing.faceIds, existing, resolved, requestedFaceDraft);
695
+ recipeFaceDraft = retained.faceDraft;
696
+ recipeFaceDraftSourceFaceIds = retained.faceDraftSourceFaceIds;
697
+ recipeFaceDraftSourceSegmentId = retained.faceDraftSourceSegmentId;
698
+ recipeFaceDraftSourceFrame = retained.faceDraftSourceFrame;
572
699
  }
573
- else {
574
- try {
575
- const resolved = await withCadKernel((cad) => resolveRetainedFaceDraft(cad, {
576
- existing,
577
- source: existing,
578
- request: requestedFaceDraft,
579
- profileChanged: false,
580
- }, (kernel, shape) => orientedSolidForShape(kernel, unmirroredDraftSource(shape))));
581
- const retained = retainedFaceDraftFields(existing.faceIds, existing, resolved, requestedFaceDraft);
582
- recipeFaceDraft = retained.faceDraft;
583
- recipeFaceDraftSourceFaceIds = retained.faceDraftSourceFaceIds;
584
- recipeFaceDraftSourceSegmentId = retained.faceDraftSourceSegmentId;
585
- recipeFaceDraftSourceFrame = retained.faceDraftSourceFrame;
586
- }
587
- catch (error) {
588
- return failed({ reason: "sweep_failed", message: error instanceof Error ? error.message : "The selected face could not be resolved." });
589
- }
700
+ catch (error) {
701
+ return failed({ reason: "sweep_failed", message: error instanceof Error ? error.message : "The selected face could not be resolved." });
590
702
  }
591
703
  }
592
- const recipe = {
593
- ...existing,
594
- ...(replacingSketchProfile ? { sketchProfile: changes.sketchProfile } : {}),
595
- ...(draftPrismChanged ? { draftPrismAngle: requestedDraftPrismAngle } : {}),
596
- ...(faceDraftChanged ? { faceDraft: recipeFaceDraft } : {}),
597
- ...(faceDraftChanged ? {
598
- faceDraftSourceFaceIds: recipeFaceDraftSourceFaceIds,
599
- faceDraftSourceSegmentId: recipeFaceDraftSourceSegmentId,
600
- faceDraftSourceFrame: !recipeFaceDraft && existing.faceDraft
601
- ? existing.faceDraftSourceFrame
602
- : recipeFaceDraftSourceFrame,
603
- } : {}),
604
- ...(isRevolveShape(existing) && REVOLVE_CHANGE_FIELDS.some((field) => changes[field] !== undefined)
605
- ? { sketchRevolve: requestedRevolveSettings(existing.sketchRevolve, changes) }
704
+ }
705
+ const recipe = {
706
+ ...existing,
707
+ ...(replacingSketchProfile ? { sketchProfile: changes.sketchProfile } : {}),
708
+ ...(draftPrismChanged ? { draftPrismAngle: requestedDraftPrismAngle } : {}),
709
+ ...(faceDraftChanged ? { faceDraft: recipeFaceDraft } : {}),
710
+ ...(faceDraftChanged ? {
711
+ faceDraftSourceFaceIds: recipeFaceDraftSourceFaceIds,
712
+ faceDraftSourceSegmentId: recipeFaceDraftSourceSegmentId,
713
+ faceDraftSourceFrame: !recipeFaceDraft && existing.faceDraft
714
+ ? existing.faceDraftSourceFrame
715
+ : recipeFaceDraftSourceFrame,
716
+ } : {}),
717
+ ...(isRevolveShape(existing) && REVOLVE_CHANGE_FIELDS.some((field) => changes[field] !== undefined)
718
+ ? { sketchRevolve: requestedRevolveSettings(existing.sketchRevolve, changes) }
719
+ : {}),
720
+ };
721
+ const candidate = replaceSketchOutput(document.shapes, shapeId, recipe);
722
+ if (candidate.matchCount !== 1) {
723
+ return failed({ reason: "sweep_failed", message: `Sketch source ${shapeId} has no unique output node.` });
724
+ }
725
+ const recomputed = await recompute({ ...document, shapes: candidate.shapes }, [shapeId], document);
726
+ if (!recomputed.ok)
727
+ return failed({ reason: "sweep_failed", message: recomputed.message ?? "The sketch source could not be recomputed." });
728
+ return ok({ shape: recomputed.updated, shapes: recomputed.shapes });
729
+ }
730
+ const sweptShape = isRevolveShape(existing);
731
+ const misplaced = REVOLVE_ONLY_FIELDS.filter((field) => changes[field] !== undefined);
732
+ if (!sweptShape && misplaced.length > 0) {
733
+ return failed({ reason: "unapplicable_fields", kind: existing.kind, fields: [...misplaced], because: "no_sweep" });
734
+ }
735
+ // A pitch, a turn count or a new outline is geometry rather than a
736
+ // property, so the mesh is swept again here. Refusing to rebuild would
737
+ // leave a thread's pitch readable but not writable.
738
+ const revolveChanges = sweptShape ? REVOLVE_CHANGE_FIELDS.filter((field) => changes[field] !== undefined) : [];
739
+ let swept = existing;
740
+ if ((replacingSketchProfile && isSketchExtrusion) || (draftPrismChanged && isSketchExtrusion)
741
+ || (faceDraftChanged && isSketchExtrusion)) {
742
+ // A treatment is built from the extrusion at the size it was shown
743
+ // (#539), and its record keeps that shape as `before`. Replaying it on
744
+ // a new profile rebuilds at that same resize, or the edit would hand
745
+ // back the treatment at the size the sketch was first drawn.
746
+ const treatmentSource = existing.edgeTreatmentHistory?.[0]?.before;
747
+ const recordedTreatmentScale = hasExistingTreatment && !existing.faceDraft && existing.draftPrismAngle === undefined
748
+ && treatmentSource?.sketchOperation === "extrude" && treatmentSource.cadBrep
749
+ ? sketchResizeFactors(treatmentSource)
750
+ : undefined;
751
+ // A treatment recorded before #539 kept the resize in `before` but was
752
+ // built, and stored, at the drawn size. Its shape is nearer that drawn
753
+ // size than the resized one on every resized axis, and its edit keeps
754
+ // the old behaviour: rebuilt at the profile's own size.
755
+ const nearerResized = (current, resized, factor) => Math.abs(factor - 1) < 1e-8 || Math.abs(current - resized) < Math.abs(current - resized / factor);
756
+ const treatmentSourceScale = recordedTreatmentScale && treatmentSource
757
+ && nearerResized(existing.width, treatmentSource.width, recordedTreatmentScale.width)
758
+ && nearerResized(existing.depth, treatmentSource.depth, recordedTreatmentScale.depth)
759
+ && nearerResized(existing.height, treatmentSource.height, recordedTreatmentScale.height)
760
+ ? recordedTreatmentScale
761
+ : undefined;
762
+ const sourceFrame = existing.faceDraftSourceFrame ?? existing.draftPrismSourceFrame ?? existing.cadBrepFrame;
763
+ const ratio = (drawn, source) => source && source > 0 && drawn > 0 ? drawn / source : 1;
764
+ const recordedFaceDraftScale = (existing.faceDraft ? existing.faceDraftSourceScale : undefined) ?? (existing.faceDraft ? {
765
+ // Editor-written drafts predate this field. Their output bounds
766
+ // include the taper, so they cannot be used to infer the source
767
+ // resize ratio; these shapes were only retained before resize support.
768
+ width: 1, depth: 1, height: 1,
769
+ } : {
770
+ width: ratio(existing.width, sourceFrame?.width ?? existing.importedMesh?.baseWidth),
771
+ depth: ratio(existing.depth, sourceFrame?.depth ?? existing.importedMesh?.baseDepth),
772
+ height: ratio(existing.height, sourceFrame?.height ?? existing.importedMesh?.baseHeight),
773
+ });
774
+ // Height is unchanged by face drafting, so a later dimension edit can
775
+ // be composed with the original scale without trying to infer scale
776
+ // from the tapered width/depth bounds.
777
+ const faceDraftSourceScale = existing.faceDraft && sourceFrame
778
+ ? { ...recordedFaceDraftScale, height: ratio(existing.height, sourceFrame.height) }
779
+ : recordedFaceDraftScale;
780
+ const rebuildScale = existing.faceDraft || faceDraftChanged
781
+ ? faceDraftSourceScale
782
+ : treatmentSourceScale ?? { width: 1, depth: 1, height: 1 };
783
+ // The extrusion is rebuilt at the height it was drawn and then scaled
784
+ // by `rebuildScale`, as its width is. Rebuilding a height-resized
785
+ // extrusion at its shown height applied that resize twice (#546).
786
+ const sourceHeight = existing.draftPrismSourceHeight ?? existing.faceDraftSourceFrame?.height
787
+ ?? (treatmentSourceScale ? treatmentSource.height / treatmentSourceScale.height
788
+ : existing.height / rebuildScale.height);
789
+ try {
790
+ const rebuilt = await sketchExtrusionShapeFromRequest({
791
+ id: existing.id,
792
+ sketchSourceId: existing.sketchSourceId ?? `sketch/${existing.id}`,
793
+ name: existing.name,
794
+ color: existing.color,
795
+ hole: existing.hole,
796
+ profile: replacingSketchProfile ? changes.sketchProfile : existing.sketchProfile,
797
+ height: sourceHeight,
798
+ x: 0,
799
+ z: 0,
800
+ elevation: 0,
801
+ rotation: existing.rotation,
802
+ rotationX: existing.rotationX,
803
+ rotationZ: existing.rotationZ,
804
+ });
805
+ const { faceIds: _oldFaceIds, faceColors: _faceColors, edgeTreatments: _edgeTreatments, edgeTreatmentHistory: _edgeTreatmentHistory, faceDraft: _faceDraft, cadDisplayEdges: _cadDisplayEdges, cadDisplayEdgesVersion: _cadDisplayEdgesVersion, ...sourceMetadata } = existing;
806
+ const draftPrismAngle = draftPrismChanged ? requestedDraftPrismAngle : existing.draftPrismAngle;
807
+ const rebuiltSource = {
808
+ ...sourceMetadata,
809
+ ...rebuilt,
810
+ mirrorX: existing.mirrorX,
811
+ mirrorY: existing.mirrorY,
812
+ mirrorZ: existing.mirrorZ,
813
+ ...retainedDraftSourcePlacement(existing, rebuilt.cadBrepFrame, existing.faceDraft && !hasExistingTreatment ? existing.cadBrepFrame : undefined),
814
+ // A cleared draft's resize is not kept: the bounds carry it from here.
815
+ faceDraftSourceScale: clearingFaceDraft ? undefined
816
+ : existing.faceDraft || faceDraftChanged ? faceDraftSourceScale : existing.faceDraftSourceScale,
817
+ width: rebuilt.width * rebuildScale.width,
818
+ depth: rebuilt.depth * rebuildScale.depth,
819
+ height: rebuilt.height * rebuildScale.height,
820
+ size: Math.max(rebuilt.width * rebuildScale.width, rebuilt.depth * rebuildScale.depth),
821
+ id: existing.id,
822
+ sketchSourceId: existing.sketchSourceId ?? rebuilt.sketchSourceId,
823
+ faceDraft: undefined,
824
+ faceDraftSourceFrame: undefined,
825
+ faceDraftSourceFaceIds: undefined,
826
+ faceDraftSourceSegmentId: undefined,
827
+ ...(faceDraftChanged && !replacingSketchProfile && !existing.faceDraft && !hasExistingTreatment
828
+ && existing.draftPrismAngle === undefined && existing.faceIds?.length === rebuilt.faceIds?.length
829
+ ? { faceIds: existing.faceIds }
606
830
  : {}),
831
+ ...(!replacingSketchProfile && existing.faceDraft && existing.faceDraftSourceFaceIds?.length === rebuilt.faceIds?.length
832
+ ? { faceIds: existing.faceDraftSourceFaceIds }
833
+ : {}),
834
+ ...(draftPrismAngle === undefined ? {} : {
835
+ draftPrismSourceHeight: sourceHeight,
836
+ ...(sourceFrame ? { draftPrismSourceFrame: sourceFrame } : {}),
837
+ }),
607
838
  };
608
- const candidate = replaceSketchOutput(document.shapes, shapeId, recipe);
609
- if (candidate.matchCount !== 1) {
610
- return failed({ reason: "sweep_failed", message: `Sketch source ${shapeId} has no unique output node.` });
839
+ const hasRetainedTreatments = (existing.edgeTreatments?.length ?? 0) > 0
840
+ || (existing.edgeTreatmentHistory?.length ?? 0) > 0;
841
+ const replayDraftAndTreatment = hasRetainedTreatments
842
+ && draftPrismAngle !== undefined
843
+ && (replacingSketchProfile || clearingFaceDraft || draftPrismChanged);
844
+ const replayFaceDraftAndTreatment = hasRetainedTreatments && faceDraftChanged && requestedFaceDraft !== undefined;
845
+ const replayOriginal = clearingFaceDraft
846
+ ? { ...existing, faceDraft: undefined }
847
+ : replayFaceDraftAndTreatment && existing.faceDraft
848
+ ? { ...existing, faceDraft: { ...existing.faceDraft, ...requestedFaceDraft } }
849
+ : existing;
850
+ const replayedSource = (replacingSketchProfile || clearingFaceDraft || draftPrismChanged || replayFaceDraftAndTreatment)
851
+ && hasRetainedTreatments
852
+ ? await replaySingleAllEdgeTreatment(replayOriginal, rebuiltSource, draftPrismChanged ? requestedDraftPrismAngle : undefined)
853
+ : rebuiltSource;
854
+ if (requestedFaceDraft && replayedSource.faceDraft) {
855
+ swept = replayedSource;
611
856
  }
612
- const recomputed = await recompute({ ...document, shapes: candidate.shapes }, [shapeId], document);
613
- if (!recomputed.ok)
614
- return failed({ reason: "sweep_failed", message: recomputed.message ?? "The sketch source could not be recomputed." });
615
- return ok({ shape: recomputed.updated, revision: await writeShapes(projectId, document, recomputed.shapes) });
616
- }
617
- const sweptShape = isRevolveShape(existing);
618
- const misplaced = REVOLVE_ONLY_FIELDS.filter((field) => changes[field] !== undefined);
619
- if (!sweptShape && misplaced.length > 0) {
620
- return failed({ reason: "unapplicable_fields", kind: existing.kind, fields: [...misplaced], because: "no_sweep" });
621
- }
622
- // A pitch, a turn count or a new outline is geometry rather than a
623
- // property, so the mesh is swept again here. Refusing to rebuild would
624
- // leave a thread's pitch readable but not writable.
625
- const revolveChanges = sweptShape ? REVOLVE_CHANGE_FIELDS.filter((field) => changes[field] !== undefined) : [];
626
- let swept = existing;
627
- if ((replacingSketchProfile && isSketchExtrusion) || (draftPrismChanged && isSketchExtrusion)
628
- || (faceDraftChanged && isSketchExtrusion)) {
629
- // A treatment is built from the extrusion at the size it was shown
630
- // (#539), and its record keeps that shape as `before`. Replaying it on
631
- // a new profile rebuilds at that same resize, or the edit would hand
632
- // back the treatment at the size the sketch was first drawn.
633
- const treatmentSource = existing.edgeTreatmentHistory?.[0]?.before;
634
- const recordedTreatmentScale = hasExistingTreatment && !existing.faceDraft && existing.draftPrismAngle === undefined
635
- && treatmentSource?.sketchOperation === "extrude" && treatmentSource.cadBrep
636
- ? sketchResizeFactors(treatmentSource)
637
- : undefined;
638
- // A treatment recorded before #539 kept the resize in `before` but was
639
- // built, and stored, at the drawn size. Its shape is nearer that drawn
640
- // size than the resized one on every resized axis, and its edit keeps
641
- // the old behaviour: rebuilt at the profile's own size.
642
- const nearerResized = (current, resized, factor) => Math.abs(factor - 1) < 1e-8 || Math.abs(current - resized) < Math.abs(current - resized / factor);
643
- const treatmentSourceScale = recordedTreatmentScale && treatmentSource
644
- && nearerResized(existing.width, treatmentSource.width, recordedTreatmentScale.width)
645
- && nearerResized(existing.depth, treatmentSource.depth, recordedTreatmentScale.depth)
646
- && nearerResized(existing.height, treatmentSource.height, recordedTreatmentScale.height)
647
- ? recordedTreatmentScale
648
- : undefined;
649
- const sourceFrame = existing.faceDraftSourceFrame ?? existing.draftPrismSourceFrame ?? existing.cadBrepFrame;
650
- const ratio = (drawn, source) => source && source > 0 && drawn > 0 ? drawn / source : 1;
651
- const recordedFaceDraftScale = (existing.faceDraft ? existing.faceDraftSourceScale : undefined) ?? (existing.faceDraft ? {
652
- // Editor-written drafts predate this field. Their output bounds
653
- // include the taper, so they cannot be used to infer the source
654
- // resize ratio; these shapes were only retained before resize support.
655
- width: 1, depth: 1, height: 1,
656
- } : {
657
- width: ratio(existing.width, sourceFrame?.width ?? existing.importedMesh?.baseWidth),
658
- depth: ratio(existing.depth, sourceFrame?.depth ?? existing.importedMesh?.baseDepth),
659
- height: ratio(existing.height, sourceFrame?.height ?? existing.importedMesh?.baseHeight),
660
- });
661
- // Height is unchanged by face drafting, so a later dimension edit can
662
- // be composed with the original scale without trying to infer scale
663
- // from the tapered width/depth bounds.
664
- const faceDraftSourceScale = existing.faceDraft && sourceFrame
665
- ? { ...recordedFaceDraftScale, height: ratio(existing.height, sourceFrame.height) }
666
- : recordedFaceDraftScale;
667
- const rebuildScale = existing.faceDraft || faceDraftChanged
668
- ? faceDraftSourceScale
669
- : treatmentSourceScale ?? { width: 1, depth: 1, height: 1 };
670
- // The extrusion is rebuilt at the height it was drawn and then scaled
671
- // by `rebuildScale`, as its width is. Rebuilding a height-resized
672
- // extrusion at its shown height applied that resize twice (#546).
673
- const sourceHeight = existing.draftPrismSourceHeight ?? existing.faceDraftSourceFrame?.height
674
- ?? (treatmentSourceScale ? treatmentSource.height / treatmentSourceScale.height
675
- : existing.height / rebuildScale.height);
676
- try {
677
- const rebuilt = await sketchExtrusionShapeFromRequest({
678
- id: existing.id,
679
- sketchSourceId: existing.sketchSourceId ?? `sketch/${existing.id}`,
680
- name: existing.name,
681
- color: existing.color,
682
- hole: existing.hole,
683
- profile: replacingSketchProfile ? changes.sketchProfile : existing.sketchProfile,
684
- height: sourceHeight,
685
- x: 0,
686
- z: 0,
687
- elevation: 0,
688
- rotation: existing.rotation,
689
- rotationX: existing.rotationX,
690
- rotationZ: existing.rotationZ,
857
+ else if (requestedFaceDraft) {
858
+ // The resolver the editor's draft, edit and replay call too (#384).
859
+ const { faceId: currentFaceId, normal: sourceFaceNormal, segmentMatch } = await withCadKernel((cad) => resolveRetainedFaceDraft(cad, {
860
+ existing,
861
+ source: replayedSource,
862
+ request: requestedFaceDraft,
863
+ profileChanged: replacingSketchProfile,
864
+ }, (kernel, shape) => orientedSolidForShape(kernel, unmirroredDraftSource(shape))));
865
+ const result = await applySketchFaceDraft(replayedSource, {
866
+ ...requestedFaceDraft,
867
+ sourceFaceId: currentFaceId,
691
868
  });
692
- const { faceIds: _oldFaceIds, faceColors: _faceColors, edgeTreatments: _edgeTreatments, edgeTreatmentHistory: _edgeTreatmentHistory, faceDraft: _faceDraft, cadDisplayEdges: _cadDisplayEdges, cadDisplayEdgesVersion: _cadDisplayEdgesVersion, ...sourceMetadata } = existing;
693
- const draftPrismAngle = draftPrismChanged ? requestedDraftPrismAngle : existing.draftPrismAngle;
694
- const rebuiltSource = {
695
- ...sourceMetadata,
696
- ...rebuilt,
697
- mirrorX: existing.mirrorX,
698
- mirrorY: existing.mirrorY,
699
- mirrorZ: existing.mirrorZ,
700
- ...retainedDraftSourcePlacement(existing, rebuilt.cadBrepFrame, existing.faceDraft && !hasExistingTreatment ? existing.cadBrepFrame : undefined),
701
- // A cleared draft's resize is not kept: the bounds carry it from here.
702
- faceDraftSourceScale: clearingFaceDraft ? undefined
703
- : existing.faceDraft || faceDraftChanged ? faceDraftSourceScale : existing.faceDraftSourceScale,
704
- width: rebuilt.width * rebuildScale.width,
705
- depth: rebuilt.depth * rebuildScale.depth,
706
- height: rebuilt.height * rebuildScale.height,
707
- size: Math.max(rebuilt.width * rebuildScale.width, rebuilt.depth * rebuildScale.depth),
708
- id: existing.id,
709
- sketchSourceId: existing.sketchSourceId ?? rebuilt.sketchSourceId,
710
- faceDraft: undefined,
711
- faceDraftSourceFrame: undefined,
712
- faceDraftSourceFaceIds: undefined,
713
- faceDraftSourceSegmentId: undefined,
714
- ...(faceDraftChanged && !replacingSketchProfile && !existing.faceDraft && !hasExistingTreatment
715
- && existing.draftPrismAngle === undefined && existing.faceIds?.length === rebuilt.faceIds?.length
716
- ? { faceIds: existing.faceIds }
717
- : {}),
718
- ...(!replacingSketchProfile && existing.faceDraft && existing.faceDraftSourceFaceIds?.length === rebuilt.faceIds?.length
719
- ? { faceIds: existing.faceDraftSourceFaceIds }
869
+ // The same record the editor writes for a draft it makes (#384).
870
+ const drafted = shapeWithCadResult(replayedSource, result);
871
+ swept = {
872
+ ...retainDraftSourceMirrors(drafted, replayedSource),
873
+ ...(!replayedSource.mirrorX && !replayedSource.mirrorY && !replayedSource.mirrorZ
874
+ ? retainedDraftSourcePlacement({
875
+ ...replayedSource,
876
+ faceDraftSourceFrame: undefined,
877
+ draftPrismSourceFrame: undefined,
878
+ }, drafted.cadBrepFrame)
720
879
  : {}),
721
- ...(draftPrismAngle === undefined ? {} : {
722
- draftPrismSourceHeight: sourceHeight,
723
- ...(sourceFrame ? { draftPrismSourceFrame: sourceFrame } : {}),
724
- }),
880
+ ...retainedFaceDraftFields(replayedSource.faceIds, existing, { faceId: currentFaceId, normal: sourceFaceNormal, segmentMatch }, requestedFaceDraft),
881
+ faceDraftSourceScale,
725
882
  };
726
- const hasRetainedTreatments = (existing.edgeTreatments?.length ?? 0) > 0
727
- || (existing.edgeTreatmentHistory?.length ?? 0) > 0;
728
- const replayDraftAndTreatment = hasRetainedTreatments
729
- && draftPrismAngle !== undefined
730
- && (replacingSketchProfile || clearingFaceDraft || draftPrismChanged);
731
- const replayFaceDraftAndTreatment = hasRetainedTreatments && faceDraftChanged && requestedFaceDraft !== undefined;
732
- const replayOriginal = clearingFaceDraft
733
- ? { ...existing, faceDraft: undefined }
734
- : replayFaceDraftAndTreatment && existing.faceDraft
735
- ? { ...existing, faceDraft: { ...existing.faceDraft, ...requestedFaceDraft } }
736
- : existing;
737
- const replayedSource = (replacingSketchProfile || clearingFaceDraft || draftPrismChanged || replayFaceDraftAndTreatment)
738
- && hasRetainedTreatments
739
- ? await replaySingleAllEdgeTreatment(replayOriginal, rebuiltSource, draftPrismChanged ? requestedDraftPrismAngle : undefined)
740
- : rebuiltSource;
741
- if (requestedFaceDraft && replayedSource.faceDraft) {
742
- swept = replayedSource;
743
- }
744
- else if (requestedFaceDraft) {
745
- // The resolver the editor's draft, edit and replay call too (#384).
746
- const { faceId: currentFaceId, normal: sourceFaceNormal, segmentMatch } = await withCadKernel((cad) => resolveRetainedFaceDraft(cad, {
747
- existing,
748
- source: replayedSource,
749
- request: requestedFaceDraft,
750
- profileChanged: replacingSketchProfile,
751
- }, (kernel, shape) => orientedSolidForShape(kernel, unmirroredDraftSource(shape))));
752
- const result = await applySketchFaceDraft(replayedSource, {
753
- ...requestedFaceDraft,
754
- sourceFaceId: currentFaceId,
755
- });
756
- // The same record the editor writes for a draft it makes (#384).
757
- const drafted = shapeWithCadResult(replayedSource, result);
758
- swept = {
759
- ...retainDraftSourceMirrors(drafted, replayedSource),
760
- ...(!replayedSource.mirrorX && !replayedSource.mirrorY && !replayedSource.mirrorZ
761
- ? retainedDraftSourcePlacement({
762
- ...replayedSource,
763
- faceDraftSourceFrame: undefined,
764
- draftPrismSourceFrame: undefined,
765
- }, drafted.cadBrepFrame)
766
- : {}),
767
- ...retainedFaceDraftFields(replayedSource.faceIds, existing, { faceId: currentFaceId, normal: sourceFaceNormal, segmentMatch }, requestedFaceDraft),
768
- faceDraftSourceScale,
769
- };
770
- }
771
- else if (draftPrismAngle !== undefined && !replayDraftAndTreatment) {
772
- swept = {
773
- ...retainDraftSourceMirrors(shapeWithCadResult(replayedSource, await applyDraftPrism(replayedSource, { angle: draftPrismAngle })), replayedSource),
774
- draftPrismAngle,
775
- };
776
- }
777
- else {
778
- swept = replayedSource;
883
+ }
884
+ else if (draftPrismAngle !== undefined && !replayDraftAndTreatment) {
885
+ swept = {
886
+ ...retainDraftSourceMirrors(shapeWithCadResult(replayedSource, await applyDraftPrism(replayedSource, { angle: draftPrismAngle })), replayedSource),
887
+ draftPrismAngle,
888
+ };
889
+ }
890
+ else {
891
+ swept = replayedSource;
892
+ }
893
+ }
894
+ catch (error) {
895
+ return failed({ reason: "sweep_failed", message: error instanceof Error ? error.message : "The sketch extrusion could not be rebuilt." });
896
+ }
897
+ }
898
+ if ((replacingSketchProfile || faceDraftChanged) && isSketchSweep) {
899
+ const profileToBuild = replacingSketchProfile ? changes.sketchProfile : existing.sketchProfile;
900
+ const invalidProfile = replacingSketchProfile ? invalidSketchSweepProfile(profileToBuild) : undefined;
901
+ if (invalidProfile)
902
+ return failed({ reason: "invalid_shape_request", message: invalidProfile });
903
+ const frame = existing.faceDraftSourceFrame ?? existing.cadBrepFrame;
904
+ try {
905
+ const rebuilt = await sketchSweepShapeFromRequest({
906
+ id: existing.id,
907
+ name: existing.name,
908
+ color: existing.color,
909
+ hole: existing.hole,
910
+ profile: profileToBuild,
911
+ x: existing.x - (frame?.x ?? 0),
912
+ z: existing.z - (frame?.z ?? 0),
913
+ elevation: (existing.elevation ?? 0) - (frame?.elevation ?? 0),
914
+ rotation: existing.rotation,
915
+ rotationX: existing.rotationX,
916
+ rotationZ: existing.rotationZ,
917
+ });
918
+ const baseDimensions = {
919
+ width: frame?.width ?? existing.importedMesh?.baseWidth ?? existing.width,
920
+ depth: frame?.depth ?? existing.importedMesh?.baseDepth ?? existing.depth,
921
+ height: frame?.height ?? existing.importedMesh?.baseHeight ?? existing.height,
922
+ };
923
+ const resized = {
924
+ ...rebuilt,
925
+ width: rebuilt.width * existing.width / Math.max(0.01, baseDimensions.width),
926
+ depth: rebuilt.depth * existing.depth / Math.max(0.01, baseDimensions.depth),
927
+ height: rebuilt.height * existing.height / Math.max(0.01, baseDimensions.height),
928
+ };
929
+ resized.size = Math.max(resized.width, resized.depth);
930
+ const refreshedFaceIds = (await shapeFaces(rebuilt))
931
+ .map((face) => `face_${createLocalId(`${existing.id}-${face.index}`)}`);
932
+ const { faceIds: _oldFaceIds, faceColors: _faceColors, edgeTreatments: _edgeTreatments, edgeTreatmentHistory: _edgeTreatmentHistory, cadDisplayEdges: _cadDisplayEdges, cadDisplayEdgesVersion: _cadDisplayEdgesVersion, faceDraft: _faceDraft, faceDraftSourceFrame: _faceDraftSourceFrame, ...sourceMetadata } = existing;
933
+ const rebuiltSweep = {
934
+ ...sourceMetadata,
935
+ ...resized,
936
+ mirrorX: existing.mirrorX,
937
+ mirrorY: existing.mirrorY,
938
+ mirrorZ: existing.mirrorZ,
939
+ id: existing.id,
940
+ sketchSourceId: existing.sketchSourceId ?? rebuilt.sketchSourceId,
941
+ faceIds: refreshedFaceIds,
942
+ faceDraft: undefined,
943
+ faceDraftSourceFrame: undefined,
944
+ };
945
+ const hasRetainedTreatments = (existing.edgeTreatments?.length ?? 0) > 0
946
+ || (existing.edgeTreatmentHistory?.length ?? 0) > 0;
947
+ const replayFaceDraftAndTreatment = hasRetainedTreatments && faceDraftChanged && requestedFaceDraft !== undefined;
948
+ const replayOriginal = clearingFaceDraft
949
+ ? { ...existing, faceDraft: undefined }
950
+ : replayFaceDraftAndTreatment && existing.faceDraft
951
+ ? { ...existing, faceDraft: { ...existing.faceDraft, ...requestedFaceDraft } }
952
+ : existing;
953
+ const replayedSource = (replacingSketchProfile || clearingFaceDraft || replayFaceDraftAndTreatment) && hasRetainedTreatments
954
+ ? await replaySingleAllEdgeTreatment(replayOriginal, rebuiltSweep)
955
+ : rebuiltSweep;
956
+ if (requestedFaceDraft && replayedSource.faceDraft) {
957
+ // `replaySingleAllEdgeTreatment` has already rebuilt the retained
958
+ // draft before its treatment; applying the draft again would try
959
+ // to operate on post-fillet topology and make source edits fail.
960
+ swept = replayedSource;
961
+ }
962
+ else if (requestedFaceDraft) {
963
+ const priorReference = existing.faceDraft?.sourceFaceId === requestedFaceDraft.sourceFaceId
964
+ ? existing.faceDraft.sourceFaceNormal
965
+ : undefined;
966
+ const selectedOnPrior = priorReference ? undefined
967
+ : (await shapeFaces(unmirroredDraftSource(existing), isExactSketchRevolve ? { topology: "exact" } : undefined))
968
+ .find((face) => face.id === requestedFaceDraft.sourceFaceId);
969
+ const sourceFaceNormal = priorReference ?? selectedOnPrior?.normal;
970
+ if (!sourceFaceNormal || selectedOnPrior && selectedOnPrior.surfaceType !== "plane") {
971
+ throw new Error("The selected source face has no stable planar reference.");
779
972
  }
973
+ const currentFace = await findUniqueDraftFace(unmirroredDraftSource(replayedSource), sourceFaceNormal);
974
+ if (!currentFace)
975
+ throw new Error("The selected source face is missing or ambiguous after the sketch edit.");
976
+ const faceDraft = { ...requestedFaceDraft, sourceFaceNormal };
977
+ const result = await applySketchFaceDraft(replayedSource, {
978
+ ...requestedFaceDraft,
979
+ sourceFaceId: currentFace.id,
980
+ });
981
+ swept = {
982
+ ...retainDraftSourceMirrors(shapeWithCadResult(replayedSource, result), replayedSource),
983
+ faceDraft,
984
+ faceDraftSourceFrame: existing.faceDraftSourceFrame ?? existing.cadBrepFrame,
985
+ };
780
986
  }
781
- catch (error) {
782
- return failed({ reason: "sweep_failed", message: error instanceof Error ? error.message : "The sketch extrusion could not be rebuilt." });
987
+ else {
988
+ swept = replayedSource;
783
989
  }
784
990
  }
785
- if ((replacingSketchProfile || faceDraftChanged) && isSketchSweep) {
786
- const profileToBuild = replacingSketchProfile ? changes.sketchProfile : existing.sketchProfile;
787
- const invalidProfile = replacingSketchProfile ? invalidSketchSweepProfile(profileToBuild) : undefined;
788
- if (invalidProfile)
789
- return failed({ reason: "invalid_shape_request", message: invalidProfile });
790
- const frame = existing.faceDraftSourceFrame ?? existing.cadBrepFrame;
791
- try {
792
- const rebuilt = await sketchSweepShapeFromRequest({
793
- id: existing.id,
794
- name: existing.name,
795
- color: existing.color,
796
- hole: existing.hole,
797
- profile: profileToBuild,
798
- x: existing.x - (frame?.x ?? 0),
799
- z: existing.z - (frame?.z ?? 0),
800
- elevation: (existing.elevation ?? 0) - (frame?.elevation ?? 0),
801
- rotation: existing.rotation,
802
- rotationX: existing.rotationX,
803
- rotationZ: existing.rotationZ,
991
+ catch (error) {
992
+ return failed({
993
+ reason: "sweep_failed",
994
+ message: error instanceof Error ? error.message : "The sketch sweep could not be rebuilt",
995
+ });
996
+ }
997
+ }
998
+ if ((faceDraftChanged || (replacingSketchProfile && existing.faceDraft)
999
+ || (revolveChanges.length > 0 && existing.faceDraft)) && isSketchRevolve) {
1000
+ try {
1001
+ const runtime = await serverManifoldRuntime();
1002
+ const sourceFrame = existing.faceDraftSourceFrame ?? existing.cadBrepFrame;
1003
+ const rebuildSeed = sourceFrame ? {
1004
+ ...existing,
1005
+ x: sourceFrame.x,
1006
+ z: sourceFrame.z,
1007
+ elevation: sourceFrame.elevation,
1008
+ } : existing;
1009
+ const rebuiltAtNaturalScale = rebuiltRevolveShape(runtime, rebuildSeed, {
1010
+ profile: (replacingSketchProfile ? changes.sketchProfile : existing.sketchProfile),
1011
+ settings: revolveChanges.length > 0
1012
+ ? requestedRevolveSettings(existing.sketchRevolve, changes)
1013
+ : existing.sketchRevolve,
1014
+ });
1015
+ const sourceScale = existing.faceDraftSourceScale ?? revolveSourceScale(existing);
1016
+ const rebuilt = resizeRebuiltRevolve(rebuiltAtNaturalScale, sourceScale);
1017
+ if (requestedFaceDraft) {
1018
+ const exactBase = {
1019
+ ...retainDraftSourceMirrors(shapeWithCadResult(rebuilt, await exactPlainSketchRevolveResult(rebuilt)), rebuilt),
1020
+ faceDraftSourceScale: sourceScale,
1021
+ };
1022
+ const priorReference = existing.faceDraft?.sourceFaceId === requestedFaceDraft.sourceFaceId
1023
+ ? existing.faceDraft.sourceFaceNormal
1024
+ : undefined;
1025
+ const selectedOnPrior = priorReference ? undefined
1026
+ : (await shapeFaces(unmirroredDraftSource(existing), { topology: "exact" }))
1027
+ .find((face) => face.id === requestedFaceDraft.sourceFaceId);
1028
+ const sourceFaceNormal = priorReference ?? selectedOnPrior?.normal;
1029
+ if (!sourceFaceNormal || selectedOnPrior && selectedOnPrior.surfaceType !== "plane") {
1030
+ throw new Error("The selected source face has no stable planar reference.");
1031
+ }
1032
+ const currentFace = await findUniqueDraftFace(unmirroredDraftSource(exactBase), sourceFaceNormal);
1033
+ if (!currentFace)
1034
+ throw new Error("The selected source face is missing or ambiguous after the sketch edit.");
1035
+ const faceDraft = { ...requestedFaceDraft, sourceFaceNormal };
1036
+ const result = await applySketchFaceDraft(exactBase, {
1037
+ ...requestedFaceDraft,
1038
+ sourceFaceId: currentFace.id,
804
1039
  });
805
- const baseDimensions = {
806
- width: frame?.width ?? existing.importedMesh?.baseWidth ?? existing.width,
807
- depth: frame?.depth ?? existing.importedMesh?.baseDepth ?? existing.depth,
808
- height: frame?.height ?? existing.importedMesh?.baseHeight ?? existing.height,
1040
+ swept = {
1041
+ ...retainDraftSourceMirrors(shapeWithCadResult(exactBase, result), exactBase),
1042
+ faceDraft,
1043
+ faceDraftSourceFrame: existing.faceDraftSourceFrame ?? existing.cadBrepFrame ?? exactBase.cadBrepFrame,
1044
+ faceDraftSourceScale: sourceScale,
809
1045
  };
810
- const resized = {
1046
+ swept = await replaySingleAllEdgeTreatment(existing, swept);
1047
+ }
1048
+ else {
1049
+ const clearedDraft = {
811
1050
  ...rebuilt,
812
- width: rebuilt.width * existing.width / Math.max(0.01, baseDimensions.width),
813
- depth: rebuilt.depth * existing.depth / Math.max(0.01, baseDimensions.depth),
814
- height: rebuilt.height * existing.height / Math.max(0.01, baseDimensions.height),
815
- };
816
- resized.size = Math.max(resized.width, resized.depth);
817
- const refreshedFaceIds = (await shapeFaces(rebuilt))
818
- .map((face) => `face_${createLocalId(`${existing.id}-${face.index}`)}`);
819
- const { faceIds: _oldFaceIds, faceColors: _faceColors, edgeTreatments: _edgeTreatments, edgeTreatmentHistory: _edgeTreatmentHistory, cadDisplayEdges: _cadDisplayEdges, cadDisplayEdgesVersion: _cadDisplayEdgesVersion, faceDraft: _faceDraft, faceDraftSourceFrame: _faceDraftSourceFrame, ...sourceMetadata } = existing;
820
- const rebuiltSweep = {
821
- ...sourceMetadata,
822
- ...resized,
823
- mirrorX: existing.mirrorX,
824
- mirrorY: existing.mirrorY,
825
- mirrorZ: existing.mirrorZ,
826
- id: existing.id,
827
- sketchSourceId: existing.sketchSourceId ?? rebuilt.sketchSourceId,
828
- faceIds: refreshedFaceIds,
829
1051
  faceDraft: undefined,
830
1052
  faceDraftSourceFrame: undefined,
1053
+ faceDraftSourceScale: undefined,
831
1054
  };
832
- const hasRetainedTreatments = (existing.edgeTreatments?.length ?? 0) > 0
833
- || (existing.edgeTreatmentHistory?.length ?? 0) > 0;
834
- const replayFaceDraftAndTreatment = hasRetainedTreatments && faceDraftChanged && requestedFaceDraft !== undefined;
835
- const replayOriginal = clearingFaceDraft
836
- ? { ...existing, faceDraft: undefined }
837
- : replayFaceDraftAndTreatment && existing.faceDraft
838
- ? { ...existing, faceDraft: { ...existing.faceDraft, ...requestedFaceDraft } }
839
- : existing;
840
- const replayedSource = (replacingSketchProfile || clearingFaceDraft || replayFaceDraftAndTreatment) && hasRetainedTreatments
841
- ? await replaySingleAllEdgeTreatment(replayOriginal, rebuiltSweep)
842
- : rebuiltSweep;
843
- if (requestedFaceDraft && replayedSource.faceDraft) {
844
- // `replaySingleAllEdgeTreatment` has already rebuilt the retained
845
- // draft before its treatment; applying the draft again would try
846
- // to operate on post-fillet topology and make source edits fail.
847
- swept = replayedSource;
848
- }
849
- else if (requestedFaceDraft) {
850
- const priorReference = existing.faceDraft?.sourceFaceId === requestedFaceDraft.sourceFaceId
851
- ? existing.faceDraft.sourceFaceNormal
852
- : undefined;
853
- const selectedOnPrior = priorReference ? undefined
854
- : (await shapeFaces(unmirroredDraftSource(existing), isExactSketchRevolve ? { topology: "exact" } : undefined))
855
- .find((face) => face.id === requestedFaceDraft.sourceFaceId);
856
- const sourceFaceNormal = priorReference ?? selectedOnPrior?.normal;
857
- if (!sourceFaceNormal || selectedOnPrior && selectedOnPrior.surfaceType !== "plane") {
858
- throw new Error("The selected source face has no stable planar reference.");
859
- }
860
- const currentFace = await findUniqueDraftFace(unmirroredDraftSource(replayedSource), sourceFaceNormal);
861
- if (!currentFace)
862
- throw new Error("The selected source face is missing or ambiguous after the sketch edit.");
863
- const faceDraft = { ...requestedFaceDraft, sourceFaceNormal };
864
- const result = await applySketchFaceDraft(replayedSource, {
865
- ...requestedFaceDraft,
866
- sourceFaceId: currentFace.id,
867
- });
868
- swept = {
869
- ...retainDraftSourceMirrors(shapeWithCadResult(replayedSource, result), replayedSource),
870
- faceDraft,
871
- faceDraftSourceFrame: existing.faceDraftSourceFrame ?? existing.cadBrepFrame,
872
- };
873
- }
874
- else {
875
- swept = replayedSource;
876
- }
877
- }
878
- catch (error) {
879
- return failed({
880
- reason: "sweep_failed",
881
- message: error instanceof Error ? error.message : "The sketch sweep could not be rebuilt",
882
- });
1055
+ swept = clearingFaceDraft
1056
+ ? await replaySingleAllEdgeTreatment({ ...existing, faceDraft: undefined }, clearedDraft)
1057
+ : clearedDraft;
883
1058
  }
884
1059
  }
885
- if ((faceDraftChanged || (replacingSketchProfile && existing.faceDraft)
886
- || (revolveChanges.length > 0 && existing.faceDraft)) && isSketchRevolve) {
1060
+ catch (error) {
1061
+ return failed({
1062
+ reason: "sweep_failed",
1063
+ message: error instanceof Error ? error.message : "The sketch revolve could not be rebuilt.",
1064
+ });
1065
+ }
1066
+ }
1067
+ else if (replacingSketchProfile && isSketchRevolve) {
1068
+ try {
1069
+ const runtime = await serverManifoldRuntime();
1070
+ const rebuilt = rebuiltRevolveShape(runtime, existing, {
1071
+ profile: changes.sketchProfile,
1072
+ settings: existing.sketchRevolve,
1073
+ });
1074
+ swept = await replaySingleAllEdgeTreatment(existing, rebuilt);
1075
+ }
1076
+ catch (error) {
1077
+ return failed({
1078
+ reason: "sweep_failed",
1079
+ message: error instanceof Error ? error.message : "The sketch revolve could not be rebuilt.",
1080
+ });
1081
+ }
1082
+ }
1083
+ if (revolveChanges.length > 0 && sweptShape && !existing.faceDraft) {
1084
+ const outline = changes.profile ?? changes.outline ?? outlineFromProfile(existing.sketchProfile);
1085
+ if (!outline) {
1086
+ return failed({
1087
+ reason: "unapplicable_fields",
1088
+ kind: existing.kind,
1089
+ fields: [...revolveChanges],
1090
+ because: "outline_not_described",
1091
+ });
1092
+ }
1093
+ const parsed = parseRevolveRequest({ profile: outline });
1094
+ if (!parsed.ok)
1095
+ return failed({ reason: "invalid_shape_request", message: parsed.error });
1096
+ try {
1097
+ const runtime = await serverManifoldRuntime();
1098
+ const rebuilt = rebuiltRevolveShape(runtime, existing, {
1099
+ profile: parsed.profile,
1100
+ settings: requestedRevolveSettings(existing.sketchRevolve, changes),
1101
+ });
1102
+ swept = await replaySingleAllEdgeTreatment(existing, rebuilt);
1103
+ }
1104
+ catch (error) {
1105
+ return failed({
1106
+ reason: "sweep_failed",
1107
+ message: error instanceof Error ? error.message : "The revolve could not be rebuilt",
1108
+ });
1109
+ }
1110
+ }
1111
+ // The sweep's own fields are already applied, so they are kept out of the
1112
+ // per-kind pass -- which would refuse them, the stored kind being `mesh`.
1113
+ const sweepFields = [
1114
+ ...(sweptShape ? REVOLVE_CHANGE_FIELDS : REVOLVE_ONLY_FIELDS),
1115
+ "sketchProfile",
1116
+ "draftPrismAngle",
1117
+ "faceDraft",
1118
+ ];
1119
+ // Shape summaries expose the source ID for identity; echoing a full
1120
+ // summary into PATCH must not let callers replace that identity.
1121
+ let requestedChanges = Object.fromEntries(Object.entries(changes).filter(([field]) => field !== "sketchSourceId"
1122
+ && field !== "faceIds"
1123
+ && !(replacingSketchProfile && field === "faceColors")
1124
+ && !sweepFields.includes(field)));
1125
+ let changeBase = swept;
1126
+ if (!replacingSketchProfile && changes.faceColors && typeof changes.faceColors === "object" && !Array.isArray(changes.faceColors)) {
1127
+ const colors = changes.faceColors;
1128
+ if (Object.keys(colors).some((key) => !/^\d+$/.test(key))) {
887
1129
  try {
888
- const runtime = await serverManifoldRuntime();
889
- const sourceFrame = existing.faceDraftSourceFrame ?? existing.cadBrepFrame;
890
- const rebuildSeed = sourceFrame ? {
891
- ...existing,
892
- x: sourceFrame.x,
893
- z: sourceFrame.z,
894
- elevation: sourceFrame.elevation,
895
- } : existing;
896
- const rebuiltAtNaturalScale = rebuiltRevolveShape(runtime, rebuildSeed, {
897
- profile: (replacingSketchProfile ? changes.sketchProfile : existing.sketchProfile),
898
- settings: revolveChanges.length > 0
899
- ? requestedRevolveSettings(existing.sketchRevolve, changes)
900
- : existing.sketchRevolve,
901
- });
902
- const sourceScale = existing.faceDraftSourceScale ?? revolveSourceScale(existing);
903
- const rebuilt = resizeRebuiltRevolve(rebuiltAtNaturalScale, sourceScale);
904
- if (requestedFaceDraft) {
905
- const exactBase = {
906
- ...retainDraftSourceMirrors(shapeWithCadResult(rebuilt, await exactPlainSketchRevolveResult(rebuilt)), rebuilt),
907
- faceDraftSourceScale: sourceScale,
908
- };
909
- const priorReference = existing.faceDraft?.sourceFaceId === requestedFaceDraft.sourceFaceId
910
- ? existing.faceDraft.sourceFaceNormal
911
- : undefined;
912
- const selectedOnPrior = priorReference ? undefined
913
- : (await shapeFaces(unmirroredDraftSource(existing), { topology: "exact" }))
914
- .find((face) => face.id === requestedFaceDraft.sourceFaceId);
915
- const sourceFaceNormal = priorReference ?? selectedOnPrior?.normal;
916
- if (!sourceFaceNormal || selectedOnPrior && selectedOnPrior.surfaceType !== "plane") {
917
- throw new Error("The selected source face has no stable planar reference.");
918
- }
919
- const currentFace = await findUniqueDraftFace(unmirroredDraftSource(exactBase), sourceFaceNormal);
920
- if (!currentFace)
921
- throw new Error("The selected source face is missing or ambiguous after the sketch edit.");
922
- const faceDraft = { ...requestedFaceDraft, sourceFaceNormal };
923
- const result = await applySketchFaceDraft(exactBase, {
924
- ...requestedFaceDraft,
925
- sourceFaceId: currentFace.id,
926
- });
927
- swept = {
928
- ...retainDraftSourceMirrors(shapeWithCadResult(exactBase, result), exactBase),
929
- faceDraft,
930
- faceDraftSourceFrame: existing.faceDraftSourceFrame ?? existing.cadBrepFrame ?? exactBase.cadBrepFrame,
931
- faceDraftSourceScale: sourceScale,
932
- };
933
- swept = await replaySingleAllEdgeTreatment(existing, swept);
934
- }
935
- else {
936
- const clearedDraft = {
937
- ...rebuilt,
938
- faceDraft: undefined,
939
- faceDraftSourceFrame: undefined,
940
- faceDraftSourceScale: undefined,
941
- };
942
- swept = clearingFaceDraft
943
- ? await replaySingleAllEdgeTreatment({ ...existing, faceDraft: undefined }, clearedDraft)
944
- : clearedDraft;
1130
+ const faces = await shapeFaces(existing);
1131
+ const faceIds = existing.faceIds ?? faces.map((face) => face.id);
1132
+ const known = new Set(faceIds);
1133
+ if (Object.keys(colors).some((key) => !/^\d+$/.test(key) && !known.has(key))) {
1134
+ return failed({ reason: "invalid_shape_request", message: "A face color references an unknown face ID." });
945
1135
  }
1136
+ changeBase = { ...swept, faceIds };
1137
+ requestedChanges = {
1138
+ ...requestedChanges,
1139
+ faceColors: Object.fromEntries(Object.entries(colors).map(([key, color]) => [
1140
+ /^\d+$/.test(key) ? (faceIds[Number(key)] ?? key) : key,
1141
+ color,
1142
+ ])),
1143
+ };
946
1144
  }
947
1145
  catch (error) {
948
- return failed({
949
- reason: "sweep_failed",
950
- message: error instanceof Error ? error.message : "The sketch revolve could not be rebuilt.",
951
- });
1146
+ return failed(cadFailure(error));
952
1147
  }
953
1148
  }
954
- else if (replacingSketchProfile && isSketchRevolve) {
955
- try {
956
- const runtime = await serverManifoldRuntime();
957
- const rebuilt = rebuiltRevolveShape(runtime, existing, {
958
- profile: changes.sketchProfile,
959
- settings: existing.sketchRevolve,
960
- });
961
- swept = await replaySingleAllEdgeTreatment(existing, rebuilt);
962
- }
963
- catch (error) {
964
- return failed({
965
- reason: "sweep_failed",
966
- message: error instanceof Error ? error.message : "The sketch revolve could not be rebuilt.",
967
- });
968
- }
1149
+ }
1150
+ const changed = shapeWithRequestedChanges(changeBase, Object.fromEntries(Object.entries(requestedChanges)));
1151
+ if (!changed.ok) {
1152
+ return failed({
1153
+ reason: "unapplicable_fields",
1154
+ kind: existing.kind,
1155
+ fields: changed.unapplicable,
1156
+ because: "not_this_kind",
1157
+ });
1158
+ }
1159
+ const geometryFields = ["width", "depth", "height", "size", ...Object.keys(SHAPE_PARAMETERS)];
1160
+ const geometryChanged = geometryFields.some((field) => JSON.stringify(existing[field])
1161
+ !== JSON.stringify(changed.shape[field]));
1162
+ let updatedShape = changed.shape;
1163
+ if (existing.kind === "mesh" && existing.importedMesh && !existing.cadBrep
1164
+ && ["rotation", "rotationX", "rotationZ"].some((field) => field in requestedChanges)) {
1165
+ const previousMesh = worldMeshForShape(existing);
1166
+ const mesh = worldMeshForShape(updatedShape);
1167
+ if (previousMesh?.vertices.length && mesh?.vertices.length) {
1168
+ const lowestPointOf = (vertices) => vertices.reduce((lowest, [, y]) => Math.min(lowest, y), Number.POSITIVE_INFINITY);
1169
+ const previousLowestPoint = lowestPointOf(previousMesh.vertices);
1170
+ const lowestPoint = lowestPointOf(mesh.vertices);
1171
+ const targetElevation = typeof requestedChanges.elevation === "number"
1172
+ ? requestedChanges.elevation
1173
+ : previousLowestPoint;
1174
+ updatedShape = {
1175
+ ...updatedShape,
1176
+ elevation: (updatedShape.elevation ?? 0) + targetElevation - lowestPoint,
1177
+ };
969
1178
  }
970
- if (revolveChanges.length > 0 && sweptShape && !existing.faceDraft) {
971
- const outline = changes.profile ?? changes.outline ?? outlineFromProfile(existing.sketchProfile);
972
- if (!outline) {
973
- return failed({
974
- reason: "unapplicable_fields",
975
- kind: existing.kind,
976
- fields: [...revolveChanges],
977
- because: "outline_not_described",
978
- });
979
- }
980
- const parsed = parseRevolveRequest({ profile: outline });
981
- if (!parsed.ok)
982
- return failed({ reason: "invalid_shape_request", message: parsed.error });
983
- try {
984
- const runtime = await serverManifoldRuntime();
985
- const rebuilt = rebuiltRevolveShape(runtime, existing, {
986
- profile: parsed.profile,
987
- settings: requestedRevolveSettings(existing.sketchRevolve, changes),
988
- });
989
- swept = await replaySingleAllEdgeTreatment(existing, rebuilt);
990
- }
991
- catch (error) {
992
- return failed({
993
- reason: "sweep_failed",
994
- message: error instanceof Error ? error.message : "The revolve could not be rebuilt",
995
- });
996
- }
1179
+ }
1180
+ if (!replacingSketchProfile && geometryChanged && (existing.faceIds?.length || existing.faceColors)) {
1181
+ try {
1182
+ updatedShape = await preserveUnambiguousFaceMetadata(existing, changed.shape);
997
1183
  }
998
- // The sweep's own fields are already applied, so they are kept out of the
999
- // per-kind pass -- which would refuse them, the stored kind being `mesh`.
1000
- const sweepFields = [
1001
- ...(sweptShape ? REVOLVE_CHANGE_FIELDS : REVOLVE_ONLY_FIELDS),
1002
- "sketchProfile",
1003
- "draftPrismAngle",
1004
- "faceDraft",
1005
- ];
1006
- // Shape summaries expose the source ID for identity; echoing a full
1007
- // summary into PATCH must not let callers replace that identity.
1008
- let requestedChanges = Object.fromEntries(Object.entries(changes).filter(([field]) => field !== "sketchSourceId"
1009
- && field !== "faceIds"
1010
- && !(replacingSketchProfile && field === "faceColors")
1011
- && !sweepFields.includes(field)));
1012
- let changeBase = swept;
1013
- if (!replacingSketchProfile && changes.faceColors && typeof changes.faceColors === "object" && !Array.isArray(changes.faceColors)) {
1014
- const colors = changes.faceColors;
1015
- if (Object.keys(colors).some((key) => !/^\d+$/.test(key))) {
1016
- try {
1017
- const faces = await shapeFaces(existing);
1018
- const faceIds = existing.faceIds ?? faces.map((face) => face.id);
1019
- const known = new Set(faceIds);
1020
- if (Object.keys(colors).some((key) => !/^\d+$/.test(key) && !known.has(key))) {
1021
- return failed({ reason: "invalid_shape_request", message: "A face color references an unknown face ID." });
1022
- }
1023
- changeBase = { ...swept, faceIds };
1024
- requestedChanges = {
1025
- ...requestedChanges,
1026
- faceColors: Object.fromEntries(Object.entries(colors).map(([key, color]) => [
1027
- /^\d+$/.test(key) ? (faceIds[Number(key)] ?? key) : key,
1028
- color,
1029
- ])),
1030
- };
1031
- }
1032
- catch (error) {
1033
- return failed(cadFailure(error));
1184
+ catch (error) {
1185
+ return failed(cadFailure(error));
1186
+ }
1187
+ }
1188
+ if (sourceSketchTarget) {
1189
+ const candidate = replaceSketchOutput(document.shapes, shapeId, updatedShape);
1190
+ if (candidate.matchCount !== 1) {
1191
+ return failed({
1192
+ reason: "sweep_failed",
1193
+ message: candidate.matchCount === 0
1194
+ ? `Sketch source ${shapeId} has no output node.`
1195
+ : `Sketch source ${shapeId} has multiple output nodes.`,
1196
+ });
1197
+ }
1198
+ const recomputed = await recompute({ ...document, shapes: candidate.shapes }, [shapeId], document);
1199
+ if (!recomputed.ok) {
1200
+ return failed({
1201
+ reason: "sweep_failed",
1202
+ message: recomputed.message ?? (recomputed.reason === "dependency_ambiguous"
1203
+ ? "The sketch source has multiple dependent outputs."
1204
+ : "The sketch source has no dependent output."),
1205
+ });
1206
+ }
1207
+ return ok({ shape: recomputed.updated, shapes: recomputed.shapes });
1208
+ }
1209
+ const shapes = document.shapes.map((shape) => (shape.id === existing.id ? updatedShape : shape));
1210
+ return ok({ shape: updatedShape, shapes });
1211
+ }
1212
+ /** Re-applies bound placement on the group around nested `shapeId` after a rebuild refit it. */
1213
+ async function restoreRootPlacement(document, previous, shapes, shapeId) {
1214
+ const before = previous.find((root) => root.id !== shapeId && findShapeInTree([root], shapeId));
1215
+ const after = before && shapes.find((root) => root.id === before.id);
1216
+ const drift = after ? driftedPlacement(before, after) : {};
1217
+ if (!Object.keys(drift).length)
1218
+ return ok(shapes);
1219
+ const placed = await changeShapeIn({ ...document, shapes }, after.id, drift);
1220
+ return placed.ok ? ok(placed.value.shapes) : placed;
1221
+ }
1222
+ /** Rebuilds a sketch output with new treatment settings through the recompute graph. */
1223
+ async function retreatSketchOutput(document, shape, values) {
1224
+ const sourceId = shape.sketchSourceId;
1225
+ const tune = (feature) => ({
1226
+ ...feature,
1227
+ ...(values["edgeTreatments.0.amount"] !== undefined ? { amount: values["edgeTreatments.0.amount"] } : {}),
1228
+ ...(values["edgeTreatments.0.chamferAngle"] !== undefined ? { chamferAngle: values["edgeTreatments.0.chamferAngle"] } : {}),
1229
+ });
1230
+ const recipe = {
1231
+ ...shape,
1232
+ edgeTreatments: shape.edgeTreatments.map((feature, index) => (index === 0 ? tune(feature) : feature)),
1233
+ ...(shape.edgeTreatmentHistory ? {
1234
+ edgeTreatmentHistory: shape.edgeTreatmentHistory.map((entry, index) => (index === 0 ? { ...entry, feature: tune(entry.feature) } : entry)),
1235
+ } : {}),
1236
+ };
1237
+ const candidate = replaceSketchOutput(document.shapes, sourceId, recipe);
1238
+ if (candidate.matchCount !== 1)
1239
+ return failed({ reason: "sweep_failed", message: `Sketch source ${sourceId} has no unique output node.` });
1240
+ const recomputed = await recompute({ ...document, shapes: candidate.shapes }, [sourceId], document);
1241
+ if (!recomputed.ok)
1242
+ return failed({ reason: "sweep_failed", message: recomputed.message ?? "The treatment could not be replayed." });
1243
+ return ok({ shape: recomputed.updated, shapes: recomputed.shapes });
1244
+ }
1245
+ /**
1246
+ * Applies resolved values to one shape through the manual-edit paths:
1247
+ * a solved sketch profile, treatment settings, sketch-source features, then the shape's own fields.
1248
+ */
1249
+ async function applyBindingValues(document, shapeId, values, sketchProfile) {
1250
+ let shapes = document.shapes;
1251
+ const initial = findShapeInTree(shapes, shapeId);
1252
+ if (!initial)
1253
+ return failed({ reason: "shapes_not_found", ids: [shapeId] });
1254
+ const fields = Object.keys(values);
1255
+ const pick = (accept) => Object.fromEntries(fields.filter(accept).map((field) => [field, values[field]]));
1256
+ const treatment = pick((field) => TREATMENT_BINDINGS.has(field));
1257
+ const feature = pick((field) => !TREATMENT_BINDINGS.has(field) && bindableField(initial.shape, field)?.target === "feature");
1258
+ const own = pick((field) => !(field in treatment) && !(field in feature));
1259
+ const step = async (run) => {
1260
+ const found = findShapeInTree(shapes, shapeId);
1261
+ if (!found)
1262
+ return failed({ reason: "shapes_not_found", ids: [shapeId] });
1263
+ const changed = await run(found.shape, found.topLevel);
1264
+ if (changed.ok)
1265
+ shapes = changed.value.shapes;
1266
+ return changed;
1267
+ };
1268
+ if (sketchProfile) {
1269
+ const result = await step(async (shape, topLevel) => {
1270
+ const target = shape.sketchSourceId ?? (topLevel ? shape.id : undefined);
1271
+ if (!target)
1272
+ return failed({ reason: "shapes_not_found", ids: [shapeId] });
1273
+ return changeShapeIn({ ...document, shapes }, target, { sketchProfile });
1274
+ });
1275
+ if (!result.ok)
1276
+ return result;
1277
+ }
1278
+ if (Object.keys(treatment).length) {
1279
+ const result = await step((shape) => retreatSketchOutput({ ...document, shapes }, shape, treatment));
1280
+ if (!result.ok)
1281
+ return result;
1282
+ }
1283
+ if (Object.keys(feature).length) {
1284
+ const result = await step(async (shape, topLevel) => {
1285
+ const request = {};
1286
+ for (const [field, number] of Object.entries(feature)) {
1287
+ if (field.startsWith("revolve."))
1288
+ request[field.slice("revolve.".length)] = number;
1289
+ else if (field === "faceDraft.angle" && shape.faceDraft) {
1290
+ request.faceDraft = { sourceFaceId: shape.faceDraft.sourceFaceId, angle: number, pullDirection: shape.faceDraft.pullDirection };
1034
1291
  }
1292
+ else
1293
+ request[field] = number;
1035
1294
  }
1295
+ // Source-ID edits reach nested outputs and rebuild retained booleans around them.
1296
+ const target = shape.sketchSourceId ?? (topLevel ? shape.id : undefined);
1297
+ if (!target)
1298
+ return failed({ reason: "shapes_not_found", ids: [shapeId] });
1299
+ return changeShapeIn({ ...document, shapes }, target, request);
1300
+ });
1301
+ if (!result.ok)
1302
+ return result;
1303
+ }
1304
+ const current = findShapeInTree(shapes, shapeId);
1305
+ if (current?.topLevel) {
1306
+ for (const [field, number] of Object.entries(driftedPlacement(initial.shape, current.shape)))
1307
+ own[field] ??= number;
1308
+ }
1309
+ if (Object.keys(own).length) {
1310
+ const result = await step((shape) => changeShapeIn({ ...document, shapes }, shape.id, own));
1311
+ if (!result.ok)
1312
+ return result;
1313
+ }
1314
+ return restoreRootPlacement(document, document.shapes, shapes, shapeId);
1315
+ }
1316
+ /**
1317
+ * Binds or clears fields on one shape and applies the resolved values, without writing.
1318
+ * Returns `document.shapes` itself when nothing changed.
1319
+ */
1320
+ async function bindFieldsIn(document, shapeId, expressions) {
1321
+ const found = findShapeInTree(document.shapes, shapeId);
1322
+ if (!found)
1323
+ return failed({ reason: "shapes_not_found", ids: [shapeId] });
1324
+ if (found.locked)
1325
+ return failed({ reason: "shape_locked", ids: [found.locked] });
1326
+ let shape = found.shape;
1327
+ const values = {};
1328
+ for (const [field, expression] of Object.entries(expressions)) {
1329
+ if (expression === null) {
1330
+ shape = withoutBindings(shape, [field]);
1331
+ continue;
1036
1332
  }
1037
- const changed = shapeWithRequestedChanges(changeBase, Object.fromEntries(Object.entries(requestedChanges)));
1038
- if (!changed.ok) {
1333
+ if (bindableField(found.shape, field)?.target === "shape" && !found.topLevel) {
1334
+ return failed({ reason: "binding_invalid", error: { code: "fieldNotBindable", shapeId, field, message: `${field} binds on top-level shapes only.` } });
1335
+ }
1336
+ const resolved = resolveShapeBinding(found.shape, field, expression, document.parameters ?? []);
1337
+ if (!resolved.ok)
1338
+ return failed({ reason: "binding_invalid", error: resolved.error });
1339
+ const constraintIds = profileSizeFields(found.shape).includes(field)
1340
+ ? boundSketchConstraints(found.shape).map(({ constraint }) => constraint.id)
1341
+ : [];
1342
+ if (constraintIds.length) {
1039
1343
  return failed({
1040
- reason: "unapplicable_fields",
1041
- kind: existing.kind,
1042
- fields: changed.unapplicable,
1043
- because: "not_this_kind",
1344
+ reason: "binding_invalid",
1345
+ error: {
1346
+ code: "conflictingBinding",
1347
+ shapeId,
1348
+ field,
1349
+ constraintIds,
1350
+ message: `${field} cannot bind: it would rescale the sketch on ${shapeId}, whose ${constraintIds.join(", ")} is bound. Clear one binding first.`,
1351
+ },
1044
1352
  });
1045
1353
  }
1046
- const geometryFields = ["width", "depth", "height", "size", ...Object.keys(SHAPE_PARAMETERS)];
1047
- const geometryChanged = geometryFields.some((field) => JSON.stringify(existing[field])
1048
- !== JSON.stringify(changed.shape[field]));
1049
- let updatedShape = changed.shape;
1050
- if (existing.kind === "mesh" && existing.importedMesh && !existing.cadBrep
1051
- && ["rotation", "rotationX", "rotationZ"].some((field) => field in requestedChanges)) {
1052
- const previousMesh = worldMeshForShape(existing);
1053
- const mesh = worldMeshForShape(updatedShape);
1054
- if (previousMesh?.vertices.length && mesh?.vertices.length) {
1055
- const lowestPointOf = (vertices) => vertices.reduce((lowest, [, y]) => Math.min(lowest, y), Number.POSITIVE_INFINITY);
1056
- const previousLowestPoint = lowestPointOf(previousMesh.vertices);
1057
- const lowestPoint = lowestPointOf(mesh.vertices);
1058
- const targetElevation = typeof requestedChanges.elevation === "number"
1059
- ? requestedChanges.elevation
1060
- : previousLowestPoint;
1061
- updatedShape = {
1062
- ...updatedShape,
1063
- elevation: (updatedShape.elevation ?? 0) + targetElevation - lowestPoint,
1064
- };
1065
- }
1354
+ const groupConflict = groupSizeConflict(document.shapes, found.shape, field, found.topLevel);
1355
+ if (groupConflict)
1356
+ return failed({ reason: "binding_invalid", error: groupConflict });
1357
+ shape = { ...shape, expressions: { ...shape.expressions, [field]: expression } };
1358
+ if (boundFieldValue(found.shape, field) !== resolved.value)
1359
+ values[field] = resolved.value;
1360
+ }
1361
+ if (shape === found.shape)
1362
+ return ok(document.shapes);
1363
+ const shapes = replaceShapeInTree(document.shapes, shape);
1364
+ if (!Object.keys(values).length)
1365
+ return ok(shapes);
1366
+ const applied = await applyBindingValues({ ...document, shapes }, shapeId, values);
1367
+ if (!applied.ok)
1368
+ return failed({ reason: "binding_failed", shapeId, fields: Object.keys(values), failure: applied.failure });
1369
+ return applied;
1370
+ }
1371
+ /**
1372
+ * Validates constraint expressions on a created shape and applies their values. The expression wins
1373
+ * over the supplied value, as shape expressions do on create, so a stored value always matches it.
1374
+ */
1375
+ async function createdConstraintBindings(document, shape) {
1376
+ const values = {};
1377
+ for (const constraint of shape.sketchProfile?.constraints ?? []) {
1378
+ const expression = constraint.expression;
1379
+ if (expression === undefined)
1380
+ continue;
1381
+ const invalid = (error) => failed({ reason: "constraint_binding_invalid", error });
1382
+ if (typeof expression !== "string" || !expression.trim()) {
1383
+ return invalid({ code: "invalidExpression", shapeId: shape.id, constraintId: constraint.id, message: `${constraint.id}: an expression must be a non-empty string.` });
1066
1384
  }
1067
- if (!replacingSketchProfile && geometryChanged && (existing.faceIds?.length || existing.faceColors)) {
1068
- try {
1069
- updatedShape = await preserveUnambiguousFaceMetadata(existing, changed.shape);
1385
+ const resolved = resolveSketchConstraintBinding(shape.id, constraint, expression, document.parameters ?? []);
1386
+ if (!resolved.ok)
1387
+ return invalid(resolved.error);
1388
+ if (!rebuildableSketch(shape, true))
1389
+ return invalid(sketchNotRebuildable(shape.id, constraint.id));
1390
+ if (sketchConstraintValue(constraint) !== resolved.value)
1391
+ values[constraint.id] = resolved.value;
1392
+ }
1393
+ if (!Object.keys(values).length)
1394
+ return ok(document.shapes);
1395
+ const solved = solvedSketchProfile(shape, values);
1396
+ if (!solved.ok)
1397
+ return solved;
1398
+ const applied = await applyBindingValues(document, shape.id, {}, solved.value);
1399
+ if (!applied.ok)
1400
+ return failed({ reason: "binding_failed", shapeId: shape.id, fields: [], constraintIds: Object.keys(values), failure: applied.failure });
1401
+ return applied;
1402
+ }
1403
+ /** Re-resolves bindings that depend on a changed parameter and applies them, children first. */
1404
+ async function applyTable(document, shapes, previous, next) {
1405
+ const plan = planParameterBindings(shapes, previous, next);
1406
+ if (!plan.ok)
1407
+ return failed(plan.failure);
1408
+ const { pending } = plan;
1409
+ let current = shapes;
1410
+ for (const { id, values, sketchProfile, constraintIds } of pending) {
1411
+ const applied = await applyBindingValues({ ...document, shapes: current }, id, values, sketchProfile);
1412
+ if (!applied.ok) {
1413
+ return failed({
1414
+ reason: "binding_failed",
1415
+ shapeId: id,
1416
+ fields: Object.keys(values),
1417
+ ...(constraintIds ? { constraintIds } : {}),
1418
+ failure: applied.failure,
1419
+ });
1420
+ }
1421
+ current = applied.value;
1422
+ }
1423
+ return ok(current);
1424
+ }
1425
+ /** Runs a pure table or configuration operation, recomputes bound geometry, and writes both once. */
1426
+ function parameterOperation(projectId, operation) {
1427
+ return mutating(projectId, async (document) => {
1428
+ const previous = document.parameters ?? [];
1429
+ const project = {
1430
+ parameters: previous,
1431
+ configurations: document.configurations ?? [],
1432
+ activeConfiguration: document.activeConfiguration ?? null,
1433
+ shapes: document.shapes,
1434
+ };
1435
+ const result = operation(project);
1436
+ if (!result.ok)
1437
+ return failed({ reason: "parameter_invalid", error: result.error });
1438
+ const { parameters, configurations, activeConfiguration } = result.project;
1439
+ if (result.project === project) {
1440
+ return ok({ parameters, configurations, activeConfiguration, shapes: [], revision: documentRevision(document) });
1441
+ }
1442
+ const applied = await applyTable(document, result.project.shapes, previous, parameters);
1443
+ if (!applied.ok)
1444
+ return applied;
1445
+ const shapes = applied.value;
1446
+ const revision = await writeShapes(projectId, { ...document, parameters, configurations, activeConfiguration }, shapes);
1447
+ const before = new Set(document.shapes);
1448
+ return ok({ parameters, configurations, activeConfiguration, shapes: shapes.filter((shape) => !before.has(shape)), revision });
1449
+ });
1450
+ }
1451
+ return {
1452
+ project: (projectId) => reading(projectId, async (document) => ok({
1453
+ projectId,
1454
+ name: document.projectName,
1455
+ createdAt: document.createdAt,
1456
+ revision: documentRevision(document),
1457
+ shapes: document.shapes,
1458
+ snapGrid: document.snapGrid,
1459
+ workspace: document.workspace,
1460
+ parameters: document.parameters ?? [],
1461
+ configurations: document.configurations ?? [],
1462
+ activeConfiguration: document.activeConfiguration ?? null,
1463
+ })),
1464
+ addShapes: async (projectId, requests) => {
1465
+ const built = [];
1466
+ const bindings = [];
1467
+ for (const [index, { expressions, ...request }] of requests.entries()) {
1468
+ const parsed = parseRequestExpressions(expressions, { allowNull: false });
1469
+ if (!parsed.ok)
1470
+ return failed({ reason: "invalid_shape_request", index, message: parsed.message });
1471
+ const shape = await builtShape(request, index);
1472
+ if (!shape.ok)
1473
+ return shape;
1474
+ built.push(shape.value);
1475
+ bindings.push(parsed.expressions);
1476
+ }
1477
+ return mutating(projectId, async (document) => {
1478
+ let shapes = [...document.shapes, ...built];
1479
+ for (const [index, shape] of built.entries()) {
1480
+ const applied = await createdConstraintBindings({ ...document, shapes }, shape);
1481
+ if (!applied.ok) {
1482
+ const { failure } = applied;
1483
+ // A batch create names the shape by index, as #613 does; its id was never stored.
1484
+ return failure.reason === "constraint_binding_invalid" || failure.reason === "sketch_unsolvable" || failure.reason === "binding_failed"
1485
+ ? failed({ ...failure, index })
1486
+ : applied;
1487
+ }
1488
+ shapes = applied.value;
1070
1489
  }
1071
- catch (error) {
1072
- return failed(cadFailure(error));
1490
+ for (const [index, expressions] of bindings.entries()) {
1491
+ if (!Object.keys(expressions).length)
1492
+ continue;
1493
+ const conflict = conflictingLiteral(built[index], requests[index], expressions, document.parameters ?? []);
1494
+ if (conflict)
1495
+ return failed({ reason: "invalid_shape_request", index, ...conflict });
1496
+ const bound = await bindFieldsIn({ ...document, shapes }, built[index].id, expressions);
1497
+ if (!bound.ok) {
1498
+ const { failure } = bound;
1499
+ return failure.reason === "binding_invalid" || failure.reason === "binding_failed" ? failed({ ...failure, index }) : bound;
1500
+ }
1501
+ shapes = bound.value;
1073
1502
  }
1503
+ return ok({
1504
+ shapes: shapes.slice(document.shapes.length),
1505
+ revision: await writeShapes(projectId, document, shapes),
1506
+ });
1507
+ });
1508
+ },
1509
+ changeShape: (projectId, shapeId, { expressions: requested, ...changes }) => mutating(projectId, async (document) => {
1510
+ const parsed = parseRequestExpressions(requested, { allowNull: true });
1511
+ if (!parsed.ok)
1512
+ return failed({ reason: "invalid_shape_request", message: parsed.message });
1513
+ const before = findShapeInTree(document.shapes, shapeId)?.shape;
1514
+ // An entry repeating the stored expression is an echo: not re-resolved, so a stale one survives.
1515
+ const expressions = Object.fromEntries(Object.entries(parsed.expressions)
1516
+ .filter(([field, expression]) => expression === null || before?.expressions?.[field] !== expression));
1517
+ // A lock refusal names the requested fields this shape can bind, as a refused parameter change does.
1518
+ const refused = (failure) => {
1519
+ const fields = before && failure.reason === "shape_locked"
1520
+ ? Object.keys(parsed.expressions).filter((field) => bindableField(before, field))
1521
+ : [];
1522
+ return failed(fields.length ? { reason: "binding_failed", shapeId, fields, failure } : failure);
1523
+ };
1524
+ // Only echoed expressions: no write and no new revision, after the checks any change gets.
1525
+ if (!Object.keys(expressions).length && Object.keys(parsed.expressions).length && !Object.keys(changes).length) {
1526
+ if (!before)
1527
+ return failed({ reason: "shapes_not_found", ids: [shapeId] });
1528
+ const unchanged = await changeShapeIn(document, shapeId, {});
1529
+ if (!unchanged.ok)
1530
+ return refused(unchanged.failure);
1531
+ return ok({ shape: before, revision: documentRevision(document) });
1074
1532
  }
1075
- if (sourceSketchTarget) {
1076
- const candidate = replaceSketchOutput(document.shapes, shapeId, updatedShape);
1077
- if (candidate.matchCount !== 1) {
1078
- return failed({
1079
- reason: "sweep_failed",
1080
- message: candidate.matchCount === 0
1081
- ? `Sketch source ${shapeId} has no output node.`
1082
- : `Sketch source ${shapeId} has multiple output nodes.`,
1083
- });
1533
+ if (Object.keys(expressions).length) {
1534
+ if (!before)
1535
+ return failed({ reason: "shapes_not_found", ids: [shapeId] });
1536
+ const conflict = conflictingLiteral(before, changes, expressions, document.parameters ?? [], before);
1537
+ if (conflict)
1538
+ return failed({ reason: "invalid_shape_request", shapeId, ...conflict });
1539
+ }
1540
+ // A summary's sketchConstraints is read-only: an echo is ignored, an edit is refused rather than dropped.
1541
+ if (Object.hasOwn(changes, "sketchConstraints")
1542
+ && !echoesSketchConstraints(findSketchOutputShape(document.shapes, shapeId)?.shape.sketchProfile, changes.sketchConstraints)) {
1543
+ return failed({
1544
+ reason: "invalid_shape_request",
1545
+ shapeId,
1546
+ field: "sketchConstraints",
1547
+ message: "sketchConstraints is read-only. Change a constraint in sketchProfile, or bind it with the sketch-constraints operation.",
1548
+ });
1549
+ }
1550
+ // Constraint expressions in a sent profile follow the field rules; see `requestedSketchProfile`.
1551
+ let request = changes;
1552
+ if (changes.sketchProfile && typeof changes.sketchProfile === "object") {
1553
+ const target = findSketchOutputShape(document.shapes, shapeId);
1554
+ // Refused before any planning or solve, as bindSketchConstraint refuses it.
1555
+ const locked = lockRefusal(document.shapes, target, changes);
1556
+ if (locked)
1557
+ return failed(locked);
1558
+ const planned = requestedSketchProfile(target?.shape.id ?? shapeId, target?.shape.sketchProfile, changes.sketchProfile, document.parameters ?? []);
1559
+ if (!planned.ok) {
1560
+ return "error" in planned
1561
+ ? failed({ reason: "constraint_binding_invalid", error: planned.error })
1562
+ : failed({ reason: "invalid_shape_request", shapeId, ...planned.contradiction });
1084
1563
  }
1085
- const recomputed = await recompute({ ...document, shapes: candidate.shapes }, [shapeId], document);
1086
- if (!recomputed.ok) {
1087
- return failed({
1088
- reason: "sweep_failed",
1089
- message: recomputed.message ?? (recomputed.reason === "dependency_ambiguous"
1090
- ? "The sketch source has multiple dependent outputs."
1091
- : "The sketch source has no dependent output."),
1564
+ let sketchProfile = planned.profile;
1565
+ if (target && planned.bound.length) {
1566
+ const constraintId = planned.bound[0];
1567
+ // A literal resize would unbind the constraint this request binds.
1568
+ const resized = profileSizeFields(target.shape).find((field) => {
1569
+ const requested = requestedBindingValue(changes, field);
1570
+ return requested !== undefined && requested !== boundFieldValue(target.shape, field);
1092
1571
  });
1572
+ if (resized) {
1573
+ return failed({
1574
+ reason: "invalid_shape_request",
1575
+ shapeId,
1576
+ field: resized,
1577
+ constraintId,
1578
+ message: `${resized} resizes the sketch, which unbinds ${constraintId}. Send the size or the binding, not both.`,
1579
+ });
1580
+ }
1581
+ if (!rebuildableSketch(target.shape, target.topLevel)) {
1582
+ return failed({ reason: "constraint_binding_invalid", error: sketchNotRebuildable(target.shape.id, constraintId) });
1583
+ }
1584
+ const cleared = Object.keys(expressions).filter((field) => expressions[field] === null);
1585
+ const conflict = conflictingConstraintBinding(withoutBindings(target.shape, cleared), constraintId)
1586
+ ?? conflictingGroupSizeBinding(target.shape.id, constraintId, boundAncestorSizeFields(document.shapes, target.shape.id));
1587
+ if (conflict)
1588
+ return failed({ reason: "constraint_binding_invalid", error: conflict });
1589
+ }
1590
+ if (target && Object.keys(planned.values).length) {
1591
+ const solved = solvedSketchProfile({ ...target.shape, sketchProfile }, planned.values);
1592
+ if (!solved.ok)
1593
+ return solved;
1594
+ sketchProfile = solved.value;
1093
1595
  }
1094
- return ok({ shape: recomputed.updated, revision: await writeShapes(projectId, document, recomputed.shapes) });
1596
+ // A size equal to the stored one is an echo. Applied after the rebuild, it would undo the new profile.
1597
+ // An echoed position still applies, so a whole summary keeps the shape where the caller read it.
1598
+ const echoedSizes = target
1599
+ ? ["width", "depth", "height"].filter((field) => changes[field] !== undefined && changes[field] === target.shape[field])
1600
+ : [];
1601
+ request = { ...Object.fromEntries(Object.entries(changes).filter(([field]) => !echoedSizes.includes(field))), sketchProfile };
1602
+ }
1603
+ const changed = await changeShapeIn(document, shapeId, request);
1604
+ if (!changed.ok)
1605
+ return refused(changed.failure);
1606
+ const named = boundFieldsNamedBy(changes);
1607
+ const previous = findShapeInTree(document.shapes, changed.value.shape.id)?.shape;
1608
+ let rebuilt = changed.value;
1609
+ const restore = previous
1610
+ ? Object.fromEntries(Object.entries(driftedPlacement(previous, rebuilt.shape)).filter(([field]) => !named.includes(field)))
1611
+ : {};
1612
+ if (Object.keys(restore).length && findShapeInTree(rebuilt.shapes, rebuilt.shape.id)?.topLevel) {
1613
+ const locked = rebuilt.shape.locked;
1614
+ const placed = await changeShapeIn({ ...document, shapes: rebuilt.shapes }, rebuilt.shape.id, { ...restore, ...(locked ? { locked: false } : {}) });
1615
+ if (!placed.ok)
1616
+ return placed;
1617
+ rebuilt = locked
1618
+ ? { shape: { ...placed.value.shape, locked }, shapes: replaceShapeInTree(placed.value.shapes, { ...placed.value.shape, locked }) }
1619
+ : placed.value;
1620
+ }
1621
+ else {
1622
+ const restored = await restoreRootPlacement(document, document.shapes, rebuilt.shapes, rebuilt.shape.id);
1623
+ if (!restored.ok)
1624
+ return restored;
1625
+ rebuilt = { ...rebuilt, shapes: restored.value };
1626
+ }
1627
+ // A literal replaces the field's binding unless it repeats the current value.
1628
+ // A rebuild that moves a bound value also drops that binding.
1629
+ const echoed = before ? echoedBindings(before, changes) : [];
1630
+ const drifted = Object.keys(rebuilt.shape.expressions ?? {})
1631
+ .filter((field) => previous && boundFieldValue(previous, field) !== boundFieldValue(rebuilt.shape, field));
1632
+ const literal = [...named.filter((field) => !echoed.includes(field)), ...drifted];
1633
+ let unbound = withoutBindings(rebuilt.shape, literal);
1634
+ // A literal resize rescales the solved sketch, so its constraint bindings no longer describe it.
1635
+ const resized = previous ? profileSizeFields(previous).filter((field) => {
1636
+ const requested = requestedBindingValue(changes, field);
1637
+ return requested !== undefined && requested !== boundFieldValue(previous, field);
1638
+ }) : [];
1639
+ const loose = resized.length ? boundSketchConstraints(unbound).map(({ constraint }) => constraint.id) : [];
1640
+ if (loose.length) {
1641
+ unbound = {
1642
+ ...unbound,
1643
+ sketchProfile: withSketchConstraintValues(unbound.sketchProfile, {}, Object.fromEntries(loose.map((id) => [id, null]))),
1644
+ };
1645
+ }
1646
+ let shapes = unbound === rebuilt.shape
1647
+ ? rebuilt.shapes
1648
+ : replaceShapeInTree(rebuilt.shapes, unbound);
1649
+ let shape = unbound;
1650
+ if (Object.keys(expressions).length) {
1651
+ const bound = await bindFieldsIn({ ...document, shapes }, unbound.id, expressions);
1652
+ if (!bound.ok)
1653
+ return bound;
1654
+ shapes = bound.value;
1655
+ shape = findShapeInTree(shapes, unbound.id)?.shape ?? unbound;
1095
1656
  }
1096
- const shapes = document.shapes.map((shape) => (shape.id === existing.id ? updatedShape : shape));
1097
- return ok({ shape: updatedShape, revision: await writeShapes(projectId, document, shapes) });
1657
+ const droppedBindings = bindingsDropped(document.shapes, shapes, shape.id);
1658
+ return ok({ shape, revision: await writeShapes(projectId, document, shapes), ...(droppedBindings.length ? { droppedBindings } : {}) });
1098
1659
  }),
1099
1660
  removeShape: (projectId, shapeId) => mutating(projectId, async (document) => {
1100
1661
  const found = oneShape(document, shapeId);
@@ -1166,7 +1727,7 @@ export function createEngine(store) {
1166
1727
  // The copy turns about the ring's centre, so its own rotation gains the
1167
1728
  // same angle the placement did.
1168
1729
  return canonicalizeShape({
1169
- ...clone,
1730
+ ...withoutBindings(clone, ["x", "z", ...(placement.rotation === 0 ? [] : ["rotation"])]),
1170
1731
  x: storedCoordinate(clone.x + placement.dx),
1171
1732
  z: storedCoordinate(clone.z + placement.dz),
1172
1733
  rotation: placement.rotation === 0 ? clone.rotation : cleanRotationDegrees(clone.rotation + placement.rotation),
@@ -1221,7 +1782,8 @@ export function createEngine(store) {
1221
1782
  return failed({ reason: "not_a_group" });
1222
1783
  // A group can have been moved, turned and resized since it was made, so
1223
1784
  // its children come back carrying all of that.
1224
- const children = restoreGroupedChildren(found.value);
1785
+ // Children come back in world placement, so group-local shape bindings no longer apply.
1786
+ const children = restoreGroupedChildren(found.value).map(withoutShapeBindings);
1225
1787
  const shapes = [...document.shapes.filter((shape) => shape.id !== shapeId), ...children];
1226
1788
  return ok({ shapes: children, revision: await writeShapes(projectId, document, shapes) });
1227
1789
  }),
@@ -1233,7 +1795,7 @@ export function createEngine(store) {
1233
1795
  return failed({ reason: "shape_locked", ids: [shapeId] });
1234
1796
  if (found.value.hole)
1235
1797
  return failed({ reason: "hole_has_no_parts" });
1236
- const parts = separateShapeParts(found.value);
1798
+ const parts = separateShapeParts(found.value).map(withoutAnyBindings);
1237
1799
  // A shape built from parameters is one body by construction, so this is
1238
1800
  // answered without meshing anything.
1239
1801
  if (parts.length <= 1)
@@ -1252,7 +1814,7 @@ export function createEngine(store) {
1252
1814
  if (!source)
1253
1815
  return failed({ reason: "cad_refused", message: "The imported STEP source asset is no longer available.", status: 422 });
1254
1816
  try {
1255
- const parts = await explodeStepAssembly(found.value, source);
1817
+ const parts = (await explodeStepAssembly(found.value, source)).map(withoutAnyBindings);
1256
1818
  const index = document.shapes.findIndex((shape) => shape.id === shapeId);
1257
1819
  const shapes = [...document.shapes.slice(0, index), ...parts, ...document.shapes.slice(index + 1)];
1258
1820
  return ok({ shapes: parts, revision: await writeShapes(projectId, document, shapes) });
@@ -1401,8 +1963,9 @@ export function createEngine(store) {
1401
1963
  : (bounds.minZ + bounds.maxZ) / 2;
1402
1964
  const changed = [];
1403
1965
  try {
1966
+ // Baking rewrites placement into the solid, so bound placement and size are literals now.
1404
1967
  for (const shape of resolved.value)
1405
- changed.push(await applyBakedMirror(shape, axis, pivot));
1968
+ changed.push(withoutShapeBindings(await applyBakedMirror(shape, axis, pivot)));
1406
1969
  }
1407
1970
  catch (error) {
1408
1971
  return failed(cadFailure(error));
@@ -1424,6 +1987,69 @@ export function createEngine(store) {
1424
1987
  ...(request.openFaces?.length ? { openFaces: [...request.openFaces] } : {}),
1425
1988
  },
1426
1989
  })),
1990
+ addParameter: (projectId, input) => parameterOperation(projectId, (project) => addTableParameter(project, input)),
1991
+ updateParameter: (projectId, name, changes) => parameterOperation(projectId, (project) => updateTableParameter(project, name, changes)),
1992
+ renameParameter: (projectId, oldName, newName) => parameterOperation(projectId, (project) => renameTableParameter(project, oldName, newName)),
1993
+ deleteParameter: (projectId, name) => parameterOperation(projectId, (project) => deleteTableParameter(project, name)),
1994
+ addConfiguration: (projectId, name, overrides) => parameterOperation(projectId, (project) => addTableConfiguration(project, { name, overrides })),
1995
+ renameConfiguration: (projectId, oldName, newName) => parameterOperation(projectId, (project) => renameTableConfiguration(project, oldName, newName)),
1996
+ deleteConfiguration: (projectId, name) => parameterOperation(projectId, (project) => deleteTableConfiguration(project, name)),
1997
+ setConfigurationOverride: (projectId, configuration, parameter, expression) => parameterOperation(projectId, (project) => setTableConfigurationOverride(project, configuration, parameter, expression)),
1998
+ clearConfigurationOverride: (projectId, configuration, parameter) => parameterOperation(projectId, (project) => clearTableConfigurationOverride(project, configuration, parameter)),
1999
+ activateConfiguration: (projectId, name) => parameterOperation(projectId, (project) => activateTableConfiguration(project, name)),
2000
+ bindShapeField: (projectId, shapeId, field, expression) => mutating(projectId, async (document) => {
2001
+ const bound = await bindFieldsIn(document, shapeId, { [field]: expression });
2002
+ if (!bound.ok)
2003
+ return bound;
2004
+ const shape = findShapeInTree(bound.value, shapeId).shape;
2005
+ if (bound.value === document.shapes)
2006
+ return ok({ shape, revision: documentRevision(document) });
2007
+ return ok({ shape, revision: await writeShapes(projectId, document, bound.value) });
2008
+ }),
2009
+ bindSketchConstraint: (projectId, shapeId, constraintId, expression) => mutating(projectId, async (document) => {
2010
+ const found = findSketchOutputShape(document.shapes, shapeId);
2011
+ if (!found)
2012
+ return failed({ reason: "shapes_not_found", ids: [shapeId] });
2013
+ const output = found.shape;
2014
+ // A locked group refuses edits to the outputs it holds, as a manual edit is refused.
2015
+ const locked = lockRefusal(document.shapes, found, {});
2016
+ if (locked)
2017
+ return failed(locked);
2018
+ const constraint = output.sketchProfile.constraints?.find((candidate) => candidate.id === constraintId);
2019
+ if (!constraint) {
2020
+ return failed({
2021
+ reason: "constraint_binding_invalid",
2022
+ error: { code: "constraintNotFound", shapeId: output.id, constraintId, message: `The sketch on ${output.id} has no constraint ${constraintId}.` },
2023
+ });
2024
+ }
2025
+ const write = async (shape) => ok({ shape, revision: await writeShapes(projectId, document, replaceShapeInTree(document.shapes, shape)) });
2026
+ if (expression === null) {
2027
+ if (constraint.expression === undefined)
2028
+ return ok({ shape: output, revision: documentRevision(document) });
2029
+ return write({ ...output, sketchProfile: withSketchConstraintValues(output.sketchProfile, {}, { [constraintId]: null }) });
2030
+ }
2031
+ if (!rebuildableSketch(output, found.topLevel)) {
2032
+ return failed({ reason: "constraint_binding_invalid", error: sketchNotRebuildable(output.id, constraintId) });
2033
+ }
2034
+ const resolved = resolveSketchConstraintBinding(output.id, constraint, expression, document.parameters ?? []);
2035
+ if (!resolved.ok)
2036
+ return failed({ reason: "constraint_binding_invalid", error: resolved.error });
2037
+ const conflict = conflictingConstraintBinding(output, constraintId)
2038
+ ?? conflictingGroupSizeBinding(output.id, constraintId, boundAncestorSizeFields(document.shapes, output.id));
2039
+ if (conflict)
2040
+ return failed({ reason: "constraint_binding_invalid", error: conflict });
2041
+ const tagged = { ...output, sketchProfile: withSketchConstraintValues(output.sketchProfile, {}, { [constraintId]: expression }) };
2042
+ if (sketchConstraintValue(constraint) === resolved.value)
2043
+ return write(tagged);
2044
+ const solved = solvedSketchProfile(tagged, { [constraintId]: resolved.value });
2045
+ if (!solved.ok)
2046
+ return solved;
2047
+ const applied = await applyBindingValues(document, output.id, {}, solved.value);
2048
+ if (!applied.ok)
2049
+ return failed({ reason: "binding_failed", shapeId: output.id, fields: [], constraintIds: [constraintId], failure: applied.failure });
2050
+ const shape = findShapeInTree(applied.value, output.id)?.shape ?? tagged;
2051
+ return ok({ shape, revision: await writeShapes(projectId, document, applied.value) });
2052
+ }),
1427
2053
  };
1428
2054
  }
1429
2055
  //# sourceMappingURL=engine.js.map