@bpmnkit/core 0.8.0 → 1.1.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 (69) hide show
  1. package/README.md +49 -3
  2. package/dist/bpmn/agentic.js +3 -1
  3. package/dist/bpmn/auto-layout.js +184 -15
  4. package/dist/bpmn/bpmn-builder.d.ts +1 -12
  5. package/dist/bpmn/bpmn-builder.js +71 -10
  6. package/dist/bpmn/bpmn-model.d.ts +78 -0
  7. package/dist/bpmn/bpmn-parser.js +199 -41
  8. package/dist/bpmn/bpmn-serializer.js +121 -72
  9. package/dist/bpmn/bpmnlint.d.ts +153 -0
  10. package/dist/bpmn/bpmnlint.js +364 -0
  11. package/dist/bpmn/camunda-compat-data.d.ts +165 -0
  12. package/dist/bpmn/camunda-compat-data.js +423 -0
  13. package/dist/bpmn/camunda-compat-feel.d.ts +68 -0
  14. package/dist/bpmn/camunda-compat-feel.js +338 -0
  15. package/dist/bpmn/camunda-compat.d.ts +120 -0
  16. package/dist/bpmn/camunda-compat.js +1677 -0
  17. package/dist/bpmn/camunda7/juel.d.ts +41 -0
  18. package/dist/bpmn/camunda7/juel.js +333 -0
  19. package/dist/bpmn/camunda7/migrate.d.ts +72 -0
  20. package/dist/bpmn/camunda7/migrate.js +1152 -0
  21. package/dist/bpmn/compact-stream.d.ts +64 -0
  22. package/dist/bpmn/compact-stream.js +167 -0
  23. package/dist/bpmn/full-operations.js +5 -2
  24. package/dist/bpmn/label-style.d.ts +51 -0
  25. package/dist/bpmn/label-style.js +116 -0
  26. package/dist/bpmn/lint.d.ts +23 -3
  27. package/dist/bpmn/lint.js +47 -10
  28. package/dist/bpmn/optimize/bpmnlint-rules.d.ts +31 -0
  29. package/dist/bpmn/optimize/bpmnlint-rules.js +916 -0
  30. package/dist/bpmn/optimize/deploy.d.ts +8 -2
  31. package/dist/bpmn/optimize/deploy.js +16 -3
  32. package/dist/bpmn/optimize/index.js +11 -2
  33. package/dist/bpmn/optimize/types.d.ts +14 -0
  34. package/dist/bpmn/optimize/variable-flow.js +4 -1
  35. package/dist/bpmn/process-types.d.ts +112 -0
  36. package/dist/bpmn/process-types.js +490 -0
  37. package/dist/bpmn/svg.js +51 -22
  38. package/dist/dmn/dmn-parser.js +4 -3
  39. package/dist/doc/docx.d.ts +20 -0
  40. package/dist/doc/docx.js +253 -0
  41. package/dist/doc/html.d.ts +21 -0
  42. package/dist/doc/html.js +303 -0
  43. package/dist/doc/index.d.ts +7 -0
  44. package/dist/doc/index.js +5 -0
  45. package/dist/doc/markdown.d.ts +11 -0
  46. package/dist/doc/markdown.js +160 -0
  47. package/dist/doc/model.d.ts +129 -0
  48. package/dist/doc/model.js +617 -0
  49. package/dist/doc/zip.d.ts +5 -0
  50. package/dist/doc/zip.js +75 -0
  51. package/dist/form/form-parser.js +29 -28
  52. package/dist/index.d.ts +18 -0
  53. package/dist/index.js +9 -0
  54. package/dist/layout/annotations.d.ts +4 -2
  55. package/dist/layout/annotations.js +31 -2
  56. package/dist/layout/collaboration/ordering.d.ts +8 -0
  57. package/dist/layout/collaboration/ordering.js +57 -18
  58. package/dist/layout/orthogonal.d.ts +32 -0
  59. package/dist/layout/orthogonal.js +367 -0
  60. package/dist/layout/repair.d.ts +31 -0
  61. package/dist/layout/repair.js +220 -0
  62. package/dist/layout/semantic/route.js +45 -3
  63. package/dist/node/bpmnlint.d.ts +109 -0
  64. package/dist/node/bpmnlint.js +198 -0
  65. package/dist/node/index.d.ts +2 -0
  66. package/dist/node/index.js +1 -0
  67. package/dist/xml/xml-patch.d.ts +21 -0
  68. package/dist/xml/xml-patch.js +27 -1
  69. package/package.json +5 -2
