@bpmnkit/core 1.5.0 → 1.6.1

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 (40) hide show
  1. package/dist/bpmn/agentic.d.ts +9 -2
  2. package/dist/bpmn/agentic.js +8 -3
  3. package/dist/bpmn/auto-layout.d.ts +7 -2
  4. package/dist/bpmn/auto-layout.js +111 -7
  5. package/dist/bpmn/bpmn-builder.d.ts +65 -4
  6. package/dist/bpmn/bpmn-builder.js +126 -45
  7. package/dist/bpmn/compact.d.ts +24 -0
  8. package/dist/bpmn/compact.js +81 -4
  9. package/dist/bpmn/full-operations.js +20 -0
  10. package/dist/bpmn/optimize/flow.js +2 -0
  11. package/dist/bpmn/optimize/patterns.js +2 -2
  12. package/dist/bpmn/optimize/variable-flow.d.ts +1 -0
  13. package/dist/bpmn/optimize/variable-flow.js +1 -1
  14. package/dist/bpmn/process-delta.d.ts +21 -1
  15. package/dist/bpmn/process-delta.js +33 -3
  16. package/dist/bpmn/process-text-writer.js +80 -6
  17. package/dist/bpmn/process-text.d.ts +22 -1
  18. package/dist/bpmn/process-text.js +268 -9
  19. package/dist/bpmn/stable-ids.d.ts +11 -0
  20. package/dist/bpmn/stable-ids.js +76 -10
  21. package/dist/connectors/apply-many.d.ts +49 -0
  22. package/dist/connectors/apply-many.js +162 -0
  23. package/dist/connectors/index.d.ts +2 -0
  24. package/dist/connectors/index.js +1 -0
  25. package/dist/connectors/lines.d.ts +1 -1
  26. package/dist/connectors/lines.js +13 -3
  27. package/dist/connectors/select.d.ts +2 -0
  28. package/dist/connectors/select.js +11 -0
  29. package/dist/index.d.ts +3 -3
  30. package/dist/layout/annotations.d.ts +3 -1
  31. package/dist/layout/annotations.js +11 -4
  32. package/dist/layout/index.d.ts +1 -1
  33. package/dist/layout/layout-engine.d.ts +4 -2
  34. package/dist/layout/layout-engine.js +4 -2
  35. package/dist/layout/semantic/index.d.ts +7 -3
  36. package/dist/layout/semantic/index.js +11 -7
  37. package/dist/layout/semantic/place.d.ts +4 -2
  38. package/dist/layout/semantic/place.js +12 -9
  39. package/dist/layout/types.d.ts +18 -0
  40. package/package.json +2 -2
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Applying several element templates in one call, from values a caller wrote
3
+ * by hand — an agent's script, not a property panel. Where
4
+ * {@link applyTemplateToElement} takes a resolved template and string values,
5
+ * this takes the names people and models actually use (`HttpJson.v2@18`,
6
+ * `http`), lets numbers and booleans stand for themselves, and answers a
7
+ * misspelt key with the key the template meant.
8
+ */
9
+ import { levenshtein } from "../bpmn/optimize/variable-flow.js";
10
+ import { applyTemplateToElement } from "./apply-element.js";
11
+ import { resolveValues } from "./apply.js";
12
+ import { templateIdForAlias } from "./cards.js";
13
+ import { getTemplate, propertyKey } from "./catalog.js";
14
+ function resolveTemplate(reference) {
15
+ const at = reference.lastIndexOf("@");
16
+ const name = at === -1 ? reference : reference.slice(0, at);
17
+ const version = at === -1 ? undefined : reference.slice(at + 1);
18
+ const template = getTemplate(name) ?? getTemplate(templateIdForAlias(name) ?? "");
19
+ if (!template)
20
+ return { problem: `Unknown connector template "${name}"` };
21
+ if (version === "") {
22
+ return { problem: `Template reference "${reference}": empty version after "@"` };
23
+ }
24
+ // The catalogue keeps one version of each id, so any other version is not there to apply.
25
+ if (version !== undefined) {
26
+ if (template.version === undefined) {
27
+ return { problem: `Template "${template.id}" has no version; drop "@${version}"` };
28
+ }
29
+ if (version !== String(template.version)) {
30
+ return {
31
+ problem: `Template "${template.id}" is not available at version ${version}; the available version is ${template.version}`,
32
+ };
33
+ }
34
+ }
35
+ return { template };
36
+ }
37
+ /**
38
+ * The property id a wrong key most likely meant. A key that is the name a
39
+ * property binds to (`retries` for `retryCount`, which writes
40
+ * `zeebe:taskDefinition` `retries`) names it exactly; otherwise the closest
41
+ * id or binding name within a third of the key's length.
42
+ */
43
+ function suggestKey(template, key) {
44
+ let best;
45
+ for (const prop of template.properties) {
46
+ const id = propertyKey(prop);
47
+ if (!id)
48
+ continue;
49
+ const binding = prop.binding;
50
+ const names = [
51
+ id,
52
+ "name" in binding ? binding.name : undefined,
53
+ "property" in binding ? binding.property : undefined,
54
+ "key" in binding ? binding.key : undefined,
55
+ ];
56
+ for (const name of names) {
57
+ if (typeof name !== "string")
58
+ continue;
59
+ const distance = levenshtein(key.toLowerCase(), name.toLowerCase());
60
+ if (best === undefined || distance < best.distance)
61
+ best = { id, distance };
62
+ }
63
+ }
64
+ const limit = Math.max(2, Math.floor(key.length / 3));
65
+ return best !== undefined && best.distance <= limit ? best.id : undefined;
66
+ }
67
+ function describeCondition(condition) {
68
+ if ("allMatch" in condition)
69
+ return condition.allMatch.map(describeCondition).join(" and ");
70
+ const c = condition;
71
+ if (c.equals !== undefined)
72
+ return `${c.property} is ${c.equals}`;
73
+ if (c.oneOf !== undefined)
74
+ return `${c.property} is one of ${c.oneOf.join(", ")}`;
75
+ if (c.isActive !== undefined)
76
+ return `${c.property} is ${c.isActive ? "" : "not "}set`;
77
+ return `${c.property} is ${c.isEmpty ? "" : "not "}empty`;
78
+ }
79
+ /**
80
+ * A problem for each given key whose property the template's conditions
81
+ * switch off for these values — `ignoreNullValues` on a GET — which the
82
+ * template would otherwise drop without a word.
83
+ */
84
+ function unwrittenValues(template, elementId, values) {
85
+ const active = resolveValues(template, values);
86
+ const problems = [];
87
+ for (const key of Object.keys(values)) {
88
+ if (key in active)
89
+ continue;
90
+ const condition = template.properties.find((p) => propertyKey(p) === key)?.condition;
91
+ if (condition === undefined)
92
+ continue;
93
+ problems.push({
94
+ elementId,
95
+ key,
96
+ message: `Value for "${key}" was not written: the template only uses it when ${describeCondition(condition)}`,
97
+ });
98
+ }
99
+ return problems;
100
+ }
101
+ /**
102
+ * Applies each entry in order with {@link applyTemplateToElement} and gathers
103
+ * what went wrong, each problem naming its element.
104
+ *
105
+ * - **Templates.** An id, `id@version`, an alias from `CONNECTOR_ALIASES`, or
106
+ * a template object. The catalogue holds one version of each id, so a
107
+ * different `@version` is a problem naming the available one and the
108
+ * element is left as it was.
109
+ * - **Values.** Keyed by template property id, as in `applyTemplateToElement`;
110
+ * numbers and booleans become their string form. Strings are written
111
+ * verbatim — a real newline stays a newline. Properties left out keep the
112
+ * template's default.
113
+ * - **Unknown keys.** Reported with a `suggestion` when a property id or
114
+ * binding name is close; the rest of the entry is still applied.
115
+ * - **Switched-off keys.** A value for a property whose `condition` does not
116
+ * hold for the entry's values is not written, and is reported naming the
117
+ * condition.
118
+ *
119
+ * @param definitions - The model; not mutated.
120
+ * @param entries - Elements anywhere in the model, nested ones included.
121
+ */
122
+ export function applyTemplates(definitions, entries) {
123
+ const problems = [];
124
+ let current = definitions;
125
+ for (const entry of entries) {
126
+ const { elementId } = entry;
127
+ let template;
128
+ if (typeof entry.template === "string") {
129
+ const resolved = resolveTemplate(entry.template);
130
+ if ("problem" in resolved) {
131
+ problems.push({ elementId, message: resolved.problem });
132
+ continue;
133
+ }
134
+ template = resolved.template;
135
+ }
136
+ else {
137
+ template = entry.template;
138
+ }
139
+ const values = Object.fromEntries(Object.entries(entry.values).map(([key, value]) => [key, String(value)]));
140
+ const result = applyTemplateToElement(current, elementId, template, values);
141
+ // A refusal returns the model it was given; its one problem says all there is.
142
+ const refused = result.definitions === current;
143
+ current = result.definitions;
144
+ for (const problem of result.problems) {
145
+ const reported = { elementId, message: problem.message };
146
+ if (problem.key !== undefined)
147
+ reported.key = problem.key;
148
+ if (problem.kind === "unknown-key" && problem.key !== undefined) {
149
+ const suggestion = suggestKey(template, problem.key);
150
+ if (suggestion !== undefined) {
151
+ reported.suggestion = suggestion;
152
+ reported.message += `; did you mean "${suggestion}"?`;
153
+ }
154
+ }
155
+ problems.push(reported);
156
+ }
157
+ if (!refused)
158
+ problems.push(...unwrittenValues(template, elementId, values));
159
+ }
160
+ return { definitions: current, problems };
161
+ }
162
+ //# sourceMappingURL=apply-many.js.map
@@ -16,6 +16,8 @@ export { applyConnectorTemplate, applyElementTemplate } from "./apply.js";
16
16
  export type { ApplyResult, ApplyProblem } from "./apply.js";
