@uipath/maestro-builder-sdk 6.111.0 → 6.113.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,564 @@
1
+ /**
2
+ * The layout `uip maestro flow format` computes, as plain data in and out: a copy of
3
+ * the parts of flow-workbench `@uipath/flow-core` `layout/` (0.172.x) that `format`
4
+ * runs, made synchronous (`core/elk-module.ts`).
5
+ *
6
+ * The SDK may not import `@uipath/flow-core` (lint FB016), so this is a copy, like the
7
+ * collision code in `node-placement.ts`. What is copied, from `packages/flow-core/src/layout/`:
8
+ *
9
+ * - `types.ts`: `GRID_SPACING`, `snapToGrid`, `resolveWidth`/`resolveHeight`,
10
+ * `DEFAULT_LAYOUT_OPTIONS` (layered, RIGHT, 96 node and layer spacing, crossing
11
+ * minimisation on);
12
+ * - `container-tidy-defaults.ts`: `snapUpToGrid`, the 32/64 interior spacing and
13
+ * `defaultContainerFit` (560 × 320, padding 96/48/144/144);
14
+ * - `elk-graph.ts`: `computeElkPortIndices`, `buildElkPorts` and the edge clearances;
15
+ * - `artifact-grouping.ts`: `analyzeArtifactConnections`, `buildArtifactParentWrappers`;
16
+ * - `elk-layout-engine.ts`: `ElkLayoutEngine.layout` (the root pass, with artifact
17
+ * wrappers frozen first), less the waypoints and metrics `format` does not read, and
18
+ * with one fix: an edge from a wrapped parent's undeclared handle (see `buildEdges`);
19
+ * - `container-tidy.ts`: `tidyContainerHierarchy` with what `format` passes: no
20
+ * `hooks`, no `overhangById`, no `portsById`.
21
+ *
22
+ * Example: three 96 × 96 nodes `a → b → c` come out on one row 192 px apart
23
+ * (`x` 16, 208, 400 before the caller anchors them), because the layer gap is 96.
24
+ *
25
+ * `tests/auto-layout.test.ts` runs these functions and the pinned flow-core's own
26
+ * (`typescript/package.json` devDependency) on the same graphs and requires the same
27
+ * answer. The CLI takes flow-core `^0.172.0` and moves on its own, so the daily
28
+ * `vendor-drift` job also runs that comparison against `@uipath/flow-core@latest`
29
+ * (`FLOW_CORE_LAYOUT`), and opens an issue when the published layout moves.
30
+ */
31
+ import { elkLayout } from './elk-module.js';
32
+ /** The canvas grid increment, in px. */
33
+ export const GRID_SPACING = 16;
34
+ /** Snap to the nearest grid increment. */
35
+ export function snapToGrid(value, gridSize = GRID_SPACING) {
36
+ return Math.round(value / gridSize) * gridSize;
37
+ }
38
+ /** Round up to the next grid increment. */
39
+ export function snapUpToGrid(value, gridSize = GRID_SPACING) {
40
+ return Math.ceil(value / gridSize) * gridSize;
41
+ }
42
+ /** flow-core `DEFAULT_LAYOUT_OPTIONS`, the fields the root pass reads. */
43
+ const ROOT = { algorithm: 'layered', direction: 'RIGHT', nodeSpacing: 96, layerSpacing: 96, minimizeCrossings: true };
44
+ /** flow-core `DEFAULT_INTERIOR_NODE_SPACING` / `DEFAULT_INTERIOR_LAYER_SPACING`. */
45
+ export const INTERIOR_NODE_SPACING = 32;
46
+ export const INTERIOR_LAYER_SPACING = 64;
47
+ /** The default node box (flow-core `resolveWidth`/`resolveHeight`). */
48
+ export const DEFAULT_NODE_SIZE = 96;
49
+ /** flow-core `defaultContainerFit()`. */
50
+ export function defaultContainerFit() {
51
+ return {
52
+ minWidth: 560,
53
+ minHeight: 320,
54
+ paddingTop: 96,
55
+ paddingBottom: 48,
56
+ paddingLeft: 144,
57
+ paddingRight: 144,
58
+ elkPadding: '[top=96,left=144,bottom=48,right=144]',
59
+ };
60
+ }
61
+ const ARTIFACT_GROUP_SPACING = 96;
62
+ const ARTIFACT_HORIZONTAL_SPACING = ARTIFACT_GROUP_SPACING / 2;
63
+ const FLOW_EDGE_STRAIGHTNESS_PRIORITY = '2';
64
+ const SPINE_STRAIGHTNESS_PRIORITY = '1';
65
+ const GRID_PADDING = `[top=${GRID_SPACING},left=${GRID_SPACING},bottom=${GRID_SPACING},right=${GRID_SPACING}]`;
66
+ const EDGE_EDGE_CLEARANCE_PX = 1 * GRID_SPACING;
67
+ const edgeNodeClearance = (layerSpacing) => snapToGrid(layerSpacing / 2);
68
+ const resolveWidth = (node) => node.width ?? DEFAULT_NODE_SIZE;
69
+ const resolveHeight = (node) => node.height ?? DEFAULT_NODE_SIZE;
70
+ // ---------------------------------------------------------------------------
71
+ // elk-graph.ts
72
+ // ---------------------------------------------------------------------------
73
+ /** Visual port order per side → ELK's clockwise order (SOUTH and WEST run backwards). */
74
+ function computeElkPortIndices(ports) {
75
+ const bySide = new Map();
76
+ for (const p of ports) {
77
+ if (!bySide.has(p.side))
78
+ bySide.set(p.side, []);
79
+ bySide.get(p.side).push(p);
80
+ }
81
+ const result = new Map();
82
+ for (const [side, sidePorts] of bySide) {
83
+ const sorted = [...sidePorts].sort((a, b) => a.index - b.index);
84
+ const reverse = side === 'SOUTH' || side === 'WEST';
85
+ sorted.forEach((p, i) => {
86
+ result.set(p.id, reverse ? sorted.length - 1 - i : i);
87
+ });
88
+ }
89
+ return result;
90
+ }
91
+ function buildElkPorts(nodeId, ports) {
92
+ const elkIndices = computeElkPortIndices([...ports]);
93
+ return ports.map((port) => ({
94
+ id: `${nodeId}_${port.id}`,
95
+ layoutOptions: { 'port.side': port.side, 'port.index': (elkIndices.get(port.id) ?? port.index).toString() },
96
+ }));
97
+ }
98
+ /** Targets of edges that leave a NORTH/SOUTH artifact port, grouped by (parent, handle). */
99
+ function analyzeArtifactConnections(edges, nodePortsMap) {
100
+ const groupMap = new Map();
101
+ const artifactNodeIds = new Set();
102
+ for (const edge of edges) {
103
+ const sourceHandle = edge.sourceHandle;
104
+ if (!sourceHandle)
105
+ continue;
106
+ const sourcePorts = nodePortsMap.get(edge.source);
107
+ if (!sourcePorts)
108
+ continue;
109
+ const port = sourcePorts.find((p) => p.id === sourceHandle);
110
+ if (!port || (port.side !== 'NORTH' && port.side !== 'SOUTH'))
111
+ continue;
112
+ if (port.handleType !== undefined && port.handleType !== 'artifact')
113
+ continue;
114
+ artifactNodeIds.add(edge.target);
115
+ let parentGroups = groupMap.get(edge.source);
116
+ if (!parentGroups) {
117
+ parentGroups = new Map();
118
+ groupMap.set(edge.source, parentGroups);
119
+ }
120
+ let group = parentGroups.get(sourceHandle);
121
+ if (!group) {
122
+ group = { side: port.side, nodeIds: [] };
123
+ parentGroups.set(sourceHandle, group);
124
+ }
125
+ if (!group.nodeIds.includes(edge.target))
126
+ group.nodeIds.push(edge.target);
127
+ }
128
+ const artifactGroups = [];
129
+ for (const [parentId, handleMap] of groupMap) {
130
+ const parentPorts = nodePortsMap.get(parentId) ?? [];
131
+ for (const [sourceHandle, group] of handleMap) {
132
+ const parentPort = parentPorts.find((p) => p.id === sourceHandle);
133
+ artifactGroups.push({ parentId, side: group.side, sourceHandle, parentPortIndex: parentPort?.index ?? 0, artifactNodeIds: [...group.nodeIds] });
134
+ }
135
+ }
136
+ return { artifactGroups, artifactNodeIds };
137
+ }
138
+ function buildArtifactParentWrappers(artifactGroups) {
139
+ const wrapperMap = new Map();
140
+ for (const group of artifactGroups) {
141
+ let wrapper = wrapperMap.get(group.parentId);
142
+ if (!wrapper) {
143
+ wrapper = { parentId: group.parentId, northGroups: [], southGroups: [] };
144
+ wrapperMap.set(group.parentId, wrapper);
145
+ }
146
+ if (group.side === 'NORTH')
147
+ wrapper.northGroups.push(group);
148
+ else
149
+ wrapper.southGroups.push(group);
150
+ }
151
+ for (const wrapper of wrapperMap.values()) {
152
+ wrapper.northGroups.sort((a, b) => a.parentPortIndex - b.parentPortIndex);
153
+ wrapper.southGroups.sort((a, b) => a.parentPortIndex - b.parentPortIndex);
154
+ }
155
+ return Array.from(wrapperMap.values());
156
+ }
157
+ // ---------------------------------------------------------------------------
158
+ // elk-layout-engine.ts — the root pass
159
+ // ---------------------------------------------------------------------------
160
+ const makeGroupId = (group) => `${group.parentId}__${group.sourceHandle}_group`;
161
+ /**
162
+ * flow-core `ElkLayoutEngine.layout` with `DEFAULT_LAYOUT_OPTIONS`: each node's new
163
+ * top-left, snapped to the grid, in ELK's frame (the caller anchors it).
164
+ *
165
+ * @param nodes - The nodes to lay out, in model order (ELK keeps it where it can).
166
+ * @param edges - The edges between them.
167
+ * @param resolveNodePorts - Each node's handles as ports.
168
+ * @returns The nodes with their new `position`.
169
+ */
170
+ export function layoutRoot(nodes, edges, resolveNodePorts) {
171
+ const nodePortsMap = new Map();
172
+ for (const node of nodes) {
173
+ const ports = resolveNodePorts(node);
174
+ if (ports.length > 0)
175
+ nodePortsMap.set(node.id, ports);
176
+ }
177
+ const { artifactGroups, artifactNodeIds } = analyzeArtifactConnections(edges, nodePortsMap);
178
+ const graph = buildHierarchicalGraph(nodes, edges, nodePortsMap, artifactGroups, artifactNodeIds);
179
+ freezeWrappers(graph);
180
+ const layouted = elkLayout(graph);
181
+ return extractNodePositions(nodes, layouted);
182
+ }
183
+ function buildHierarchicalGraph(nodes, edges, nodePortsMap, artifactGroups, artifactNodeIds) {
184
+ const nodeMap = new Map(nodes.map((n) => [n.id, n]));
185
+ const parentWrappers = buildArtifactParentWrappers(artifactGroups);
186
+ const wrappedParentIds = new Set(parentWrappers.map((w) => w.parentId));
187
+ const rootChildren = [];
188
+ for (const node of nodes) {
189
+ if (artifactNodeIds.has(node.id) || wrappedParentIds.has(node.id))
190
+ continue;
191
+ rootChildren.push(createElkNode(node, nodePortsMap));
192
+ }
193
+ for (const wrapper of parentWrappers) {
194
+ rootChildren.push(createWrapperNode(wrapper, nodeMap.get(wrapper.parentId), nodePortsMap, nodeMap));
195
+ }
196
+ return {
197
+ id: 'root',
198
+ layoutOptions: rootLayoutOptions(),
199
+ children: rootChildren,
200
+ edges: buildEdges(edges, wrappedParentIds, artifactNodeIds, nodePortsMap),
201
+ };
202
+ }
203
+ function createElkNode(node, nodePortsMap) {
204
+ const elkPorts = buildElkPorts(node.id, nodePortsMap.get(node.id) ?? []);
205
+ return {
206
+ id: node.id,
207
+ width: resolveWidth(node),
208
+ height: resolveHeight(node),
209
+ ports: elkPorts.length > 0 ? elkPorts : undefined,
210
+ layoutOptions: elkPorts.length > 0 ? { portConstraints: 'FIXED_ORDER' } : undefined,
211
+ };
212
+ }
213
+ function createWrapperNode(wrapper, parentNode, nodePortsMap, nodeMap) {
214
+ const wrapperId = `${wrapper.parentId}_wrapper`;
215
+ const wrapperChildren = [];
216
+ for (const group of wrapper.northGroups) {
217
+ const child = createGroupNode(group, nodePortsMap, nodeMap);
218
+ child.layoutOptions = { ...child.layoutOptions, 'elk.partitioning.partition': '0' };
219
+ wrapperChildren.push(child);
220
+ }
221
+ const parentPorts = nodePortsMap.get(wrapper.parentId) ?? [];
222
+ const parentElkIndices = computeElkPortIndices(parentPorts);
223
+ const parentElkPorts = parentPorts.map((port) => ({
224
+ id: `${wrapper.parentId}_${port.id}`,
225
+ layoutOptions: { 'port.side': port.side, 'port.index': (parentElkIndices.get(port.id) ?? port.index).toString() },
226
+ }));
227
+ wrapperChildren.push({
228
+ id: wrapper.parentId,
229
+ width: resolveWidth(parentNode),
230
+ height: resolveHeight(parentNode),
231
+ ports: parentElkPorts.length > 0 ? parentElkPorts : undefined,
232
+ layoutOptions: {
233
+ ...(parentElkPorts.length > 0 ? { portConstraints: 'FIXED_ORDER' } : {}),
234
+ 'elk.partitioning.partition': '1',
235
+ },
236
+ });
237
+ for (const group of wrapper.southGroups) {
238
+ const child = createGroupNode(group, nodePortsMap, nodeMap);
239
+ child.layoutOptions = { ...child.layoutOptions, 'elk.partitioning.partition': '2' };
240
+ wrapperChildren.push(child);
241
+ }
242
+ const wrapperPorts = parentPorts
243
+ .filter((p) => p.side === 'WEST' || p.side === 'EAST')
244
+ .map((port) => ({
245
+ id: `${wrapperId}_${port.id}`,
246
+ layoutOptions: { 'port.side': port.side, 'port.index': (parentElkIndices.get(port.id) ?? port.index).toString() },
247
+ }));
248
+ const internalEdges = [];
249
+ for (const group of [...wrapper.northGroups, ...wrapper.southGroups]) {
250
+ const groupId = makeGroupId(group);
251
+ internalEdges.push({
252
+ id: `internal_${wrapper.parentId}_${group.sourceHandle}_to_${groupId}`,
253
+ sources: [`${wrapper.parentId}_${group.sourceHandle}`],
254
+ targets: [`${groupId}_port`],
255
+ });
256
+ }
257
+ return {
258
+ id: wrapperId,
259
+ children: wrapperChildren,
260
+ edges: internalEdges.length > 0 ? internalEdges : undefined,
261
+ ports: wrapperPorts.length > 0 ? wrapperPorts : undefined,
262
+ layoutOptions: {
263
+ 'elk.algorithm': 'layered',
264
+ 'elk.direction': 'DOWN',
265
+ 'elk.spacing.nodeNode': ARTIFACT_GROUP_SPACING.toString(),
266
+ 'elk.layered.spacing.nodeNodeBetweenLayers': ARTIFACT_GROUP_SPACING.toString(),
267
+ 'elk.padding': '[top=0,left=0,bottom=0,right=0]',
268
+ portConstraints: 'FIXED_SIDE',
269
+ 'elk.alignment': 'CENTER',
270
+ 'elk.layered.nodePlacement.strategy': 'BRANDES_KOEPF',
271
+ 'elk.layered.nodePlacement.bk.fixedAlignment': 'BALANCED',
272
+ 'elk.layered.nodePlacement.bk.edgeStraightening': 'IMPROVE_STRAIGHTNESS',
273
+ 'elk.partitioning.activate': 'true',
274
+ },
275
+ };
276
+ }
277
+ function createGroupNode(group, nodePortsMap, nodeMap) {
278
+ const groupId = makeGroupId(group);
279
+ const children = group.artifactNodeIds.map((artifactId, index) => {
280
+ const node = nodeMap.get(artifactId);
281
+ const ports = nodePortsMap.get(artifactId) ?? [];
282
+ const elkIndices = computeElkPortIndices(ports);
283
+ const elkPorts = ports.map((port) => ({
284
+ id: `${artifactId}_${port.id}`,
285
+ layoutOptions: { 'port.side': port.side, 'port.index': (elkIndices.get(port.id) ?? port.index).toString() },
286
+ }));
287
+ if (index > 0)
288
+ elkPorts.push({ id: `${artifactId}_chain_in`, layoutOptions: { 'port.side': 'WEST', 'port.index': '100' } });
289
+ if (index < group.artifactNodeIds.length - 1)
290
+ elkPorts.push({ id: `${artifactId}_chain_out`, layoutOptions: { 'port.side': 'EAST', 'port.index': '100' } });
291
+ return {
292
+ id: artifactId,
293
+ width: node ? resolveWidth(node) : DEFAULT_NODE_SIZE,
294
+ height: node ? resolveHeight(node) : DEFAULT_NODE_SIZE,
295
+ ports: elkPorts.length > 0 ? elkPorts : undefined,
296
+ layoutOptions: { portConstraints: 'FIXED_SIDE' },
297
+ };
298
+ });
299
+ const chainEdges = [];
300
+ for (let i = 0; i < group.artifactNodeIds.length - 1; i++) {
301
+ chainEdges.push({
302
+ id: `${groupId}_chain_${i}`,
303
+ sources: [`${group.artifactNodeIds[i]}_chain_out`],
304
+ targets: [`${group.artifactNodeIds[i + 1]}_chain_in`],
305
+ });
306
+ }
307
+ return {
308
+ id: groupId,
309
+ children,
310
+ edges: chainEdges.length > 0 ? chainEdges : undefined,
311
+ ports: [{ id: `${groupId}_port`, layoutOptions: { 'port.side': group.side === 'NORTH' ? 'SOUTH' : 'NORTH', 'port.index': '0' } }],
312
+ layoutOptions: {
313
+ 'elk.algorithm': 'layered',
314
+ 'elk.direction': 'RIGHT',
315
+ 'elk.spacing.nodeNode': ARTIFACT_HORIZONTAL_SPACING.toString(),
316
+ 'elk.layered.spacing.nodeNodeBetweenLayers': ARTIFACT_HORIZONTAL_SPACING.toString(),
317
+ 'elk.padding': '[top=0,left=0,bottom=0,right=0]',
318
+ portConstraints: 'FIXED_SIDE',
319
+ },
320
+ };
321
+ }
322
+ function buildEdges(edges, wrappedParentIds, artifactNodeIds, nodePortsMap) {
323
+ const hasPort = (nodeId, handleId) => nodePortsMap.get(nodeId)?.some((p) => p.id === handleId) ?? false;
324
+ // A wrapper declares a port only for its parent's WEST/EAST handles. flow-core points
325
+ // an edge from any other handle at `<id>_wrapper_<handle>` too, which ELK refuses
326
+ // ("Referenced shape does not exist"), and `format` fails. That is the implicit
327
+ // `error` port of an agent with context or tools, which no definition declares.
328
+ // Here such an edge attaches to the wrapper itself; every other edge is flow-core's.
329
+ const wrapperRef = (nodeId, handle) => nodePortsMap.get(nodeId)?.some((p) => p.id === handle && (p.side === 'WEST' || p.side === 'EAST')) ? `${nodeId}_wrapper_${handle}` : `${nodeId}_wrapper`;
330
+ const elkEdges = [];
331
+ for (const edge of edges) {
332
+ const { sourceHandle, targetHandle } = edge;
333
+ if (artifactNodeIds.has(edge.target))
334
+ continue;
335
+ const sourceRef = wrappedParentIds.has(edge.source) && sourceHandle ? wrapperRef(edge.source, sourceHandle)
336
+ : sourceHandle && hasPort(edge.source, sourceHandle) ? `${edge.source}_${sourceHandle}`
337
+ : edge.source;
338
+ const targetRef = wrappedParentIds.has(edge.target) && targetHandle ? wrapperRef(edge.target, targetHandle)
339
+ : targetHandle && hasPort(edge.target, targetHandle) ? `${edge.target}_${targetHandle}`
340
+ : edge.target;
341
+ elkEdges.push({
342
+ id: edge.id,
343
+ sources: [sourceRef],
344
+ targets: [targetRef],
345
+ layoutOptions: { 'org.eclipse.elk.layered.priority.straightness': FLOW_EDGE_STRAIGHTNESS_PRIORITY },
346
+ });
347
+ }
348
+ return elkEdges;
349
+ }
350
+ /**
351
+ * Lay each artifact wrapper out on its own, then give the root pass a frozen copy whose
352
+ * flow ports sit on the parent's row (flow-core `freezeWrappers`).
353
+ */
354
+ function freezeWrappers(root) {
355
+ for (const child of root.children ?? []) {
356
+ if (!child.id.endsWith('_wrapper') || !child.children)
357
+ continue;
358
+ const parentId = child.id.slice(0, -'_wrapper'.length);
359
+ const laid = elkLayout(structuredClone(child));
360
+ const parent = laid.children?.find((c) => c.id === parentId);
361
+ if (!parent || laid.width === undefined || laid.height === undefined)
362
+ continue;
363
+ const parentCenterY = (parent.y ?? 0) + (parent.height ?? 0) / 2;
364
+ child.children = laid.children;
365
+ child.edges = laid.edges;
366
+ child.width = laid.width;
367
+ child.height = laid.height;
368
+ child.layoutOptions = { 'elk.algorithm': 'fixed', 'elk.padding': '[top=0,left=0,bottom=0,right=0]', portConstraints: 'FIXED_POS' };
369
+ child.ports = child.ports?.map((port) => {
370
+ const side = port.layoutOptions?.['port.side'];
371
+ return { ...port, x: side === 'EAST' ? laid.width : 0, y: parentCenterY, layoutOptions: { 'port.side': side ?? 'WEST' } };
372
+ });
373
+ }
374
+ }
375
+ function extractNodePositions(nodes, layouted) {
376
+ const nodePositions = new Map();
377
+ for (const child of layouted.children ?? []) {
378
+ if (child.id.endsWith('_wrapper')) {
379
+ const wrapperX = child.x ?? 0;
380
+ const wrapperY = child.y ?? 0;
381
+ for (const wrapperChild of child.children ?? []) {
382
+ if (wrapperChild.id.endsWith('_group')) {
383
+ const groupX = wrapperX + (wrapperChild.x ?? 0);
384
+ const groupY = wrapperY + (wrapperChild.y ?? 0);
385
+ for (const artifact of wrapperChild.children ?? []) {
386
+ nodePositions.set(artifact.id, { x: snapToGrid(groupX + (artifact.x ?? 0)), y: snapToGrid(groupY + (artifact.y ?? 0)) });
387
+ }
388
+ }
389
+ else {
390
+ nodePositions.set(wrapperChild.id, { x: snapToGrid(wrapperX + (wrapperChild.x ?? 0)), y: snapToGrid(wrapperY + (wrapperChild.y ?? 0)) });
391
+ }
392
+ }
393
+ }
394
+ else {
395
+ nodePositions.set(child.id, { x: snapToGrid(child.x ?? 0), y: snapToGrid(child.y ?? 0) });
396
+ }
397
+ }
398
+ return nodes.map((node) => {
399
+ const pos = nodePositions.get(node.id);
400
+ return pos ? { ...node, position: { x: pos.x, y: pos.y } } : node;
401
+ });
402
+ }
403
+ function rootLayoutOptions() {
404
+ return {
405
+ 'elk.algorithm': ROOT.algorithm,
406
+ 'elk.direction': ROOT.direction,
407
+ 'elk.spacing.nodeNode': ROOT.nodeSpacing.toString(),
408
+ 'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',
409
+ 'elk.padding': GRID_PADDING,
410
+ 'elk.layered.spacing.nodeNodeBetweenLayers': ROOT.layerSpacing.toString(),
411
+ 'elk.layered.nodePlacement.strategy': 'NETWORK_SIMPLEX',
412
+ 'elk.layered.layering.strategy': 'NETWORK_SIMPLEX',
413
+ ...(ROOT.minimizeCrossings ? { 'elk.layered.crossingMinimization.strategy': 'LAYER_SWEEP' } : {}),
414
+ 'elk.layered.cycleBreaking.strategy': 'DEPTH_FIRST',
415
+ 'elk.spacing.edgeNode': ROOT.nodeSpacing.toString(),
416
+ 'elk.spacing.edgeEdge': EDGE_EDGE_CLEARANCE_PX.toString(),
417
+ 'elk.layered.spacing.edgeNodeBetweenLayers': edgeNodeClearance(ROOT.layerSpacing).toString(),
418
+ 'elk.edgeRouting': 'ORTHOGONAL',
419
+ };
420
+ }
421
+ /** Linear-segment edges (source out-degree 1, target in-degree 1): the spine. */
422
+ function findSpineEdgeIds(childIds, edges) {
423
+ if (childIds.length === 0 || edges.length === 0)
424
+ return new Set();
425
+ const idSet = new Set(childIds);
426
+ const outDegree = new Map(childIds.map((id) => [id, 0]));
427
+ const inDegree = new Map(childIds.map((id) => [id, 0]));
428
+ for (const e of edges) {
429
+ const [src, tgt] = [e.sources[0], e.targets[0]];
430
+ if (!idSet.has(src) || !idSet.has(tgt) || src === tgt)
431
+ continue;
432
+ outDegree.set(src, (outDegree.get(src) ?? 0) + 1);
433
+ inDegree.set(tgt, (inDegree.get(tgt) ?? 0) + 1);
434
+ }
435
+ const spine = new Set();
436
+ for (const e of edges) {
437
+ const [src, tgt] = [e.sources[0], e.targets[0]];
438
+ if (!idSet.has(src) || !idSet.has(tgt) || src === tgt)
439
+ continue;
440
+ if ((outDegree.get(src) ?? 0) === 1 && (inDegree.get(tgt) ?? 0) === 1)
441
+ spine.add(e.id);
442
+ }
443
+ return spine;
444
+ }
445
+ function buildTidyElkContainer(containerId, params) {
446
+ const directChildren = params.childrenByParent.get(containerId) ?? [];
447
+ const localEdges = params.edgesByParent.get(containerId) ?? [];
448
+ const elkChildren = directChildren.map((child) => child.isContainer ? buildTidyElkContainer(child.id, params) : { id: child.id, width: child.width, height: child.height });
449
+ const spineEdgeIds = findSpineEdgeIds(directChildren.map((c) => c.id), localEdges);
450
+ const annotatedEdges = localEdges.map((e) => spineEdgeIds.has(e.id)
451
+ ? { ...e, layoutOptions: { ...e.layoutOptions, 'org.eclipse.elk.layered.priority.straightness': SPINE_STRAIGHTNESS_PRIORITY } }
452
+ : e);
453
+ return {
454
+ id: containerId,
455
+ width: params.fit.minWidth,
456
+ height: params.fit.minHeight,
457
+ layoutOptions: {
458
+ 'elk.algorithm': 'layered',
459
+ 'elk.direction': 'RIGHT',
460
+ 'elk.padding': params.fit.elkPadding,
461
+ 'elk.spacing.nodeNode': String(INTERIOR_NODE_SPACING),
462
+ 'elk.layered.spacing.nodeNodeBetweenLayers': String(INTERIOR_LAYER_SPACING),
463
+ 'elk.layered.nodePlacement.strategy': 'BRANDES_KOEPF',
464
+ 'elk.layered.nodePlacement.bk.fixedAlignment': 'BALANCED',
465
+ 'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',
466
+ 'elk.layered.crossingMinimization.forceNodeModelOrder': 'true',
467
+ 'elk.layered.cycleBreaking.strategy': 'DEPTH_FIRST',
468
+ 'elk.edgeRouting': 'ORTHOGONAL',
469
+ 'elk.spacing.edgeNode': String(INTERIOR_NODE_SPACING),
470
+ 'elk.spacing.edgeEdge': String(EDGE_EDGE_CLEARANCE_PX),
471
+ 'elk.layered.spacing.edgeNodeBetweenLayers': String(edgeNodeClearance(INTERIOR_LAYER_SPACING)),
472
+ 'elk.hierarchyHandling': 'SEPARATE_CHILDREN',
473
+ 'elk.nodeSize.constraints': 'MINIMUM_SIZE',
474
+ 'elk.nodeSize.minimum': `(${params.fit.minWidth},${params.fit.minHeight})`,
475
+ },
476
+ children: elkChildren,
477
+ edges: annotatedEdges,
478
+ };
479
+ }
480
+ function clamp(value, lo, hi) {
481
+ if (hi < lo)
482
+ return lo;
483
+ return Math.min(hi, Math.max(lo, value));
484
+ }
485
+ /** Size each container to fit its laid-out body plus padding, and centre the body (bottom-up). */
486
+ function applyTidyContainerLayout(node, updates, params) {
487
+ const { fit } = params;
488
+ const children = node.children ?? [];
489
+ if (children.length === 0) {
490
+ if (node.children !== undefined) {
491
+ const w = snapUpToGrid(Math.max(fit.minWidth, node.width ?? 0));
492
+ const h = snapUpToGrid(Math.max(fit.minHeight, node.height ?? 0));
493
+ updates.set(node.id, { width: w, height: h });
494
+ return { width: w, height: h };
495
+ }
496
+ return { width: node.width ?? DEFAULT_NODE_SIZE, height: node.height ?? DEFAULT_NODE_SIZE };
497
+ }
498
+ const childSizes = new Map();
499
+ for (const child of children)
500
+ childSizes.set(child.id, applyTidyContainerLayout(child, updates, params));
501
+ let minX = Number.POSITIVE_INFINITY;
502
+ let minY = Number.POSITIVE_INFINITY;
503
+ let maxX = 0;
504
+ let maxY = 0;
505
+ for (const child of children) {
506
+ const x = child.x ?? 0;
507
+ const y = child.y ?? 0;
508
+ const { width: w, height: h } = childSizes.get(child.id);
509
+ if (x < minX)
510
+ minX = x;
511
+ if (y < minY)
512
+ minY = y;
513
+ if (x + w > maxX)
514
+ maxX = x + w;
515
+ if (y + h > maxY)
516
+ maxY = y + h;
517
+ }
518
+ for (const edge of node.edges ?? []) {
519
+ for (const section of edge.sections ?? []) {
520
+ for (const bend of section.bendPoints ?? []) {
521
+ if (bend.x < minX)
522
+ minX = bend.x;
523
+ if (bend.y < minY)
524
+ minY = bend.y;
525
+ if (bend.x > maxX)
526
+ maxX = bend.x;
527
+ if (bend.y > maxY)
528
+ maxY = bend.y;
529
+ }
530
+ }
531
+ }
532
+ const bboxWidth = maxX - minX;
533
+ const bboxHeight = maxY - minY;
534
+ const finalWidth = snapUpToGrid(Math.max(fit.minWidth, bboxWidth + fit.paddingLeft + fit.paddingRight));
535
+ const finalHeight = snapUpToGrid(Math.max(fit.minHeight, bboxHeight + fit.paddingTop + fit.paddingBottom));
536
+ const dx = clamp((finalWidth - bboxWidth) / 2 - minX, fit.paddingLeft - minX, finalWidth - fit.paddingRight - maxX);
537
+ const dy = clamp((finalHeight - bboxHeight) / 2 - minY, fit.paddingTop - minY, finalHeight - fit.paddingBottom - maxY);
538
+ updates.set(node.id, { width: finalWidth, height: finalHeight });
539
+ for (const child of children) {
540
+ const size = childSizes.get(child.id);
541
+ updates.set(child.id, {
542
+ position: { x: snapToGrid((child.x ?? 0) + dx), y: snapToGrid((child.y ?? 0) + dy) },
543
+ width: size.width,
544
+ height: size.height,
545
+ });
546
+ }
547
+ return { width: finalWidth, height: finalHeight };
548
+ }
549
+ /**
550
+ * flow-core `tidyContainerHierarchy` as `format` calls it: lay out a container's
551
+ * interior (nested containers recurse), size every container to fit, and centre each body.
552
+ *
553
+ * @param containerId - The top-level container.
554
+ * @param childrenByParent - Each container's direct children.
555
+ * @param edgesByParent - Each container's interior edges (node ids, no ports).
556
+ * @returns Each node's new relative position and size, by id.
557
+ */
558
+ export function tidyContainer(containerId, childrenByParent, edgesByParent) {
559
+ const params = { childrenByParent, edgesByParent, fit: defaultContainerFit() };
560
+ const layouted = elkLayout(buildTidyElkContainer(containerId, params));
561
+ const updates = new Map();
562
+ applyTidyContainerLayout(layouted, updates, params);
563
+ return updates;
564
+ }
@@ -0,0 +1,40 @@
1
+ /** An ELK graph node, as `elkjs` reads and writes it (`elk-api.d.ts`), with only the fields layout uses. */
2
+ export interface ElkNode {
3
+ id: string;
4
+ x?: number;
5
+ y?: number;
6
+ width?: number;
7
+ height?: number;
8
+ children?: ElkNode[];
9
+ ports?: ElkPort[];
10
+ edges?: ElkEdge[];
11
+ layoutOptions?: Record<string, string>;
12
+ }
13
+ /** An ELK port. */
14
+ export interface ElkPort {
15
+ id: string;
16
+ x?: number;
17
+ y?: number;
18
+ layoutOptions?: Record<string, string>;
19
+ }
20
+ /** An ELK edge; `sections` carry the routed bend points. */
21
+ export interface ElkEdge {
22
+ id: string;
23
+ sources: string[];
24
+ targets: string[];
25
+ layoutOptions?: Record<string, string>;
26
+ sections?: {
27
+ bendPoints?: {
28
+ x: number;
29
+ y: number;
30
+ }[];
31
+ }[];
32
+ }
33
+ /**
34
+ * Lay out `graph` with ELK, in place, and return it.
35
+ *
36
+ * @param graph - The ELK graph; its nodes get `x`/`y` (and containers `width`/`height`).
37
+ * @returns `graph`, laid out.
38
+ * @throws CompileRefusal `ELK_UNAVAILABLE` outside Node when no host handed elkjs over.
39
+ */
40
+ export declare function elkLayout(graph: ElkNode): ElkNode;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * ELK (the Eclipse Layout Kernel, `elkjs`), loaded on first use and run synchronously.
3
+ *
4
+ * Compile lays out a flow with no `.layout()` the way `uip maestro flow format` does
5
+ * (`core/elk-layout.ts`), and `format` is ELK. `elkjs` is 1.6 MB of compiled Java, so it
6
+ * loads only when a flow needs laying out, the way `core/typescript-module.ts` loads the
7
+ * TypeScript compiler (FB009 keeps both off the import path).
8
+ *
9
+ * `serialize()` is synchronous, and elkjs's public `ELK.layout()` returns a Promise. The
10
+ * promise is only a wrapper: in Node, `elk-worker` exports a `FakeWorker` whose
11
+ * dispatcher runs the layout in the calling thread and posts the laid-out graph to
12
+ * `onmessage` before it returns. `elk-api` defers that post behind a `setTimeout`; this
13
+ * module calls the dispatcher directly and reads the result in the same tick. That is
14
+ * the same code path `ELK.layout()` runs, without the timer. `elkjs` is pinned to an
15
+ * exact version for that reason, and `tests/auto-layout.test.ts` compares this runner
16
+ * with `ELK.layout()` on the same graphs.
17
+ *
18
+ * A host without Node (a browser sandbox) hands the `elkjs/lib/elk-worker.min.js` module
19
+ * over before the first compile: `globalThis[Symbol.for('uipath.maestro-builder-sdk.elkjs')]`.
20
+ * Otherwise `createRequire` comes from `process.getBuiltinModule`, not an `import`, so the
21
+ * flow core loads no `node:` builtin (FB015 exempts this fallback).
22
+ */
23
+ import { CompileRefusal } from './compile-refusal.js';
24
+ const HOST_ELK = Symbol.for('uipath.maestro-builder-sdk.elkjs');
25
+ /** The algorithms `elk-api` registers when given none (elkjs 0.11 `elk-api.js`). */
26
+ const DEFAULT_ALGORITHMS = ['layered', 'stress', 'mrtree', 'radial', 'force', 'disco', 'sporeOverlap', 'sporeCompaction', 'rectpacking'];
27
+ let worker;
28
+ let reply;
29
+ /**
30
+ * Lay out `graph` with ELK, in place, and return it.
31
+ *
32
+ * @param graph - The ELK graph; its nodes get `x`/`y` (and containers `width`/`height`).
33
+ * @returns `graph`, laid out.
34
+ * @throws CompileRefusal `ELK_UNAVAILABLE` outside Node when no host handed elkjs over.
35
+ */
36
+ export function elkLayout(graph) {
37
+ const w = (worker ??= startWorker());
38
+ const answer = post(w, { cmd: 'layout', graph, layoutOptions: {}, options: {} });
39
+ if (answer.error !== undefined) {
40
+ const message = answer.error?.message;
41
+ throw new Error(`internal SDK error: ELK layout failed: ${typeof message === 'string' ? message : String(answer.error)}`);
42
+ }
43
+ return graph;
44
+ }
45
+ function post(w, msg) {
46
+ reply = undefined;
47
+ w.dispatcher.saveDispatch({ data: { ...msg, id: 0 } });
48
+ const answer = reply;
49
+ if (answer === undefined)
50
+ throw new Error('internal SDK error: the ELK worker answered asynchronously');
51
+ return answer;
52
+ }
53
+ function startWorker() {
54
+ const mod = (globalThis[HOST_ELK] ?? fromNode());
55
+ const Ctor = mod.default ?? mod.Worker;
56
+ if (typeof Ctor !== 'function')
57
+ throw new Error('internal SDK error: elkjs/lib/elk-worker.min.js exports no FakeWorker');
58
+ const w = new Ctor();
59
+ w.onmessage = (event) => { reply = event.data; };
60
+ if (typeof w.dispatcher?.saveDispatch !== 'function')
61
+ throw new Error('internal SDK error: the elkjs FakeWorker has no dispatcher');
62
+ post(w, { cmd: 'register', algorithms: DEFAULT_ALGORITHMS });
63
+ return w;
64
+ }
65
+ function fromNode() {
66
+ const getBuiltinModule = globalThis.process?.getBuiltinModule;
67
+ if (getBuiltinModule === undefined) {
68
+ throw new CompileRefusal('ELK_UNAVAILABLE', "no layout engine: outside Node, set globalThis[Symbol.for('uipath.maestro-builder-sdk.elkjs')] to the 'elkjs/lib/elk-worker.min.js' module before compiling a flow with no .layout()");
69
+ }
70
+ const { createRequire } = getBuiltinModule('node:module');
71
+ return createRequire(import.meta.url)('elkjs/lib/elk-worker.min.js');
72
+ }