@@ -0,0 +1,490 @@
1
+ import { buildFlowIndex, reachableFrom, readZeebeIoMapping, readZeebeTaskHeaders, readZeebeTaskType, } from "./optimize/utils.js";
2
+ import { analyzeVariableFlow, extractFeelIdentifiers } from "./optimize/variable-flow.js";
3
+ function isContainer(el) {
4
+ return (el.type === "subProcess" ||
5
+ el.type === "adHocSubProcess" ||
6
+ el.type === "eventSubProcess" ||
7
+ el.type === "transaction");
8
+ }
9
+ function eventDefinitions(el) {
10
+ return "eventDefinitions" in el ? el.eventDefinitions : [];
11
+ }
12
+ const isDynamic = (value) => value.trim().startsWith("=");
13
+ function addRef(map, key, ref) {
14
+ const list = map.get(key);
15
+ if (list)
16
+ list.push(ref);
17
+ else
18
+ map.set(key, [ref]);
19
+ }
20
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
21
+ const byRef = (a, b) => byText(a.processId, b.processId) || byText(a.elementId, b.elementId);
22
+ function uniqueRefs(refs) {
23
+ const seen = new Set();
24
+ const out = [];
25
+ for (const ref of [...refs].sort(byRef)) {
26
+ const key = `${ref.processId}\u0000${ref.elementId}`;
27
+ if (seen.has(key))
28
+ continue;
29
+ seen.add(key);
30
+ out.push(ref);
31
+ }
32
+ return out;
33
+ }
34
+ /** Merge per-element key maps: a key is required only when every element requires it. */
35
+ function mergeKeys(maps) {
36
+ const names = new Set();
37
+ for (const map of maps)
38
+ for (const name of map.keys())
39
+ names.add(name);
40
+ return [...names].sort(byText).map((name) => ({
41
+ name,
42
+ required: maps.every((map) => map.get(name) === true),
43
+ }));
44
+ }
45
+ function readSubscriptionKey(ext) {
46
+ const sub = ext.find((e) => e.name === "zeebe:subscription");
47
+ const key = sub?.attributes.correlationKey?.trim();
48
+ return key === undefined || key === "" ? undefined : key;
49
+ }
50
+ /**
51
+ * Read the worker-facing contract out of one or more BPMN definitions. Pure and
52
+ * deterministic: every list is sorted.
53
+ */
54
+ export function extractProcessContract(definitions) {
55
+ const all = Array.isArray(definitions)
56
+ ? definitions
57
+ : [definitions];
58
+ const processIds = new Set();
59
+ const jobs = new Map();
60
+ const dynamicJobTypes = [];
61
+ const messageRefs = new Map();
62
+ const messageKeys = new Map();
63
+ const signals = new Map();
64
+ const errors = new Map();
65
+ const escalations = new Map();
66
+ for (const defs of all) {
67
+ const errorById = new Map(defs.errors.map((e) => [e.id, e]));
68
+ const escalationById = new Map(defs.escalations.map((e) => [e.id, e]));
69
+ const messageById = new Map(defs.messages.map((m) => [m.id, m]));
70
+ const signalById = new Map(defs.signals.map((s) => [s.id, s]));
71
+ for (const process of defs.processes) {
72
+ if (process.isExecutable !== true)
73
+ continue;
74
+ processIds.add(process.id);
75
+ const flow = variableFlowIndex(process);
76
+ const topIndex = buildFlowIndex(process);
77
+ /** Error codes caught at a scope (boundary on `el`, or error event sub-processes inside `container`). */
78
+ const caughtIn = (scopeElement, container) => {
79
+ const codes = [];
80
+ let any = false;
81
+ const collect = (defsList) => {
82
+ for (const def of defsList) {
83
+ if (def.type !== "error")
84
+ continue;
85
+ const code = def.errorRef === undefined ? undefined : errorById.get(def.errorRef)?.errorCode;
86
+ if (code === undefined || code.trim() === "")
87
+ any = true;
88
+ else
89
+ codes.push(code);
90
+ }
91
+ };
92
+ if (scopeElement !== undefined) {
93
+ for (const el of container.flowElements) {
94
+ if (el.type === "boundaryEvent" && el.attachedToRef === scopeElement.id) {
95
+ collect(el.eventDefinitions);
96
+ }
97
+ }
98
+ }
99
+ return { codes, any };
100
+ };
101
+ const eventSubProcessCatches = (container) => {
102
+ const codes = [];
103
+ let any = false;
104
+ for (const el of container.flowElements) {
105
+ const isEventSub = el.type === "eventSubProcess" || (el.type === "subProcess" && el.triggeredByEvent);
106
+ if (!isEventSub || !isContainer(el))
107
+ continue;
108
+ for (const start of el.flowElements) {
109
+ if (start.type !== "startEvent")
110
+ continue;
111
+ for (const def of start.eventDefinitions) {
112
+ if (def.type !== "error")
113
+ continue;
114
+ const code = def.errorRef === undefined ? undefined : errorById.get(def.errorRef)?.errorCode;
115
+ if (code === undefined || code.trim() === "")
116
+ any = true;
117
+ else
118
+ codes.push(code);
119
+ }
120
+ }
121
+ }
122
+ return { codes, any };
123
+ };
124
+ const visit = (container, ancestors) => {
125
+ for (const el of container.flowElements) {
126
+ const ref = {
127
+ processId: process.id,
128
+ elementId: el.id,
129
+ elementType: el.type,
130
+ };
131
+ collectEvents(el, ref);
132
+ const jobType = el.type === "userTask" ? null : readZeebeTaskType(el.extensionElements);
133
+ if (jobType !== null && jobType.trim() !== "") {
134
+ if (isDynamic(jobType))
135
+ dynamicJobTypes.push(ref);
136
+ else
137
+ addJob(jobType, el, ref, { ancestors, container });
138
+ }
139
+ if (isContainer(el))
140
+ visit(el, [el, ...ancestors]);
141
+ }
142
+ };
143
+ const collectEvents = (el, ref) => {
144
+ const messageRefIds = [];
145
+ if ((el.type === "sendTask" || el.type === "receiveTask") && el.messageRef) {
146
+ messageRefIds.push(el.messageRef);
147
+ }
148
+ for (const def of eventDefinitions(el)) {
149
+ if (def.type === "message" && def.messageRef)
150
+ messageRefIds.push(def.messageRef);
151
+ if (def.type === "signal" && def.signalRef) {
152
+ const name = signalById.get(def.signalRef)?.name;
153
+ if (name && !isDynamic(name))
154
+ addRef(signals, name, ref);
155
+ }
156
+ if (def.type === "error" && def.errorRef) {
157
+ const code = errorById.get(def.errorRef)?.errorCode;
158
+ if (code && !isDynamic(code))
159
+ addRef(errors, code, ref);
160
+ }
161
+ if (def.type === "escalation" && def.escalationRef) {
162
+ const code = escalationById.get(def.escalationRef)?.escalationCode;
163
+ if (code && !isDynamic(code))
164
+ addRef(escalations, code, ref);
165
+ }
166
+ }
167
+ for (const id of messageRefIds) {
168
+ const message = messageById.get(id);
169
+ const name = message?.name;
170
+ if (!name || isDynamic(name))
171
+ continue;
172
+ addRef(messageRefs, name, ref);
173
+ const key = readSubscriptionKey(el.extensionElements) ??
174
+ readSubscriptionKey(message.extensionElements ?? []);
175
+ const keys = messageKeys.get(name) ?? new Set();
176
+ if (key !== undefined)
177
+ keys.add(key);
178
+ messageKeys.set(name, keys);
179
+ }
180
+ };
181
+ const addJob = (jobType, el, ref, scope) => {
182
+ const acc = jobs.get(jobType) ?? {
183
+ elements: [],
184
+ variables: [],
185
+ output: [],
186
+ headers: [],
187
+ errors: new Set(),
188
+ anyError: false,
189
+ };
190
+ jobs.set(jobType, acc);
191
+ acc.elements.push(ref);
192
+ const io = readZeebeIoMapping(el.extensionElements);
193
+ const inputTargets = (io?.inputs ?? [])
194
+ .map((input) => input.target.trim())
195
+ .filter((target) => target !== "");
196
+ const variables = new Map();
197
+ if (inputTargets.length > 0) {
198
+ for (const target of inputTargets)
199
+ variables.set(target, true);
200
+ }
201
+ else {
202
+ for (const name of flow.scopeBefore(el, scope))
203
+ variables.set(name, false);
204
+ }
205
+ acc.variables.push(variables);
206
+ const output = new Map();
207
+ const outputs = (io?.outputs ?? []).filter((o) => o.target.trim() !== "");
208
+ if (outputs.length > 0) {
209
+ const locals = new Set(inputTargets);
210
+ for (const mapping of outputs) {
211
+ const plain = /^=?\s*[A-Za-z_$][\w$]*(\s*\.\s*[A-Za-z_$][\w$]*)*\s*$/.test(mapping.source);
212
+ for (const name of extractFeelIdentifiers(mapping.source)) {
213
+ if (locals.has(name))
214
+ continue;
215
+ output.set(name, (output.get(name) ?? false) || plain);
216
+ }
217
+ }
218
+ }
219
+ else if (scope.ancestors.length === 0) {
220
+ const downstream = reachableFrom(topIndex.bySource.get(el.id)?.map((f) => f.targetRef) ?? [], topIndex.bySource);
221
+ for (const id of [...downstream].sort(byText)) {
222
+ if (id === el.id)
223
+ continue;
224
+ for (const name of flow.consumedBy.get(id) ?? []) {
225
+ if (!flow.produced.has(name))
226
+ output.set(name, false);
227
+ }
228
+ }
229
+ }
230
+ acc.output.push(output);
231
+ const headers = new Map();
232
+ for (const header of readZeebeTaskHeaders(el.extensionElements)?.headers ?? []) {
233
+ if (header.key !== "")
234
+ headers.set(header.key, header.value);
235
+ }
236
+ acc.headers.push(headers);
237
+ const scopes = [
238
+ { element: el, container: scope.container },
239
+ ];
240
+ let containerOf = process;
241
+ for (let i = scope.ancestors.length - 1; i >= 0; i--) {
242
+ const ancestor = scope.ancestors[i];
243
+ scopes.push({ element: ancestor, container: containerOf });
244
+ if (isContainer(ancestor))
245
+ containerOf = ancestor;
246
+ }
247
+ const catches = [
248
+ ...scopes.map((s) => caughtIn(s.element, s.container)),
249
+ eventSubProcessCatches(process),
250
+ ...scope.ancestors.filter(isContainer).map(eventSubProcessCatches),
251
+ ];
252
+ for (const c of catches) {
253
+ for (const code of c.codes)
254
+ acc.errors.add(code);
255
+ if (c.any)
256
+ acc.anyError = true;
257
+ }
258
+ };
259
+ visit(process, []);
260
+ }
261
+ }
262
+ const jobList = [...jobs.entries()]
263
+ .sort(([a], [b]) => byText(a, b))
264
+ .map(([type, acc]) => {
265
+ const headerKeys = new Set();
266
+ for (const map of acc.headers)
267
+ for (const key of map.keys())
268
+ headerKeys.add(key);
269
+ return {
270
+ type,
271
+ elements: uniqueRefs(acc.elements),
272
+ variables: mergeKeys(acc.variables),
273
+ output: mergeKeys(acc.output),
274
+ headers: [...headerKeys].sort(byText).map((key) => {
275
+ const values = new Set();
276
+ for (const map of acc.headers) {
277
+ const value = map.get(key);
278
+ if (value !== undefined)
279
+ values.add(value);
280
+ }
281
+ return {
282
+ key,
283
+ values: [...values].sort(byText),
284
+ required: acc.headers.every((map) => map.has(key)),
285
+ };
286
+ }),
287
+ errors: acc.anyError ? "any" : [...acc.errors].sort(byText),
288
+ };
289
+ });
290
+ const codes = (map) => [...map.entries()]
291
+ .sort(([a], [b]) => byText(a, b))
292
+ .map(([code, refs]) => ({ code, elements: uniqueRefs(refs) }));
293
+ return {
294
+ processIds: [...processIds].sort(byText),
295
+ jobs: jobList,
296
+ messages: [...messageRefs.entries()]
297
+ .sort(([a], [b]) => byText(a, b))
298
+ .map(([name, refs]) => ({
299
+ name,
300
+ correlationKeys: [...(messageKeys.get(name) ?? [])].sort(byText),
301
+ elements: uniqueRefs(refs),
302
+ })),
303
+ signals: codes(signals),
304
+ errors: codes(errors),
305
+ escalations: codes(escalations),
306
+ dynamicJobTypes: uniqueRefs(dynamicJobTypes),
307
+ };
308
+ }
309
+ /** What the variable-flow analysis knows about one process, indexed for lookup. */
310
+ function variableFlowIndex(process) {
311
+ // The analysis counts `zeebe:input` targets as produced, but they are local to
312
+ // their element: nothing downstream sees one unless something else also sets it.
313
+ const inputTargets = new Set();
314
+ const setGlobally = new Set();
315
+ for (const el of process.flowElements) {
316
+ const io = readZeebeIoMapping(el.extensionElements);
317
+ for (const input of io?.inputs ?? [])
318
+ inputTargets.add(input.target.trim());
319
+ for (const output of io?.outputs ?? [])
320
+ setGlobally.add(output.target.trim());
321
+ for (const ext of el.extensionElements) {
322
+ const result = ext.attributes.resultVariable;
323
+ if (ext.name === "zeebe:calledDecision" && result)
324
+ setGlobally.add(result);
325
+ }
326
+ }
327
+ const visible = (name) => !inputTargets.has(name) || setGlobally.has(name);
328
+ const edgeScope = new Map();
329
+ const consumedBy = new Map();
330
+ const produced = new Set();
331
+ for (const f of analyzeVariableFlow(process)) {
332
+ if (f.id.startsWith("data-flow/edge-scope:")) {
333
+ const flowId = f.elementIds[0];
334
+ if (flowId !== undefined)
335
+ edgeScope.set(flowId, (f.produces ?? []).filter(visible));
336
+ }
337
+ else if (f.id.startsWith("data-flow/role:")) {
338
+ const elementId = f.elementIds[0];
339
+ if (elementId !== undefined)
340
+ consumedBy.set(elementId, f.consumes ?? []);
341
+ for (const name of f.produces ?? [])
342
+ if (visible(name))
343
+ produced.add(name);
344
+ }
345
+ }
346
+ return {
347
+ consumedBy,
348
+ produced,
349
+ /**
350
+ * Variables in scope on the element's incoming flows — or, for an element
351
+ * with none known, on the incoming flows of its nearest enclosing scope.
352
+ */
353
+ scopeBefore(el, scope) {
354
+ for (const candidate of [el, ...scope.ancestors]) {
355
+ const names = new Set();
356
+ let known = false;
357
+ for (const flowId of candidate.incoming) {
358
+ const vars = edgeScope.get(flowId);
359
+ if (vars === undefined)
360
+ continue;
361
+ known = true;
362
+ for (const name of vars)
363
+ names.add(name);
364
+ }
365
+ if (known)
366
+ return [...names];
367
+ }
368
+ return [];
369
+ },
370
+ };
371
+ }
372
+ // ---------------------------------------------------------------------------
373
+ // Rendering
374
+ // ---------------------------------------------------------------------------
375
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
376
+ const propertyKey = (name) => (IDENTIFIER.test(name) ? name : JSON.stringify(name));
377
+ const literal = (value) => JSON.stringify(value);
378
+ const comment = (text) => text.replace(/\*\//g, "*\\/").replace(/[\r\n]+/g, " ");
379
+ const union = (values, empty = "never") => values.length === 0 ? empty : values.map(literal).join(" | ");
380
+ function pascalCase(value) {
381
+ const words = value.split(/[^A-Za-z0-9]+/).filter((w) => w !== "");
382
+ const joined = words.map((w) => w[0].toUpperCase() + w.slice(1)).join("");
383
+ if (joined === "")
384
+ return "Job";
385
+ return /^[0-9]/.test(joined) ? `Job${joined}` : joined;
386
+ }
387
+ /** Assign every job type a distinct TypeScript name stem, in sorted job type order. */
388
+ function jobTypeNames(types) {
389
+ const taken = new Set();
390
+ const out = new Map();
391
+ for (const type of types) {
392
+ const base = pascalCase(type);
393
+ let name = base;
394
+ for (let n = 2; taken.has(name); n++)
395
+ name = `${base}${n}`;
396
+ taken.add(name);
397
+ out.set(type, name);
398
+ }
399
+ return out;
400
+ }
401
+ function refList(refs) {
402
+ return refs.map((r) => `${r.processId}#${r.elementId}`).join(", ");
403
+ }
404
+ function renderKeys(name, keys, doc) {
405
+ const lines = [`/** ${comment(doc)} */`, `export interface ${name} {`];
406
+ for (const key of keys) {
407
+ lines.push(`\t${propertyKey(key.name)}${key.required ? "" : "?"}: unknown`);
408
+ }
409
+ lines.push("}");
410
+ return lines;
411
+ }
412
+ function renderConstUnion(constName, typeName, values) {
413
+ return [
414
+ `export const ${constName} = [${values.map(literal).join(", ")}] as const`,
415
+ `export type ${typeName} = (typeof ${constName})[number]`,
416
+ ];
417
+ }
418
+ /**
419
+ * Render the {@link ProcessContract} of one or more BPMN definitions as
420
+ * TypeScript source. The output is deterministic (everything sorted) and
421
+ * starts with a "do not edit" header.
422
+ *
423
+ * @example
424
+ * ```ts
425
+ * import { Bpmn, generateProcessTypes } from "@bpmnkit/core"
426
+ * const source = generateProcessTypes(Bpmn.parse(xml))
427
+ * ```
428
+ */
429
+ export function generateProcessTypes(definitions, options = {}) {
430
+ const contract = extractProcessContract(definitions);
431
+ const banner = options.banner ?? "generated by casen gen types — do not edit";
432
+ const names = jobTypeNames(contract.jobs.map((j) => j.type));
433
+ const out = [
434
+ `// ${comment(banner)}`,
435
+ "//",
436
+ "// Keys are exact; values are `unknown` because FEEL cannot be typed statically.",
437
+ "// Optional keys are ones the model does not guarantee. See the typed workers guide:",
438
+ "// https://bpmnkit.com/docs/guides/typed-workers",
439
+ ];
440
+ if (contract.dynamicJobTypes.length > 0) {
441
+ out.push(`// Skipped dynamic job types (FEEL expressions): ${comment(refList(contract.dynamicJobTypes))}`);
442
+ }
443
+ out.push("");
444
+ out.push(...renderConstUnion("processIds", "ProcessId", contract.processIds), "");
445
+ out.push(...renderConstUnion("jobTypes", "JobType", contract.jobs.map((j) => j.type)), "");
446
+ for (const job of contract.jobs) {
447
+ const stem = names.get(job.type);
448
+ const where = `Job type ${literal(job.type)} — ${refList(job.elements)}`;
449
+ out.push(...renderKeys(`${stem}Variables`, job.variables, `Variables of ${where}`), "");
450
+ out.push(...renderKeys(`${stem}Output`, job.output, `Output of ${where}`), "");
451
+ out.push(`/** Task headers of ${comment(where)} */`, `export interface ${stem}Headers {`);
452
+ for (const header of job.headers) {
453
+ out.push(`\treadonly ${propertyKey(header.key)}${header.required ? "" : "?"}: ${union(header.values)}`);
454
+ }
455
+ out.push("}", "");
456
+ }
457
+ out.push("/** Job type → the contract a worker for it can rely on. */", "export type JobTypes = {");
458
+ for (const job of contract.jobs) {
459
+ const stem = names.get(job.type);
460
+ const processes = [...new Set(job.elements.map((e) => e.processId))];
461
+ const errorsType = job.errors === "any" ? "string" : union(job.errors);
462
+ out.push(`\t${literal(job.type)}: {`, `\t\tvariables: ${stem}Variables`, `\t\toutput: ${stem}Output`, `\t\theaders: ${stem}Headers`, `\t\terrors: ${errorsType}`, `\t\tprocessIds: ${union(processes)}`, `\t\telementIds: ${union(job.elements.map((e) => e.elementId))}`, "\t}");
463
+ }
464
+ out.push("}", "");
465
+ out.push("/** Message name → the correlation key expressions its subscriptions use. */");
466
+ out.push("export interface Messages {");
467
+ for (const message of contract.messages) {
468
+ const keys = message.correlationKeys;
469
+ out.push(`\t/** ${comment(keys.length > 0
470
+ ? `Correlation key: ${keys.join(" | ")} — ${refList(message.elements)}`
471
+ : `No correlation key — ${refList(message.elements)}`)} */`, `\t${propertyKey(message.name)}: { correlationKey: ${union(keys, "undefined")} }`);
472
+ }
473
+ out.push("}");
474
+ out.push(...renderConstUnion("messageNames", "MessageName", contract.messages.map((m) => m.name)), "");
475
+ const codeSection = (constName, typeName, doc, list) => {
476
+ out.push("/**", ` * ${doc}`);
477
+ for (const item of list)
478
+ out.push(` * - ${comment(`${item.code} — ${refList(item.elements)}`)}`);
479
+ out.push(" */", ...renderConstUnion(constName, typeName, list.map((c) => c.code)), "");
480
+ };
481
+ codeSection("signalNames", "SignalName", "Signal names thrown or caught.", contract.signals);
482
+ codeSection("errorCodes", "ErrorCode", "Error codes thrown or caught.", contract.errors);
483
+ codeSection("escalationCodes", "EscalationCode", "Escalation codes thrown or caught.", contract.escalations);
484
+ // An empty body renders as `{}` rather than a brace pair split over two lines.
485
+ return `${out
486
+ .join("\n")
487
+ .replace(/\{\n\}/g, "{}")
488
+ .trimEnd()}\n`;
489
+ }
490
+ //# sourceMappingURL=process-types.js.map
package/dist/bpmn/svg.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { collectLabelStyles, labelFontCss, resolveLabelFont, } from "./label-style.js";
1
2
  const LIGHT = {
2
3
  bg: "#f8f9fa",
3
4
  shapeFill: "#ffffff",
@@ -50,6 +51,11 @@ export function exportSvg(defs, options) {
50
51
  return emptySvg(t);
51
52
  // Build model index for name/type lookups
52
53
  const idx = buildIndex(defs);
54
+ const labelStyles = collectLabelStyles(defs);
55
+ const fontOf = (label) => {
56
+ const font = resolveLabelFont(label, labelStyles);
57
+ return font ? labelFontCss(font, DEFAULT_FAMILY, DEFAULT_SIZE) : undefined;
58
+ };
53
59
  // ── Bounding box ──────────────────────────────────────────────────────────
54
60
  let minX = Number.POSITIVE_INFINITY;
55
61
  let minY = Number.POSITIVE_INFINITY;
@@ -115,7 +121,7 @@ export function exportSvg(defs, options) {
115
121
  // Edge label
116
122
  if (flow?.name && edge.label?.bounds) {
117
123
  const { x, y, width, height } = edge.label.bounds;
118
- edgeParts.push(labelSvg(flow.name, x + width / 2, y + height / 2, width - 4, t));
124
+ edgeParts.push(labelSvg(flow.name, x + width / 2, y + height / 2, width - 4, t, false, fontOf(edge.label)));
119
125
  }
120
126
  }
121
127
  // ── Shapes ────────────────────────────────────────────────────────────────
@@ -128,6 +134,7 @@ export function exportSvg(defs, options) {
128
134
  const { x, y, width, height } = shape.bounds;
129
135
  const el = idx.elements.get(shape.bpmnElement);
130
136
  const type = el?.type ?? "";
137
+ const font = fontOf(shape.label);
131
138
  let inner;
132
139
  let isContainer = false;
133
140
  if (isEvent(type)) {
@@ -140,14 +147,14 @@ export function exportSvg(defs, options) {
140
147
  // Pool, lane, or annotation
141
148
  const annotation = idx.annotations.get(shape.bpmnElement);
142
149
  if (annotation !== undefined) {
143
- inner = renderAnnotation(annotation.text, width, height, t);
150
+ inner = renderAnnotation(annotation.text, width, height, t, font);
144
151
  }
145
152
  else if (idx.participants.has(shape.bpmnElement)) {
146
- inner = renderPool(idx.participants.get(shape.bpmnElement), width, height, t);
153
+ inner = renderPool(idx.participants.get(shape.bpmnElement), width, height, t, font);
147
154
  isContainer = true;
148
155
  }
149
156
  else if (idx.lanes.has(shape.bpmnElement)) {
150
- inner = renderLane(idx.lanes.get(shape.bpmnElement), width, height, t);
157
+ inner = renderLane(idx.lanes.get(shape.bpmnElement), width, height, t, font);
151
158
  isContainer = true;
152
159
  }
153
160
  else {
@@ -164,7 +171,7 @@ export function exportSvg(defs, options) {
164
171
  type === "eventSubProcess" ||
165
172
  type === "transaction") &&
166
173
  shape.isExpanded === true;
167
- inner = renderTask(el, width, height, t, { expanded: isExpandedContainer });
174
+ inner = renderTask(el, width, height, t, { expanded: isExpandedContainer, font });
168
175
  if (isExpandedContainer)
169
176
  isContainer = true;
170
177
  }
@@ -186,7 +193,7 @@ export function exportSvg(defs, options) {
186
193
  width: 80,
187
194
  height: 20,
188
195
  };
189
- labelParts.push(labelSvg(el.name, lb.x + lb.width / 2, lb.y + lb.height / 2, lb.width - 4, t, true));
196
+ labelParts.push(labelSvg(el.name, lb.x + lb.width / 2, lb.y + lb.height / 2, lb.width - 4, t, true, font));
190
197
  }
191
198
  }
192
199
  // ── Assemble SVG ──────────────────────────────────────────────────────────
@@ -227,7 +234,16 @@ function isGateway(type) {
227
234
  }
228
235
  // ── Text ──────────────────────────────────────────────────────────────────────
229
236
  const AVG_CHAR_PX = 6.5;
230
- function wrapText(text, maxPx) {
237
+ const DEFAULT_FAMILY = "system-ui,-apple-system,sans-serif";
238
+ const DEFAULT_SIZE = 11;
239
+ const DEFAULT_LINE_H = 14;
240
+ /** Estimated glyph width for a label font — scaled from the 11px default. */
241
+ function charPx(font) {
242
+ if (!font)
243
+ return AVG_CHAR_PX;
244
+ return AVG_CHAR_PX * (font.fontSize / DEFAULT_SIZE) * (font.fontWeight === "bold" ? 1.1 : 1);
245
+ }
246
+ function wrapText(text, maxPx, charW = AVG_CHAR_PX) {
231
247
  if (!text.trim())
232
248
  return [];
233
249
  const words = text.split(/\s+/);
@@ -235,7 +251,7 @@ function wrapText(text, maxPx) {
235
251
  let line = "";
236
252
  for (const word of words) {
237
253
  const candidate = line ? `${line} ${word}` : word;
238
- if (candidate.length * AVG_CHAR_PX <= maxPx) {
254
+ if (candidate.length * charW <= maxPx) {
239
255
  line = candidate;
240
256
  }
241
257
  else if (line) {
@@ -257,18 +273,31 @@ function esc(s) {
257
273
  .replace(/>/g, "&gt;")
258
274
  .replace(/"/g, "&quot;");
259
275
  }
260
- function textStyle(t) {
261
- return `fill:${t.text};font-family:system-ui,-apple-system,sans-serif;font-size:11px;text-anchor:middle;dominant-baseline:central;paint-order:stroke;stroke:${t.textHalo};stroke-width:4px;stroke-linejoin:round`;
276
+ function fontStyle(font) {
277
+ if (!font)
278
+ return `font-family:${DEFAULT_FAMILY};font-size:${DEFAULT_SIZE}px`;
279
+ let out = `font-family:${font.fontFamily};font-size:${font.fontSize}px`;
280
+ if (font.fontWeight !== "normal")
281
+ out += `;font-weight:${font.fontWeight}`;
282
+ if (font.fontStyle !== "normal")
283
+ out += `;font-style:${font.fontStyle}`;
284
+ if (font.textDecoration !== "none")
285
+ out += `;text-decoration:${font.textDecoration}`;
286
+ return out;
287
+ }
288
+ /** A label's inline style, XML-escaped for a double-quoted attribute. */
289
+ function textStyle(t, font) {
290
+ return esc(`fill:${t.text};${fontStyle(font)};text-anchor:middle;dominant-baseline:central;paint-order:stroke;stroke:${t.textHalo};stroke-width:4px;stroke-linejoin:round`);
262
291
  }
263
292
  /**
264
293
  * Generates SVG text element(s) for a label centred at (cx, cy).
265
294
  * topAlign=true makes multi-line text flow downward from cy rather than
266
295
  * being centred around it — prevents long labels from overlapping the shape above.
267
296
  */
268
- function labelSvg(text, cx, cy, maxWidth, t, topAlign = false) {
269
- const lines = wrapText(text, maxWidth);
270
- const lineH = 14;
271
- const style = textStyle(t);
297
+ function labelSvg(text, cx, cy, maxWidth, t, topAlign = false, font) {
298
+ const lines = wrapText(text, maxWidth, charPx(font));
299
+ const lineH = font ? (font.fontSize * DEFAULT_LINE_H) / DEFAULT_SIZE : DEFAULT_LINE_H;
300
+ const style = textStyle(t, font);
272
301
  if (lines.length === 1) {
273
302
  return `<text style="${style}" x="${cx}" y="${cy}">${esc(lines[0] ?? text)}</text>`;
274
303
  }
@@ -476,10 +505,10 @@ function renderTask(el, width, height, t, options) {
476
505
  // subprocess header, so it doesn't collide with the child shapes drawn
477
506
  // inside it (a centered label would land right where children are placed).
478
507
  if (options?.expanded) {
479
- out += labelSvg(el.name, width / 2, 14, width - 16, t, true);
508
+ out += labelSvg(el.name, width / 2, 14, width - 16, t, true, options.font);
480
509
  }
481
510
  else {
482
- out += labelSvg(el.name, width / 2, height / 2, width - 16, t);
511
+ out += labelSvg(el.name, width / 2, height / 2, width - 16, t, false, options?.font);
483
512
  }
484
513
  }
485
514
  if (type === "subProcess" ||
@@ -502,31 +531,31 @@ function renderGateway(el, width, height, t) {
502
531
  }
503
532
  return out;
504
533
  }
505
- function renderPool(participant, width, height, t) {
534
+ function renderPool(participant, width, height, t, font) {
506
535
  const bodyStyle = `fill:${t.shapeFill};stroke:${t.shapeStroke};stroke-width:1.5`;
507
536
  const headerStyle = `fill:${t.poolHeader};stroke:${t.shapeStroke};stroke-width:1.5`;
508
537
  let out = `<rect x="0" y="0" width="${width}" height="${height}" style="${bodyStyle}"/>` +
509
538
  `<rect x="0" y="0" width="30" height="${height}" style="${headerStyle}"/>`;
510
539
  if (participant?.name) {
511
- out += `<text style="${textStyle(t)}" transform="translate(15 ${height / 2}) rotate(-90)">${esc(participant.name)}</text>`;
540
+ out += `<text style="${textStyle(t, font)}" transform="translate(15 ${height / 2}) rotate(-90)">${esc(participant.name)}</text>`;
512
541
  }
513
542
  return out;
514
543
  }
515
- function renderLane(lane, width, height, t) {
544
+ function renderLane(lane, width, height, t, font) {
516
545
  const bodyStyle = `fill:${t.shapeFill};stroke:${t.shapeStroke};stroke-width:1.5`;
517
546
  const headerStyle = `fill:${t.poolHeader};stroke:${t.shapeStroke};stroke-width:1.5`;
518
547
  let out = `<rect x="0" y="0" width="${width}" height="${height}" style="${bodyStyle}"/>` +
519
548
  `<rect x="0" y="0" width="30" height="${height}" style="${headerStyle}"/>`;
520
549
  if (lane?.name) {
521
- out += `<text style="${textStyle(t)}" transform="translate(15 ${height / 2}) rotate(-90)">${esc(lane.name)}</text>`;
550
+ out += `<text style="${textStyle(t, font)}" transform="translate(15 ${height / 2}) rotate(-90)">${esc(lane.name)}</text>`;
522
551
  }
523
552
  return out;
524
553
  }
525
- function renderAnnotation(text, width, height, t) {
554
+ function renderAnnotation(text, width, height, t, font) {
526
555
  const pathStyle = `fill:none;stroke:${t.shapeStroke};stroke-width:1.5`;
527
556
  let out = `<path d="M${width} 0 L0 0 L0 ${height} L${width} ${height}" style="${pathStyle}"/>`;
528
557
  if (text) {
529
- out += labelSvg(text, width / 2, height / 2, width - 8, t);
558
+ out += labelSvg(text, width / 2, height / 2, width - 8, t, false, font);
530
559
  }
531
560
  return out;
532
561
  }