17
17
  export { applyTemplateToElement } from "./apply-element.js";
18
18
  export type { ApplyToElementResult } from "./apply-element.js";
19
+ export { applyTemplates } from "./apply-many.js";
20
+ export type { TemplateApplication, TemplateApplicationProblem } from "./apply-many.js";
19
21
  export { BUNDLED_CONNECTOR_TEMPLATES } from "./templates/generated.js";
20
22
  export { BPMNKIT_CONNECTOR_TEMPLATES } from "./templates/bpmnkit.js";
21
23
  export { CONNECTOR_ALIASES } from "./aliases.js";
@@ -13,6 +13,7 @@
13
13
  export { listConnectors, searchConnectors, getTemplate, propertyKey, registerElementTemplates, clearRegisteredTemplates, summarizeTemplate, } from "./catalog.js";
14
14
  export { applyConnectorTemplate, applyElementTemplate } from "./apply.js";
15
15
  export { applyTemplateToElement } from "./apply-element.js";
16
+ export { applyTemplates } from "./apply-many.js";
16
17
  export { BUNDLED_CONNECTOR_TEMPLATES } from "./templates/generated.js";
17
18
  export { BPMNKIT_CONNECTOR_TEMPLATES } from "./templates/bpmnkit.js";
18
19
  export { CONNECTOR_ALIASES } from "./aliases.js";
@@ -17,7 +17,7 @@ import { type ConnectorCard } from "./cards.js";
17
17
  * connector cards for the diagram's tasks follow it in the prompt. A test
18
18
  * parses its example and expects every line to resolve.
19
19
  */
20
- export declare const CONNECT_GUIDE = "Connect the diagram: write one with line for each node that calls an outside system, nothing else.\nwith <id>: <alias> <operation> | key=value | key==FEEL expression\n- <id> is a node of the diagram, written exactly as before the colon of its cards. <alias>, <operation> and the keys come from the connector cards.\n- When the request names a system, use that system's card.\n- Write every input marked *. Write a mode (key=choice) only to change its default, with the inputs that choice adds.\n- A value starting with = is FEEL: text== \"Order \" + orderId. Without =, it is literal text. A variable is FEEL too: to==email, never {{email}} or ${email}; {{\u2026}} is only for secrets.\n- Credentials are never values: token={{secrets.SLACK_TOKEN}}.\n- result=name keeps the response in a variable; result=name: response.body keeps a part of it.\n- A plain task that becomes a connector needs no other change. Leave out nodes no card fits.\n- An api card lists real endpoints of a service for the http connector: write http <METHOD> <path> | api=<service>. The base URL, the authentication and the {params} of the path, read from variables of the same name, are added. Prefer a dedicated connector's card to an api card.\n\nExample:\nwith notify: slack chat.postMessage | token={{secrets.SLACK_TOKEN}} | data.channel=#ops | data.text== \"Order \" + orderId + \" failed\"\nwith fetch: http GET https://api.example.com/orders | result=order: response.body\nwith charge: http POST /v1/customers | api=stripe | body=={email: email} | result=customer: response.body";
20
+ export declare const CONNECT_GUIDE = "Connect the diagram: write one with line for each node that calls an outside system, nothing else.\nwith <id>: <alias> <operation> | key=value | key==FEEL expression\n- <id> is a node of the diagram, written exactly as before the colon of its cards. <alias>, <operation> and the keys come from the connector cards.\n- When the request names a system, use that system's card.\n- Write every input marked *. Write a mode (key=choice) only to change its default, with the inputs that choice adds.\n- A value starting with = is FEEL: text== \"Order \" + orderId. Without =, it is literal text. In a FEEL value, \\n is a line break (one value is one line). A variable is FEEL too: to==email, never {{email}} or ${email}; {{\u2026}} is only for secrets.\n- Credentials are never values: token={{secrets.SLACK_TOKEN}}.\n- result=name keeps the response in a variable; result=name: response.body keeps a part of it.\n- A plain task that becomes a connector needs no other change. Leave out nodes no card fits.\n- An api card lists real endpoints of a service for the http connector: write http <METHOD> <path> | api=<service>. The base URL, the authentication and the {params} of the path, read from variables of the same name, are added. Prefer a dedicated connector's card to an api card.\n\nExample:\nwith notify: slack chat.postMessage | token={{secrets.SLACK_TOKEN}} | data.channel=#ops | data.text== \"Order \" + orderId + \" failed\"\nwith fetch: http GET https://api.example.com/orders | result=order: response.body\nwith charge: http POST /v1/customers | api=stripe | body=={email: email} | result=customer: response.body";
21
21
  /** What {@link resolveConnectorLine} made of a line. */
22
22
  export interface ResolvedConnectorLine {
23
23
  /** The template, when the alias named one. */
@@ -8,6 +8,7 @@
8
8
  * operation does not have or a credential written as a value is repaired or
9
9
  * reported, and a required input still missing becomes a question.
10
10
  */
11
+ import { findElement } from "../bpmn/utils.js";
11
12
  import { apiAuthValues, apiHeaders, apiUrl, findApiOperation } from "./api.js";
12
13
  import { applyTemplateToElement, messageRefOf } from "./apply-element.js";
13
14
  import { evalCondition, resolveValues } from "./apply.js";
@@ -24,7 +25,7 @@ with <id>: <alias> <operation> | key=value | key==FEEL expression
24
25
  - <id> is a node of the diagram, written exactly as before the colon of its cards. <alias>, <operation> and the keys come from the connector cards.
25
26
  - When the request names a system, use that system's card.
26
27
  - Write every input marked *. Write a mode (key=choice) only to change its default, with the inputs that choice adds.
27
- - A value starting with = is FEEL: text== "Order " + orderId. Without =, it is literal text. A variable is FEEL too: to==email, never {{email}} or \${email}; {{…}} is only for secrets.
28
+ - A value starting with = is FEEL: text== "Order " + orderId. Without =, it is literal text. In a FEEL value, \\n is a line break (one value is one line). A variable is FEEL too: to==email, never {{email}} or \${email}; {{…}} is only for secrets.
28
29
  - Credentials are never values: token={{secrets.SLACK_TOKEN}}.
29
30
  - result=name keeps the response in a variable; result=name: response.body keeps a part of it.
30
31
  - A plain task that becomes a connector needs no other change. Leave out nodes no card fits.
@@ -320,8 +321,16 @@ function feelHeaders(value, fixes) {
320
321
  fixes.push(`read headers ${value} as a FEEL context`);
321
322
  return `={${entries.join(", ")}}`;
322
323
  }
324
+ /**
325
+ * `\n` in a FEEL value is a line break: a `with` line is one line, and an agent's prompt is
326
+ * paragraphs. `\\n` stays a backslash and n. Only `==` values: a literal value is taken as written.
327
+ */
328
+ function feelLineBreaks(value) {
329
+ return value.replace(/\\\\n|\\n/g, (m) => (m === "\\n" ? "\n" : "\\n"));
330
+ }
323
331
  /** A variable written in another template syntax, as the FEEL expression it means. */
324
- function feelForVariable(key, value, fixes) {
332
+ function feelForVariable(key, rawValue, fixes) {
333
+ const value = rawValue.startsWith("=") ? feelLineBreaks(rawValue) : rawValue;
325
334
  // `== "Order " + ${orderId} + " failed"`: a template variable inside FEEL is the variable
326
335
  if (value.startsWith("=") && /\$\{\s*[A-Za-z_][\w.]*\s*\}/.test(value)) {
327
336
  const feel = value.replace(/\$\{\s*([A-Za-z_][\w.]*)\s*\}/g, "$1");
@@ -484,7 +493,8 @@ export function applyConnectorLines(definitions, lines, options = {}) {
484
493
  return out;
485
494
  }
486
495
  function elementOf(definitions, id) {
487
- return definitions.processes.flatMap((p) => p.flowElements).find((el) => el.id === id);
496
+ // Nested too: the tools of an ad-hoc sub-process are configured by the same lines
497
+ return findElement(definitions, id);
488
498
  }
489
499
  function child(ext, name) {
490
500
  return ext?.find((x) => x.name === name);
@@ -15,6 +15,8 @@ export interface ConnectorTask {
15
15
  id: string;
16
16
  name?: string;
17
17
  type: BpmnElementType;
18
+ /** The ad-hoc sub-process this task is a tool of, which makes the REST connector a candidate. */
19
+ inside?: string;
18
20
  }
19
21
  /** The cards picked for one task, best first. */
20
22
  export interface TaskCards {
@@ -22,9 +22,12 @@ const BPMN_TYPE = {
22
22
  intermediateCatchEvent: "bpmn:IntermediateCatchEvent",
23
23
  intermediateThrowEvent: "bpmn:IntermediateThrowEvent",
24
24
  boundaryEvent: "bpmn:BoundaryEvent",
25
+ adHocSubProcess: "bpmn:AdHocSubProcess",
25
26
  };
26
27
  /** Tasks a template written for `bpmn:Task` turns into its own type. */
27
28
  const TASKS = new Set(["task", "serviceTask", "sendTask", "scriptTask"]);
29
+ /** The connector an ad-hoc sub-process becomes: the AI agent, whatever the container is called. */
30
+ const AGENT_TEMPLATE = "io.camunda.connectors.agenticai.ai-agent-subprocess.v2";
28
31
  /** Template element types that turn a task into an outbound call. */
29
32
  const OUTBOUND_TASKS = new Set(["bpmn:ServiceTask", "bpmn:SendTask", "bpmn:Task"]);
30
33
  /**
@@ -352,6 +355,14 @@ export function selectConnectors(input, options = {}) {
352
355
  scored.push({ card: http, score: 5 });
353
356
  }
354
357
  }
358
+ // A draft's ad-hoc container is the agent's: "Support helper" names no AI system, and
359
+ // its tools are free-named tasks that most often call a REST endpoint
360
+ const agent = task.type === "adHocSubProcess" ? connectorCards(AGENT_TEMPLATE)[0] : undefined;
361
+ if (agent && !scored.some((s) => s.card === agent))
362
+ scored.push({ card: agent, score: 100 });
363
+ if (task.inside !== undefined && http && !scored.some((s) => s.card === http)) {
364
+ scored.push({ card: http, score: 1 });
365
+ }
355
366
  scored.sort((a, b) => b.score - a.score);
356
367
  return { task, scored: varied(scored), apiCards };
357
368
  });
package/dist/index.d.ts CHANGED
@@ -27,7 +27,7 @@ export { checkDiCompleteness } from "./bpmn/di-check.js";
27
27
  export type { DiCompleteness } from "./bpmn/di-check.js";
28
28
  export { planeForElement, listPlaneElementIds } from "./bpmn/di-planes.js";
29
29
  export { DiagramBuilder, ProcessBuilder } from "./bpmn/bpmn-builder.js";
30
- export type { BranchBuilder, BuildOptions, MessageFlowOptions, ParticipantOptions, DiagramMessageOptions, SubProcessContentBuilder, ServiceTaskOptions, ScriptTaskOptions, UserTaskOptions, CallActivityOptions, BusinessRuleTaskOptions, ElementOptions, GatewayOptions, MultiInstanceOptions, SubProcessOptions, StartEventOptions, IntermediateCatchEventOptions, IntermediateThrowEventOptions, EndEventOptions, BoundaryEventOptions, AdHocSubProcessOptions, } from "./bpmn/bpmn-builder.js";
30
+ export type { BranchBuilder, BuildOptions, MessageFlowOptions, ParticipantOptions, DiagramMessageOptions, SubProcessContentBuilder, ServiceTaskOptions, ScriptTaskOptions, UserTaskOptions, CallActivityOptions, BusinessRuleTaskOptions, ElementOptions, GatewayOptions, MultiInstanceOptions, SubProcessOptions, StartEventOptions, IntermediateCatchEventOptions, IntermediateThrowEventOptions, EndEventOptions, BoundaryEventOptions, AdHocSubProcessOptions, AnnotateOptions, } from "./bpmn/bpmn-builder.js";
31
31
  export type { BpmnDefinitions, BpmnProcess, BpmnFlowNode, BpmnFlowElement, BpmnSequenceFlow, BpmnBoundaryEvent, BpmnElementType, BpmnStartEvent, BpmnEndEvent, BpmnIntermediateCatchEvent, BpmnIntermediateThrowEvent, BpmnTask, BpmnServiceTask, BpmnScriptTask, BpmnUserTask, BpmnSendTask, BpmnReceiveTask, BpmnBusinessRuleTask, BpmnManualTask, BpmnCallActivity, BpmnSubProcess, BpmnAdHocSubProcess, BpmnEventSubProcess, BpmnTransaction, BpmnExclusiveGateway, BpmnParallelGateway, BpmnInclusiveGateway, BpmnEventBasedGateway, BpmnComplexGateway, BpmnCollaboration, BpmnParticipant, BpmnMessageFlow, BpmnLane, BpmnLaneSet, BpmnError, BpmnEscalation, BpmnMessage, BpmnSignal, BpmnTextAnnotation, BpmnAssociation, BpmnGroup, BpmnDataObject, BpmnDataObjectReference, BpmnDataStoreReference, BpmnConditionExpression, BpmnEventDefinition, BpmnTimerEventDefinition, BpmnErrorEventDefinition, BpmnEscalationEventDefinition, BpmnMessageEventDefinition, BpmnSignalEventDefinition, BpmnConditionalEventDefinition, BpmnLinkEventDefinition, BpmnCancelEventDefinition, BpmnTerminateEventDefinition, BpmnCompensateEventDefinition, BpmnMultiInstanceLoopCharacteristics, BpmnDiagram, BpmnDiPlane, BpmnDiShape, BpmnDiEdge, BpmnDiLabel, BpmnBounds, BpmnWaypoint, } from "./bpmn/bpmn-model.js";
32
32
  export type { RestConnectorConfig, RestAuthentication, HttpMethod, } from "./bpmn/rest-connector.js";
33
33
  export type { ZeebeExtensions, ZeebeTaskDefinition, ZeebeIoMapping, ZeebeIoMappingEntry, ZeebeTaskHeaders, ZeebeTaskHeaderEntry, ZeebeProperties, ZeebePropertyEntry, ZeebeFormDefinition, ZeebeCalledDecision, ZeebeAssignmentDefinition, ZeebeTaskSchedule, ZeebePriorityDefinition, ZeebeSubscription, ZeebeAgentDefinition, } from "./bpmn/zeebe-extensions.js";
@@ -64,7 +64,7 @@ export { layoutProcess, layoutFlowNodes } from "./layout/index.js";
64
64
  export type { LayoutEngine } from "./layout/index.js";
65
65
  export { benchmarkLayout, compareLayouts, formatBenchmarkResult, generateAutoLayout, parseReferenceLayout, } from "./layout/index.js";
66
66
  export type { BenchmarkResult, BoundingBox, ElementComparison, ElementPosition, FlowOrderViolation, } from "./layout/index.js";
67
- export type { Bounds, LayoutEdge, LayoutNode, LayoutResult, Waypoint } from "./layout/index.js";
67
+ export type { Bounds, GridHint, LayoutEdge, LayoutHints, LayoutNode, LayoutResult, Waypoint, } from "./layout/index.js";
68
68
  export { ELEMENT_SIZES, GRID_CELL_HEIGHT, GRID_CELL_WIDTH } from "./layout/index.js";
69
69
  export { compactify, expand } from "./bpmn/compact.js";
70
70
  export { createCompactStream } from "./bpmn/compact-stream.js";
@@ -94,7 +94,7 @@ export { exportSvg } from "./bpmn/svg.js";
94
94
  export type { SvgExportOptions } from "./bpmn/svg.js";
95
95
  export { buildProcessDocumentation, documentationToDocx, documentationToHtml, documentationToMarkdown, renderDocumentationDocx, renderDocumentationHtml, renderDocumentationMarkdown, } from "./doc/index.js";
96
96
  export type { DocumentationLink, DocumentationOptions, DocumentedDecision, DocumentedElement, DocumentedForm, DocumentedFormField, DocumentedLane, DocumentedMessageFlow, DocumentedProcess, DocumentedProperty, DocxDocumentationOptions, ProcessDocumentation, } from "./doc/index.js";
97
- export type { CompactDiagram, CompactElement, CompactFlow, CompactProcess, } from "./bpmn/compact.js";
97
+ export type { CompactDiagram, CompactElement, CompactFlow, CompactNote, CompactProcess, } from "./bpmn/compact.js";
98
98
  export { compilePlan, extractPlan, mergePlan, slugify, uniqueId, } from "./plan/index.js";
99
99
  export type { CompilePlanOptions, ConnectorApplyResult, ConnectorResolver, ExtractResult, PlanAgentTool, PlanAiAgentStep, PlanBranch, PlanBusinessRuleTaskStep, PlanCallActivityStep, PlanConnectorRef, PlanConnectorStep, PlanEndStep, PlanErrorBoundary, PlanGatewayStep, PlanInputVariable, PlanProblem, PlanRawStep, PlanReceiveTaskStep, PlanScenario, PlanScriptTaskStep, PlanSendTaskStep, PlanServiceTaskStep, PlanStartStep, PlanStep, PlanSubProcessStep, PlanTimerBoundary, PlanUserTaskStep, PlanWaitStep, ProcessPlan, SynthResult, UnsupportedElement, } from "./plan/index.js";
100
100
  export { listSecrets } from "./bpmn/secrets.js";
@@ -17,7 +17,9 @@ import type { Bounds, LayoutEdge, LayoutNode, Waypoint } from "./types.js";
17
17
  */
18
18
  export declare function packAnnotations(process: BpmnProcess, layoutNodes: LayoutNode[],
19
19
  /** Routed connections: an annotation box must not sit on top of one. */
20
- layoutEdges?: LayoutEdge[]): Map<string, Bounds>;
20
+ layoutEdges?: LayoutEdge[],
21
+ /** Sides the author asked for, by annotation id. */
22
+ sides?: ReadonlyMap<string, "above" | "below">): Map<string, Bounds>;
21
23
  /**
22
24
  * Edge-to-edge, clamped association waypoints between a linked element and
23
25
  * its annotation. Port of `chooseWaypoints` (tmp/01-annotation-layouting.cjs:365-389).
@@ -83,8 +83,13 @@ function computeMainFlowY(layoutNodes) {
83
83
  }
84
84
  return bestKey;
85
85
  }
86
- /** Elements at or above the main flow keep their annotation "above"; elements clearly below get "below". */
87
- function naturalSide(elemBounds, mainFlowY) {
86
+ /**
87
+ * Elements at or above the main flow keep their annotation "above"; elements
88
+ * clearly below get "below". A side the author asked for wins.
89
+ */
90
+ function naturalSide(elemBounds, mainFlowY, hint) {
91
+ if (hint)
92
+ return hint;
88
93
  const cy = elemBounds.y + elemBounds.height / 2;
89
94
  return cy > mainFlowY + 60 ? "below" : "above";
90
95
  }
@@ -109,7 +114,9 @@ function overlapsPadded(a, others, padding) {
109
114
  */
110
115
  export function packAnnotations(process, layoutNodes,
111
116
  /** Routed connections: an annotation box must not sit on top of one. */
112
- layoutEdges = []) {
117
+ layoutEdges = [],
118
+ /** Sides the author asked for, by annotation id. */
119
+ sides) {
113
120
  const result = new Map();
114
121
  if (process.textAnnotations.length === 0)
115
122
  return result;
@@ -134,7 +141,7 @@ layoutEdges = []) {
134
141
  unlinked.push({ id: ann.id, width, height });
135
142
  continue;
136
143
  }
137
- const side = naturalSide(linked.bounds, mainFlowY);
144
+ const side = naturalSide(linked.bounds, mainFlowY, sides?.get(ann.id));
138
145
  const lc = center(linked.bounds);
139
146
  items.push({
140
147
  id: ann.id,
@@ -5,6 +5,6 @@ export type { BenchmarkResult, BoundingBox, ElementComparison, ElementPosition,
5
5
  export { assertNoOverlap } from "./overlap.js";
6
6
  export { checkDiCompleteness } from "../bpmn/di-check.js";
7
7
  export type { DiCompleteness } from "../bpmn/di-check.js";
8
- export type { Bounds, LayoutEdge, LayoutNode, LayoutResult, Waypoint } from "./types.js";
8
+ export type { Bounds, GridHint, LayoutEdge, LayoutHints, LayoutNode, LayoutResult, Waypoint, } from "./types.js";
9
9
  export { ELEMENT_SIZES, GRID_CELL_HEIGHT, GRID_CELL_WIDTH, HORIZONTAL_SPACING, LABEL_CHAR_WIDTH, LABEL_HEIGHT, LABEL_MIN_WIDTH, LABEL_VERTICAL_OFFSET, SUBPROCESS_PADDING, VERTICAL_SPACING, } from "./types.js";
10
10
  //# sourceMappingURL=index.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import type { BpmnFlowElement, BpmnProcess, BpmnSequenceFlow } from "../bpmn/bpmn-model.js";
2
- import type { LayoutResult } from "./types.js";
2
+ import type { LayoutHints, LayoutResult } from "./types.js";
3
3
  /**
4
4
  * Which layout algorithm to run.
5
5
  *
@@ -16,7 +16,9 @@ export type LayoutEngine = "semantic" | "grid";
16
16
  */
17
17
  export declare function layoutProcess(process: BpmnProcess, engine?: LayoutEngine,
18
18
  /** Sub-processes the diagram draws collapsed; their contents get their own plane. */
19
- collapsed?: ReadonlySet<string>): LayoutResult;
19
+ collapsed?: ReadonlySet<string>,
20
+ /** Tool-grid hints; only the `semantic` engine packs tools into a grid, so `grid` ignores them. */
21
+ grids?: LayoutHints["grids"]): LayoutResult;
20
22
  /** Layout a set of flow nodes and sequence flows (used by ascii, proxy, compact). */
21
23
  export declare function layoutFlowNodes(flowNodes: BpmnFlowElement[], sequenceFlows: BpmnSequenceFlow[]): LayoutResult;
22
24
  //# sourceMappingURL=layout-engine.d.ts.map
@@ -8,10 +8,12 @@ import { semanticLayoutProcess } from "./semantic/index.js";
8
8
  */
9
9
  export function layoutProcess(process, engine = "semantic",
10
10
  /** Sub-processes the diagram draws collapsed; their contents get their own plane. */
11
- collapsed) {
11
+ collapsed,
12
+ /** Tool-grid hints; only the `semantic` engine packs tools into a grid, so `grid` ignores them. */
13
+ grids) {
12
14
  if (engine === "grid")
13
15
  return gridLayoutFlowNodes(process.flowElements, process.sequenceFlows);
14
- return semanticLayoutProcess(process, collapsed);
16
+ return semanticLayoutProcess(process, collapsed, grids);
15
17
  }
16
18
  /** Layout a set of flow nodes and sequence flows (used by ascii, proxy, compact). */
17
19
  export function layoutFlowNodes(flowNodes, sequenceFlows) {
@@ -1,15 +1,19 @@
1
1
  import type { BpmnFlowElement, BpmnLaneSet, BpmnProcess, BpmnSequenceFlow } from "../../bpmn/bpmn-model.js";
2
- import type { LayoutResult } from "../types.js";
2
+ import type { GridHint, LayoutHints, LayoutResult } from "../types.js";
3
3
  /**
4
4
  * Lay out a process the way the BPMN reads: ranks carry the flow left to right,
5
5
  * semantic bands carry branch meaning up and down, and lane membership wins over
6
6
  * both.
7
7
  */
8
- export declare function semanticLayoutProcess(process: BpmnProcess, collapsed?: ReadonlySet<string>): LayoutResult;
8
+ export declare function semanticLayoutProcess(process: BpmnProcess, collapsed?: ReadonlySet<string>, grids?: LayoutHints["grids"]): LayoutResult;
9
9
  export declare function semanticLayout(flowElements: BpmnFlowElement[], sequenceFlows: BpmnSequenceFlow[], laneSet?: BpmnLaneSet,
10
10
  /** Sub-processes drawn collapsed: their contents go on a plane of their own. */
11
11
  collapsed?: ReadonlySet<string>,
12
12
  /** True for the contents of an expanded sub-process; see `place`'s `packLoose`. */
13
- inContainer?: boolean): LayoutResult;
13
+ inContainer?: boolean,
14
+ /** Tool-grid hints, by container id; applied to the containers in this scope and below. */
15
+ grids?: LayoutHints["grids"],
16
+ /** The hint for this scope's own grid, when it is a hinted container's interior. */
17
+ grid?: GridHint): LayoutResult;
14
18
  export type { Placement } from "./place.js";
15
19
  //# sourceMappingURL=index.d.ts.map
@@ -16,14 +16,18 @@ const CONTAINER_TYPES = new Set(["subProcess", "adHocSubProcess", "eventSubProce
16
16
  * semantic bands carry branch meaning up and down, and lane membership wins over
17
17
  * both.
18
18
  */
19
- export function semanticLayoutProcess(process, collapsed) {
20
- return semanticLayout(process.flowElements, process.sequenceFlows, process.laneSet, collapsed);
19
+ export function semanticLayoutProcess(process, collapsed, grids) {
20
+ return semanticLayout(process.flowElements, process.sequenceFlows, process.laneSet, collapsed, false, grids);
21
21
  }
22
22
  export function semanticLayout(flowElements, sequenceFlows, laneSet,
23
23
  /** Sub-processes drawn collapsed: their contents go on a plane of their own. */
24
24
  collapsed = new Set(),
25
25
  /** True for the contents of an expanded sub-process; see `place`'s `packLoose`. */
26
- inContainer = false) {
26
+ inContainer = false,
27
+ /** Tool-grid hints, by container id; applied to the containers in this scope and below. */
28
+ grids,
29
+ /** The hint for this scope's own grid, when it is a hinted container's interior. */
30
+ grid) {
27
31
  if (flowElements.length === 0)
28
32
  return { nodes: [], edges: [] };
29
33
  const graph = buildSemanticGraph(flowElements, sequenceFlows);
@@ -33,7 +37,7 @@ inContainer = false) {
33
37
  const planes = [];
34
38
  const sizes = new Map();
35
39
  for (const el of graph.nodes) {
36
- const child = childLayoutOf(el, collapsed);
40
+ const child = childLayoutOf(el, collapsed, grids);
37
41
  if (!child) {
38
42
  sizes.set(el.id, sizeOf(el));
39
43
  continue;
@@ -52,7 +56,7 @@ inContainer = false) {
52
56
  // A named expanded sub-process draws its title along its top border.
53
57
  const titled = new Set([...childResults.keys()].filter((id) => graph.byId.get(id)?.name !== undefined));
54
58
  const bandLayout = assignBands(graph, titled);
55
- const { bounds, lanes, gutterX } = place(graph, bandLayout, sizes, laneSet, inContainer, titled);
59
+ const { bounds, lanes, gutterX } = place(graph, bandLayout, sizes, laneSet, inContainer, titled, grid);
56
60
  const besideStem = boundaryLabels(graph, bounds);
57
61
  const nodes = [];
58
62
  for (const el of flowElements) {
@@ -113,7 +117,7 @@ inContainer = false) {
113
117
  return result;
114
118
  }
115
119
  /** Lay out a container's children and report the size its border needs. */
116
- function childLayoutOf(el, collapsed) {
120
+ function childLayoutOf(el, collapsed, grids) {
117
121
  if (!CONTAINER_TYPES.has(el.type))
118
122
  return null;
119
123
  const container = el;
@@ -122,7 +126,7 @@ function childLayoutOf(el, collapsed) {
122
126
  const result = semanticLayout(container.flowElements, container.sequenceFlows ?? [], container.laneSet, collapsed,
123
127
  // A collapsed container's contents go on a plane of their own, laid out
124
128
  // like any top-level scope.
125
- !collapsed.has(el.id));
129
+ !collapsed.has(el.id), grids, grids?.get(el.id));
126
130
  const extent = extentOf(result);
127
131
  if (!extent)
128
132
  return null;
@@ -1,5 +1,5 @@
1
1
  import type { BpmnFlowElement, BpmnLaneSet } from "../../bpmn/bpmn-model.js";
2
- import type { Bounds } from "../types.js";
2
+ import type { Bounds, GridHint } from "../types.js";
3
3
  import { type BandLayout } from "./bands.js";
4
4
  import type { SemanticGraph } from "./graph.js";
5
5
  /** Geometry constants. Layout may add space beyond these; it never takes any back. */
@@ -54,5 +54,7 @@ packLoose?: boolean,
54
54
  * Hosts whose title is drawn along their top border — named expanded
55
55
  * sub-processes. Boundary events stay off that border.
56
56
  */
57
- titled?: ReadonlySet<string>): Placement;
57
+ titled?: ReadonlySet<string>,
58
+ /** Shape of the `packLoose` grid, when the builder asked for one. */
59
+ grid?: GridHint): Placement;
58
60
  //# sourceMappingURL=place.d.ts.map
@@ -53,7 +53,9 @@ packLoose = false,
53
53
  * Hosts whose title is drawn along their top border — named expanded
54
54
  * sub-processes. Boundary events stay off that border.
55
55
  */
56
- titled = new Set()) {
56
+ titled = new Set(),
57
+ /** Shape of the `packLoose` grid, when the builder asked for one. */
58
+ grid) {
57
59
  const bounds = new Map();
58
60
  const componentOf = new Map();
59
61
  for (let i = 0; i < graph.components.length; i++) {
@@ -86,7 +88,7 @@ titled = new Set()) {
86
88
  if (members.length === 1 && looseSet.has(members[0])) {
87
89
  // The whole grid takes the place of the first loose node; the rest are in it.
88
90
  if (members[0] === loose[0])
89
- cursorY = placeGrid(graph, loose, sizes, cursorY, bounds);
91
+ cursorY = placeGrid(graph, loose, sizes, cursorY, bounds, grid);
90
92
  continue;
91
93
  }
92
94
  const rowHeight = new Map();
@@ -137,11 +139,13 @@ function looseNodes(graph) {
137
139
  }
138
140
  /**
139
141
  * Place `ids` row by row in `ceil(sqrt(n))` columns of equal cells, starting at
140
- * `top`, so the set grows roughly square. Returns the cursor for whatever is
141
- * stacked below.
142
+ * `top`, so the set grows roughly square. A hint can fix the column count and
143
+ * fill column by column instead. Returns the cursor for whatever is stacked below.
142
144
  */
143
- function placeGrid(graph, ids, sizes, top, bounds) {
144
- const columns = Math.ceil(Math.sqrt(ids.length));
145
+ function placeGrid(graph, ids, sizes, top, bounds, hint) {
146
+ const columns = hint?.columns ?? Math.ceil(Math.sqrt(ids.length));
147
+ const rows = Math.ceil(ids.length / columns);
148
+ const byColumn = hint?.fill === "column";
145
149
  let cellWidth = 0;
146
150
  let cellHeight = 0;
147
151
  for (const id of ids) {
@@ -155,8 +159,8 @@ function placeGrid(graph, ids, sizes, top, bounds) {
155
159
  }
156
160
  ids.forEach((id, i) => {
157
161
  const size = sizes.get(id) ?? DEFAULT_SIZE;
158
- const column = i % columns;
159
- const row = Math.floor(i / columns);
162
+ const column = byColumn ? Math.floor(i / rows) : i % columns;
163
+ const row = byColumn ? i % rows : Math.floor(i / columns);
160
164
  bounds.set(id, {
161
165
  x: column * (cellWidth + H_GAP) + (cellWidth - size.width) / 2,
162
166
  y: top + row * (cellHeight + V_GAP) + (cellHeight - size.height) / 2,
@@ -164,7 +168,6 @@ function placeGrid(graph, ids, sizes, top, bounds) {
164
168
  height: size.height,
165
169
  });
166
170
  });
167
- const rows = Math.ceil(ids.length / columns);
168
171
  return top + rows * (cellHeight + V_GAP) - V_GAP + COMPONENT_GAP;
169
172
  }
170
173
  /**
@@ -70,6 +70,24 @@ export interface SubProcessChildResult {
70
70
  parentX: number;
71
71
  parentY: number;
72
72
  }
73
+ /** How the unconnected children of an ad-hoc sub-process are arranged in their grid. */
74
+ export interface GridHint {
75
+ /** Columns in the grid; defaults to `ceil(sqrt(n))`. */
76
+ columns?: number;
77
+ /** `row` (default) reads declaration order left to right; `column` top to bottom. */
78
+ fill?: "row" | "column";
79
+ }
80
+ /**
81
+ * Placement requests the builder collects while it builds and hands to
82
+ * {@link applyAutoLayout}. They steer the layout only; nothing of them is
83
+ * written to the model or the XML.
84
+ */
85
+ export interface LayoutHints {
86
+ /** Tool grid per ad-hoc sub-process id. */
87
+ grids?: Map<string, GridHint>;
88
+ /** Side per text annotation id, overriding the side the packer would choose. */
89
+ annotationSides?: Map<string, "above" | "below">;
90
+ }
73
91
  /** Complete layout result for a process. */
74
92
  export interface LayoutResult {
75
93
  nodes: LayoutNode[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bpmnkit/core",
3
- "version": "1.5.0",
3
+ "version": "1.6.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "scripts": {
57
57
  "build": "tsc",
58
- "typecheck": "tsc --noEmit",
58
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.test.json",
59
59
  "check": "biome check .",
60
60
  "test": "vitest run",
61
61
  "check:descriptors": "tsx scripts/descriptor-report.ts",