@uipath/maestro-builder-sdk 6.94.5 → 6.95.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.
@@ -4,41 +4,290 @@
4
4
  *
5
5
  * Usage:
6
6
  * bpmn-merge <original.bpmn> <edited.bpmn> [-o merged.bpmn] [--baseline <baseline.bpmn>]
7
+ * bpmn-merge <original.bpmn> <edited.bpmn.ts> [-o <original.bpmn>] [--baseline <baseline.bpmn>]
8
+ * [--style nested|explicit] [--connectors lift|verbatim] [--keep-flow-ids] [--keep-unused-bindings]
9
+ * [--library <dir>] [--connectors-local <dir>] [--bindings <file>] [--resources <file>]
7
10
  *
8
11
  * `edited.bpmn` is compile(decompile(original)) after your edits. `--baseline` is
9
12
  * compile(decompile(original)) BEFORE any edit — supplying it enables the delta merge, so
10
13
  * every element you did not touch is emitted from the original byte for byte. Omit it for
11
14
  * a two-way merge (take the edited process, keep the original diagram). See merge.ts.
15
+ *
16
+ * An edited SOURCE (`.bpmn.ts`) needs neither file (UiPath/builder-sdk#1871): merge
17
+ * compiles it as `compile` would, derives the baseline by decompiling the original and
18
+ * compiling that, in memory, and writes only the merged result — over the original
19
+ * unless `-o` says otherwise. The library, bindings and resources are `compile`'s, and
20
+ * both compiles use them. See merge-source.ts.
21
+ *
22
+ * The source must carry the stamp `bpmn decompile` writes on its first line
23
+ * (decompile-stamp.ts). Merge refuses, writing nothing, when there is no stamp, and when
24
+ * the source it decompiles from the original now does not have the digest the stamp
25
+ * records — the derived baseline would then hold the original's later changes, and the
26
+ * merge would revert them. A change decompile does not read (line endings, the layout
27
+ * `bpmn format` rewrites) leaves the digest alone and merges. It derives the
28
+ * baseline with the decompile options the stamp records; a decompile flag given here
29
+ * that disagrees with the stamp is refused, one that agrees is accepted. With
30
+ * `--baseline` the stamp is not checked: the baseline is the caller's.
31
+ *
32
+ * After it writes over the original, merge decompiles the merged file the same way and
33
+ * rewrites the source's stamp with that digest, options kept, so the next
34
+ * edit-and-merge round on the same source passes the check; under `--baseline` too,
35
+ * when the source has a readable stamp. With `-o` elsewhere the original and the
36
+ * stamp stay as they were.
12
37
  */
13
- import { reportResult } from '../cli-result.js';
38
+ import { reportCompileRefusal, reportDiagnostics, reportResult } from '../cli-result.js';
14
39
  import { readFileSync, writeFileSync } from 'node:fs';
15
40
  import { basename, resolve } from 'node:path';
41
+ import { fileURLToPath } from 'node:url';
16
42
  import { mergeBpmn } from './merge.js';
43
+ import { decompiledDigest, deriveBaseline } from './merge-source.js';
44
+ import { readStamp, sourceDigest, restampSource, STAMP_MARKER } from './decompile-stamp.js';
45
+ import { loadBuiltBpmn } from './load.js';
46
+ import { serialize } from './serialize.js';
47
+ import { Bindings } from '../core/bindings.js';
48
+ import { openCliLibrary } from '../core/cli-library.js';
49
+ import { readCliResources } from '../registry/prepare/resources.js';
50
+ import { ensureTypeScriptRuntime } from '../node-runtime.js';
51
+ import { defaultBindingsFile, defaultResourcesFile } from '../workdir.js';
17
52
  import { flagValue, runWhenInvokedDirectly } from '../cli-run.js';
18
- export function run(argv) {
53
+ const USAGE = 'usage: bpmn-merge <original.bpmn> <edited.bpmn | edited.bpmn.ts> [-o merged.bpmn] [--baseline <baseline.bpmn>]\n' +
54
+ ' an edited .bpmn.ts is compiled here, the baseline derived from the original, and the\n' +
55
+ ' merge written over the original unless -o is given. The source must carry the stamp\n' +
56
+ ' `bpmn decompile` writes, and the original must be unchanged since; the decompile options\n' +
57
+ ' come from the stamp. It also takes\n' +
58
+ ' [--style nested|explicit] [--connectors lift|verbatim] [--keep-flow-ids] [--keep-unused-bindings]\n' +
59
+ ' (each refused when it disagrees with the stamp)\n' +
60
+ ' [--library <dir>] [--connectors-local <dir>] [--bindings <file>] [--resources <file>]';
61
+ /** Flags that take a value, so the value is not read as a positional. */
62
+ const VALUE_FLAGS = new Set([
63
+ '-o', '--baseline', '--style', '--connectors', '--library', '--connectors-local', '--bindings', '--resources',
64
+ ]);
65
+ const BARE_FLAGS = new Set(['--keep-flow-ids', '--keep-unused-bindings']);
66
+ /** The decompile options a stamp records, as `deriveBaseline` and `decompiledDigest` take them. */
67
+ function stampedDecompile(stamp, library) {
68
+ return {
69
+ sdkEntry: fileURLToPath(new URL('./bpmn-sdk.js', import.meta.url)),
70
+ style: stamp.style,
71
+ keepFlowIds: stamp.keepFlowIds,
72
+ keepUnusedBindings: stamp.keepUnusedBindings,
73
+ ...(stamp.connectors === 'lift' && library ? { liftLibrary: library } : {}),
74
+ };
75
+ }
76
+ /** Refuse the merge with a coded diagnostic; nothing has been written. */
77
+ function refuseMerge(code, message) {
78
+ console.error(`bpmn-merge: ${message}`);
79
+ reportDiagnostics([{ level: 'error', code, message }]);
80
+ return 1;
81
+ }
82
+ /** The way on from a refused source merge. */
83
+ function redoAdvice(originalPath) {
84
+ return (`Decompile ${basename(originalPath)} again (\`bpmn decompile\`) and reapply the edit to the new source, ` +
85
+ 'or merge with --baseline <file>, the compile of the unedited decompile.');
86
+ }
87
+ /**
88
+ * Check the decompile flags, then — unless `--baseline` was given — read the source's
89
+ * stamp, refuse a missing or unreadable one and a flag that disagrees with it. Returns
90
+ * the stamp (`undefined` under `--baseline`), or the exit code. Whether the original
91
+ * still decompiles to the stamped digest is checked once the baseline is derived
92
+ * (`compileSides`).
93
+ */
94
+ function decompileOptions(argv, editedPath, originalPath, hasBaseline) {
95
+ const style = flagValue(argv, '--style');
96
+ if (style !== undefined && style !== 'explicit' && style !== 'nested') {
97
+ console.error(`bpmn-merge: --style must be explicit or nested, not "${style}"`);
98
+ return 2;
99
+ }
100
+ const connectors = flagValue(argv, '--connectors');
101
+ if (connectors !== undefined && connectors !== 'lift' && connectors !== 'verbatim') {
102
+ console.error(`bpmn-merge: --connectors must be lift or verbatim, not "${connectors}"`);
103
+ return 2;
104
+ }
105
+ if (hasBaseline)
106
+ return undefined;
107
+ const edited = basename(editedPath);
108
+ const original = basename(originalPath);
109
+ const redo = redoAdvice(originalPath);
110
+ const stamp = readStamp(readFileSync(editedPath, 'utf8'));
111
+ if (stamp === undefined) {
112
+ return refuseMerge('MERGE_SOURCE_NOT_STAMPED', `${edited} has no \`${STAMP_MARKER.trim()}\` line, so merge cannot tell whether ${original} is still the file ` +
113
+ `it was decompiled from, or how it was decompiled. Nothing was written. ${redo}`);
114
+ }
115
+ if ('error' in stamp) {
116
+ return refuseMerge('MERGE_SOURCE_STAMP_UNREADABLE', `${edited}'s decompile stamp is unreadable — ${stamp.error}. Nothing was written. ${redo}`);
117
+ }
118
+ const given = [
119
+ ['--style', style, stamp.style],
120
+ ['--connectors', connectors, stamp.connectors],
121
+ ['--keep-flow-ids', argv.includes('--keep-flow-ids') || undefined, stamp.keepFlowIds],
122
+ ['--keep-unused-bindings', argv.includes('--keep-unused-bindings') || undefined, stamp.keepUnusedBindings],
123
+ ];
124
+ for (const [flag, value, recorded] of given) {
125
+ if (value === undefined || value === recorded)
126
+ continue;
127
+ const said = typeof value === 'string' ? `${flag} ${value}` : flag;
128
+ const records = typeof recorded === 'string' ? `${flag.slice(2)}=${recorded}` : `no ${flag.slice(2)}`;
129
+ return refuseMerge('MERGE_OPTION_CONFLICT', `${said} disagrees with ${edited}'s decompile stamp, which records ${records}. ` +
130
+ 'Merge derives the baseline with the options the stamp records; drop the flag. Nothing was written.');
131
+ }
132
+ return stamp;
133
+ }
134
+ /**
135
+ * Compile the edited source and, unless `--baseline` was given, derive the baseline
136
+ * from the original — both in memory, with the decompile options the source's stamp
137
+ * records — and refuse when the source derived from the original does not have the
138
+ * stamped digest. A refused compile is reported as `compile` reports it, and its exit
139
+ * code returned instead.
140
+ */
141
+ async function compileSides(argv, editedPath, originalPath, original, explicitBaseline, decompiled) {
142
+ // Loading authored TypeScript, and the nested decompile's verification, both import
143
+ // `.ts`; this re-executes under --experimental-strip-types where Node needs the flag.
144
+ ensureTypeScriptRuntime();
145
+ // `compile`'s context, shared by both compiles so they differ only by the edit.
146
+ const library = openCliLibrary(argv);
147
+ const resources = readCliResources(argv, defaultResourcesFile());
148
+ const opts = {
149
+ bindings: new Bindings(flagValue(argv, '--bindings') ?? defaultBindingsFile()),
150
+ ...(library ? { library } : {}),
151
+ ...(resources ? { resources } : {}),
152
+ };
153
+ // Two catches, as `compile` has them, so a broken source fails here exactly as it
154
+ // fails there. While the source loads, only a builder refusal is printed by its code;
155
+ // a syntax error or a missing import propagates with its own code and the JSON
156
+ // `error` field, not as a COMPILE_FAILED refusal.
157
+ let built;
158
+ try {
159
+ built = await loadBuiltBpmn(resolve(editedPath));
160
+ }
161
+ catch (error) {
162
+ return reportCompileRefusal(error, { uncoded: 'propagate' });
163
+ }
164
+ let edited;
165
+ try {
166
+ edited = await serialize(built, opts);
167
+ }
168
+ catch (error) {
169
+ // What `compile` would refuse, printed as `compile` prints it.
170
+ return reportCompileRefusal(error);
171
+ }
172
+ // No stamp options means `--baseline` was given: the baseline is the caller's.
173
+ if (decompiled === undefined)
174
+ return { edited, baseline: explicitBaseline };
175
+ const derive = { serialize: opts, ...stampedDecompile(decompiled, library) };
176
+ let derived;
177
+ try {
178
+ derived = await deriveBaseline(original, derive);
179
+ }
180
+ catch (error) {
181
+ console.error(`bpmn-merge: could not derive the baseline from ${basename(editedPath)}'s original (decompile, then compile, in memory). ` +
182
+ 'Compile the unedited decompile yourself and pass it as --baseline <file>.');
183
+ return reportCompileRefusal(error);
184
+ }
185
+ // The baseline is the source the author started from only if decompiling the original
186
+ // now gives the source decompile wrote then. Compared by digest, not by the original's
187
+ // bytes, so what decompile does not read (line endings, `bpmn format`'s layout) passes.
188
+ const actual = sourceDigest(derived.decompile.source);
189
+ if (actual !== decompiled.sha256) {
190
+ const edited = basename(editedPath);
191
+ const name = basename(originalPath);
192
+ const lift = decompiled.connectors === 'lift' ? ', or the connector library it lifted with,' : '';
193
+ return refuseMerge('MERGE_ORIGINAL_CHANGED', `${name}${lift} changed since ${edited} was decompiled from ${decompiled.file === name ? 'it' : decompiled.file}: ` +
194
+ `decompiling it now gives a different source (sha256 ${decompiled.sha256} recorded, ${actual} now). ` +
195
+ `Merging would read those changes as the edit's deletions and revert them, so nothing was written. ${redoAdvice(originalPath)}`);
196
+ }
197
+ return {
198
+ edited,
199
+ baseline: derived.xml,
200
+ derived: {
201
+ style: derived.decompile.lifted ? 'nested' : 'explicit',
202
+ lifted: derived.decompile.connectors?.lifted.length ?? 0,
203
+ },
204
+ derive,
205
+ };
206
+ }
207
+ /**
208
+ * `run(argv)` is the tool contract the family-first `flow-sdk` CLI loads: the
209
+ * original first, then the edited document or source.
210
+ */
211
+ export async function run(argv) {
19
212
  if (argv.length === 0 || argv[0] === '-h' || argv[0] === '--help') {
20
- console.error('usage: bpmn-merge <original.bpmn> <edited.bpmn> [-o merged.bpmn] [--baseline <baseline.bpmn>]');
213
+ console.error(USAGE);
21
214
  return 2;
22
215
  }
23
- const flags = new Set(['-o', '--baseline']);
24
- const positionals = argv.filter((a, i) => !flags.has(a) && !flags.has(argv[i - 1]) && !a.startsWith('-'));
216
+ const positionals = argv.filter((a, i) => !BARE_FLAGS.has(a) && !VALUE_FLAGS.has(a) && !VALUE_FLAGS.has(argv[i - 1] ?? '') && !a.startsWith('-'));
25
217
  const [originalPath, editedPath] = positionals;
26
218
  if (!originalPath || !editedPath) {
27
- console.error('bpmn-merge: need <original.bpmn> and <edited.bpmn>');
219
+ console.error('bpmn-merge: need <original.bpmn> and <edited.bpmn> (or <edited.bpmn.ts>)');
28
220
  return 2;
29
221
  }
222
+ const original = readFileSync(originalPath, 'utf8');
30
223
  const baselinePath = flagValue(argv, '--baseline');
31
- const result = mergeBpmn(readFileSync(originalPath, 'utf8'), readFileSync(editedPath, 'utf8'), {
32
- ...(baselinePath ? { baseline: readFileSync(baselinePath, 'utf8') } : {}),
33
- });
34
- const out = flagValue(argv, '-o') ?? 'merged.bpmn';
224
+ const explicitBaseline = baselinePath ? readFileSync(baselinePath, 'utf8') : undefined;
225
+ // An edited source is compiled here and the baseline derived from the original, so
226
+ // the brownfield loop writes nothing but the merged file (#1871).
227
+ const isSource = editedPath.endsWith('.ts');
228
+ let edited;
229
+ let baseline = explicitBaseline;
230
+ let derived;
231
+ let derive;
232
+ if (isSource) {
233
+ // Before anything compiles: a missing stamp, or a flag that disagrees with it. The
234
+ // digest check, which refuses an original that changed since the decompile, runs
235
+ // once the baseline's source is derived (compileSides).
236
+ const decompiled = decompileOptions(argv, editedPath, originalPath, explicitBaseline !== undefined);
237
+ if (typeof decompiled === 'number')
238
+ return decompiled;
239
+ const sides = await compileSides(argv, editedPath, originalPath, original, explicitBaseline, decompiled);
240
+ if (typeof sides === 'number')
241
+ return sides;
242
+ ({ edited, baseline, derived, derive } = sides);
243
+ if (explicitBaseline !== undefined) {
244
+ // No stamp check under --baseline, but a readable stamp still says how to digest
245
+ // the merged file, so a merge written over the original restamps as it does without.
246
+ const stamp = readStamp(readFileSync(editedPath, 'utf8'));
247
+ if (stamp !== undefined && !('error' in stamp))
248
+ derive = stampedDecompile(stamp, openCliLibrary(argv));
249
+ }
250
+ }
251
+ else {
252
+ edited = readFileSync(editedPath, 'utf8');
253
+ }
254
+ const result = mergeBpmn(original, edited, baseline !== undefined ? { baseline } : {});
255
+ // The source form merges in place by default: a `merged.bpmn` beside the original is
256
+ // one more `.bpmn` for the next reader to open by mistake — the very leftover the
257
+ // source form exists to avoid. It is safe because the stamp check above refused an
258
+ // original that changed since the decompile.
259
+ const out = flagValue(argv, '-o') ?? (isSource ? originalPath : 'merged.bpmn');
35
260
  writeFileSync(out, result.xml);
261
+ // Written over the original: point the source's stamp at the merged file, so the next
262
+ // edit-and-merge round on the same source passes the check. The merged original is
263
+ // what the source, as it now stands, decompiles from; its digest is that of the merged
264
+ // file decompiled with the stamped options, which is what the next check derives.
265
+ // Written elsewhere, the original is unchanged and so is the stamp; a source with no
266
+ // readable stamp (possible only under --baseline) keeps none.
267
+ let restamped = false;
268
+ if (derive && resolve(out) === resolve(originalPath)) {
269
+ const source = readFileSync(editedPath, 'utf8');
270
+ let next;
271
+ try {
272
+ next = restampSource(source, basename(originalPath), await decompiledDigest(result.xml, derive));
273
+ }
274
+ catch (error) {
275
+ // The merge stands; the old stamp makes the next round refuse, never revert.
276
+ console.error(`bpmn-merge: could not decompile the merged ${basename(originalPath)} to restamp ${basename(editedPath)} ` +
277
+ `(${error instanceof Error ? error.message : String(error)}); decompile it again before the next edit`);
278
+ }
279
+ if (next !== undefined && next !== source) {
280
+ writeFileSync(editedPath, next);
281
+ restamped = true;
282
+ }
283
+ }
36
284
  const { layout } = result;
37
285
  reportResult({
38
286
  path: resolve(out),
39
287
  preserved: result.preserved.length,
40
288
  authored: result.authored.length,
41
289
  removed: result.removed.length,
290
+ ...(isSource ? { baseline: derived ? 'derived' : 'file', restamped } : {}),
42
291
  placed: layout.placed.length,
43
292
  routed: layout.routed.length + layout.rerouted.length,
44
293
  ...(layout.resized.length || layout.moved.length ? { resized: layout.resized, moved: layout.moved } : {}),
@@ -47,6 +296,13 @@ export function run(argv) {
47
296
  // should dwarf the authored one, and a reader who sees otherwise has learned something.
48
297
  console.log(`bpmn-merge: wrote ${basename(out)} (${result.preserved.length} preserved, ` +
49
298
  `${result.authored.length} authored, ${result.removed.length} removed)`);
299
+ if (derived) {
300
+ console.log(`bpmn-merge: compiled ${basename(editedPath)} and derived the baseline from ${basename(originalPath)} in memory ` +
301
+ `(${derived.style} decompile${derived.lifted ? `, ${derived.lifted} connector task(s) lifted` : ''}); no intermediate file written`);
302
+ }
303
+ if (restamped) {
304
+ console.log(`bpmn-merge: restamped ${basename(editedPath)} for the merged ${basename(originalPath)}, so it merges again after the next edit`);
305
+ }
50
306
  // The diagram: what the edit added is drawn, and an existing shape moves only when a
51
307
  // full lane, pool or sub-process had to grow — say so, by id, when it did.
52
308
  if (layout.placed.length || layout.routed.length || layout.rerouted.length) {
@@ -0,0 +1,86 @@
1
+ /**
2
+ * merge-source — the two compiles `bpmn merge` runs itself when it is handed the
3
+ * edited SOURCE (`bpmn merge X.bpmn.ts --original X.bpmn`), so the brownfield loop
4
+ * writes no intermediate `.bpmn` (UiPath/builder-sdk#1871).
5
+ *
6
+ * The file-based pipeline needs two compiled documents beside the original:
7
+ *
8
+ * decompile X.bpmn -> X.bpmn.ts
9
+ * compile X.bpmn.ts -o X.baseline.bpmn # BEFORE the edit
10
+ * (edit X.bpmn.ts)
11
+ * compile X.bpmn.ts -o X.edited.bpmn
12
+ * merge X.edited.bpmn --original X.bpmn --baseline X.baseline.bpmn -o X.bpmn
13
+ *
14
+ * Agents left `X.baseline.bpmn` and `X.edited.bpmn` in the project, and the next
15
+ * reader of `*.bpmn` opened the wrong one. Both are derivable: the edited document is
16
+ * the compile of the source, and the baseline is the compile of a FRESH decompile of
17
+ * the original — which is what `X.bpmn.ts` was before the edit, because decompile is a
18
+ * function of the original and the options it was given. That holds only while the
19
+ * original is the file the source was decompiled from: if it changed since, its changes
20
+ * are in the derived baseline and not in the source, and the merge would revert them.
21
+ * So `bpmn decompile` stamps the source with the digest of the source it wrote and its
22
+ * options (decompile-stamp.ts); merge-cli.ts refuses a source whose stamp is missing,
23
+ * passes the stamped options here, and refuses when the source this derives digests
24
+ * differently — the derived baseline is then not what the author started from. This makes both in
25
+ * memory: `decompilePipeline` (the same code `bpmn decompile` runs, lifts and their
26
+ * verification included) for the baseline's source, and `serialize`, with the
27
+ * library, bindings and resources the edited compile uses, for both.
28
+ *
29
+ * The baseline only has to agree with the edited compile on what the author did NOT
30
+ * touch, and that holds when it was decompiled with the options the author's source
31
+ * was — the ones the stamp records: the connector lift (`connectors`) changes how a
32
+ * connector task compiles, and a dropped unused binding (`keepUnusedBindings`) changes
33
+ * the process extension block. The nested style does not change the compiled graph —
34
+ * `bpmn decompile` writes the nested source only when it builds the same graph as the
35
+ * flat one, flow ids included — but it is reproduced too, so the baseline is built
36
+ * from the same text the author started from.
37
+ *
38
+ * Nothing here prints or reads argv; merge-cli.ts does.
39
+ */
40
+ import type { Library } from '../core/library.js';
41
+ import { type BpmnSerializeOpts } from './serialize.js';
42
+ import { type DecompilePipelineResult } from './decompile-pipeline.js';
43
+ /** What both in-memory compiles need, and how to decompile the original. */
44
+ export interface SourceMergeOptions {
45
+ /** The library, bindings and resources `compile` would use; the edited and baseline compiles share them. */
46
+ serialize: BpmnSerializeOpts;
47
+ /** Absolute path of this package's `bpmn-sdk.js`, which the baseline source builds against. */
48
+ sdkEntry: string;
49
+ /** The decompile style the author's source was written in (default `nested`). */
50
+ style?: 'explicit' | 'nested';
51
+ /**
52
+ * The library the decompile lifts connector tasks with — `undefined` for
53
+ * `--connectors verbatim`, or when no library opens, which is what `bpmn decompile`
54
+ * did with the same options.
55
+ */
56
+ liftLibrary?: Library;
57
+ /** As `bpmn decompile --keep-flow-ids`. */
58
+ keepFlowIds?: boolean;
59
+ /** As `bpmn decompile --keep-unused-bindings`. */
60
+ keepUnusedBindings?: boolean;
61
+ }
62
+ /** The baseline merge derived from the original. */
63
+ export interface DerivedBaseline {
64
+ /** `compile(decompile(original))`, the document a `--baseline` file would hold. */
65
+ xml: string;
66
+ /** What the decompile did: the lifts, the bindings it dropped. */
67
+ decompile: DecompilePipelineResult;
68
+ }
69
+ /**
70
+ * `compile(decompile(original))`, made in memory: the baseline the file-based pipeline
71
+ * writes to `X.baseline.bpmn` before the edit.
72
+ *
73
+ * @param original - The original `.bpmn` text.
74
+ * @param opts - The compile context and the decompile options.
75
+ * @returns The baseline document and what the decompile did.
76
+ */
77
+ export declare function deriveBaseline(original: string, opts: SourceMergeOptions): Promise<DerivedBaseline>;
78
+ /**
79
+ * The stamp digest of `xml` decompiled with `opts`'s options: what `bpmn decompile`
80
+ * would record for it. Merge restamps the source with this after writing over the
81
+ * original, so the next round's check compares like with like.
82
+ *
83
+ * @param xml - The merged `.bpmn` text.
84
+ * @param opts - The decompile options the baseline was derived with.
85
+ */
86
+ export declare function decompiledDigest(xml: string, opts: Omit<SourceMergeOptions, 'serialize'>): Promise<string>;
@@ -0,0 +1,39 @@
1
+ import { serialize } from './serialize.js';
2
+ import { buildSource } from './lift-verify.js';
3
+ import { decompilePipeline } from './decompile-pipeline.js';
4
+ import { sourceDigest } from './decompile-stamp.js';
5
+ /**
6
+ * `compile(decompile(original))`, made in memory: the baseline the file-based pipeline
7
+ * writes to `X.baseline.bpmn` before the edit.
8
+ *
9
+ * @param original - The original `.bpmn` text.
10
+ * @param opts - The compile context and the decompile options.
11
+ * @returns The baseline document and what the decompile did.
12
+ */
13
+ export async function deriveBaseline(original, opts) {
14
+ const decompiled = await decompileAs(original, opts);
15
+ const built = await buildSource(decompiled.source, opts.sdkEntry);
16
+ return { xml: await serialize(built, opts.serialize), decompile: decompiled };
17
+ }
18
+ /**
19
+ * The stamp digest of `xml` decompiled with `opts`'s options: what `bpmn decompile`
20
+ * would record for it. Merge restamps the source with this after writing over the
21
+ * original, so the next round's check compares like with like.
22
+ *
23
+ * @param xml - The merged `.bpmn` text.
24
+ * @param opts - The decompile options the baseline was derived with.
25
+ */
26
+ export async function decompiledDigest(xml, opts) {
27
+ return sourceDigest((await decompileAs(xml, opts)).source);
28
+ }
29
+ /** `decompilePipeline` with the options `bpmn decompile` was given. */
30
+ function decompileAs(xml, opts) {
31
+ return decompilePipeline(xml, {
32
+ importSpecifier: opts.sdkEntry,
33
+ style: opts.style ?? 'nested',
34
+ keepFlowIds: opts.keepFlowIds === true,
35
+ keepUnusedBindings: opts.keepUnusedBindings === true,
36
+ sdkEntry: opts.sdkEntry,
37
+ ...(opts.liftLibrary ? { library: opts.liftLibrary } : {}),
38
+ });
39
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * How a saved custom (`{ assign }`) task output row differs from the row
3
+ * compile writes for it, so the round trip can put the saved row back.
4
+ *
5
+ * Compile writes one shape (`emitCustomOutput` in `serialize.ts`, the shape
6
+ * Studio Web writes for a new row):
7
+ *
8
+ * { name, type, custom: true, var, value: <source>, source, target: '', body: '', elementId: 'root' }
9
+ *
10
+ * Saved plans hold others. Examples from Studio Web plans:
11
+ *
12
+ * - `{ ..., id: 'currentTaskName', elementId: '<stage>-<task>', value: 'currentTaskName' }`:
13
+ * a row with its own id, which names its task as the element.
14
+ * - `{ ..., source: '=js:vars.a.b', value: '=vars.a' }`: a `value` that is a
15
+ * stale Designer copy, not the assigned `source`.
16
+ * - `{ ..., type: 'json', body: { ... } }`: a json row, whose expressions the
17
+ * platform reads from `body`, not `source` (`getCustomOutputExpressions` in
18
+ * `@uipath/case-schema`).
19
+ * - a row saved with no `source`, `target` or `body`.
20
+ *
21
+ * `customRowShape` records the difference (`set`: the saved value of each
22
+ * field that differs or that compile does not write; `omit`: each field
23
+ * compile writes that the row lacks), with the `source` and `type` the row
24
+ * had and how many custom rows of the task assign its variable. Compile puts
25
+ * it back only while the compiled row still has that `source` and `type` and
26
+ * the task still has that many rows on the variable, so an edited (or
27
+ * retyped) `{ assign }` keeps the row compile writes for it, and a shape is
28
+ * never put on another row of the same variable.
29
+ * That includes the row's `id`: the engine does not read a custom row's id,
30
+ * and a Designer id on compile's own row (`elementId: 'root'`, `value ===
31
+ * source`) is neither the Designer's shape nor compile's, which
32
+ * `uip maestro case validate --strict` rejects (`STRICT_CUSTOM_OUTPUT_SHAPE`).
33
+ */
34
+ /** Fields a carried custom-row shape never sets: the label (`name`, carried apart) and what the `{ assign }` source types. */
35
+ export declare const CUSTOM_ROW_TYPED_FIELDS: ReadonlySet<string>;
36
+ /** Fields a carried custom-row shape may omit: the Designer copies compile writes. */
37
+ export declare const CUSTOM_ROW_OMITTABLE_FIELDS: ReadonlySet<string>;
38
+ export interface CustomRowShape {
39
+ /** The `source` the saved row assigned (`''` when it had none): the shape applies only while the compiled row assigns the same. */
40
+ source: string;
41
+ /** The `type` the saved row had (`'string'` when it had none): a retyped row gets compile's shape. */
42
+ type: string;
43
+ /** The variable the row assigns, which finds the compiled row. */
44
+ var: string;
45
+ /** How many custom rows of the task assign `var`, when more than one: the shape applies only while the compiled task has as many. */
46
+ varRows?: number;
47
+ /** Saved values of fields compile writes otherwise, or does not write. */
48
+ set?: Record<string, unknown>;
49
+ /** Fields compile writes that the saved row lacks. */
50
+ omit?: string[];
51
+ }
52
+ /**
53
+ * The shape of saved custom row `row`, or undefined when compile writes it
54
+ * as saved. `ownFields` are fields another channel already carries for this
55
+ * row (an action custom row's `originalVar`), left out here.
56
+ */
57
+ export declare function customRowShape(row: Record<string, unknown>, ownFields?: ReadonlySet<string>, varRows?: number): CustomRowShape | undefined;
58
+ /** Problems with a carried shape (`preserveCaseJson` payload validation), as messages. */
59
+ export declare function customRowShapeErrors(owner: string, shape: unknown): string[];
60
+ /**
61
+ * Put carried `shape` back on compiled custom row `row`, only while `row`
62
+ * has the carried `source` and `type` and its task has `shape.varRows` custom
63
+ * rows on the variable (`varRows`, the compiled count): an edited or retyped
64
+ * row keeps compile's shape, id included, and a task that gained or lost a
65
+ * row on the variable puts no shape on the wrong row. `idFree(id)` says
66
+ * whether no other output row holds `id`.
67
+ */
68
+ export declare function applyCustomRowShape(row: Record<string, unknown>, shape: CustomRowShape, idFree: (id: string) => boolean, varRows?: number): void;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * How a saved custom (`{ assign }`) task output row differs from the row
3
+ * compile writes for it, so the round trip can put the saved row back.
4
+ *
5
+ * Compile writes one shape (`emitCustomOutput` in `serialize.ts`, the shape
6
+ * Studio Web writes for a new row):
7
+ *
8
+ * { name, type, custom: true, var, value: <source>, source, target: '', body: '', elementId: 'root' }
9
+ *
10
+ * Saved plans hold others. Examples from Studio Web plans:
11
+ *
12
+ * - `{ ..., id: 'currentTaskName', elementId: '<stage>-<task>', value: 'currentTaskName' }`:
13
+ * a row with its own id, which names its task as the element.
14
+ * - `{ ..., source: '=js:vars.a.b', value: '=vars.a' }`: a `value` that is a
15
+ * stale Designer copy, not the assigned `source`.
16
+ * - `{ ..., type: 'json', body: { ... } }`: a json row, whose expressions the
17
+ * platform reads from `body`, not `source` (`getCustomOutputExpressions` in
18
+ * `@uipath/case-schema`).
19
+ * - a row saved with no `source`, `target` or `body`.
20
+ *
21
+ * `customRowShape` records the difference (`set`: the saved value of each
22
+ * field that differs or that compile does not write; `omit`: each field
23
+ * compile writes that the row lacks), with the `source` and `type` the row
24
+ * had and how many custom rows of the task assign its variable. Compile puts
25
+ * it back only while the compiled row still has that `source` and `type` and
26
+ * the task still has that many rows on the variable, so an edited (or
27
+ * retyped) `{ assign }` keeps the row compile writes for it, and a shape is
28
+ * never put on another row of the same variable.
29
+ * That includes the row's `id`: the engine does not read a custom row's id,
30
+ * and a Designer id on compile's own row (`elementId: 'root'`, `value ===
31
+ * source`) is neither the Designer's shape nor compile's, which
32
+ * `uip maestro case validate --strict` rejects (`STRICT_CUSTOM_OUTPUT_SHAPE`).
33
+ */
34
+ /** The fields compile writes on a custom row, with the value it writes, given the row's `source`, `type` and `var`. */
35
+ function writtenCustomRow(source, type, variable) {
36
+ return { type, custom: true, var: variable, value: source, source, target: '', body: '', elementId: 'root' };
37
+ }
38
+ /** Fields a carried custom-row shape never sets: the label (`name`, carried apart) and what the `{ assign }` source types. */
39
+ export const CUSTOM_ROW_TYPED_FIELDS = new Set(['name', 'type', 'custom', 'var', 'source']);
40
+ /** Fields a carried custom-row shape may omit: the Designer copies compile writes. */
41
+ export const CUSTOM_ROW_OMITTABLE_FIELDS = new Set(['value', 'source', 'target', 'body', 'elementId']);
42
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
43
+ /**
44
+ * The shape of saved custom row `row`, or undefined when compile writes it
45
+ * as saved. `ownFields` are fields another channel already carries for this
46
+ * row (an action custom row's `originalVar`), left out here.
47
+ */
48
+ export function customRowShape(row, ownFields = new Set(), varRows = 1) {
49
+ if (row.custom !== true || typeof row.var !== 'string')
50
+ return undefined;
51
+ if (row.source !== undefined && typeof row.source !== 'string')
52
+ return undefined;
53
+ const source = row.source ?? '';
54
+ const type = typeof row.type === 'string' ? row.type : 'string';
55
+ const written = writtenCustomRow(source, type, row.var);
56
+ const set = {};
57
+ for (const [field, value] of Object.entries(row)) {
58
+ if (CUSTOM_ROW_TYPED_FIELDS.has(field) || ownFields.has(field))
59
+ continue;
60
+ if (!Object.prototype.hasOwnProperty.call(written, field) || !same(written[field], value))
61
+ set[field] = structuredClone(value);
62
+ }
63
+ // A field another channel carries (`ownFields`) is not this shape's to set or to omit.
64
+ const omit = Object.keys(written).filter((field) => CUSTOM_ROW_OMITTABLE_FIELDS.has(field) && !ownFields.has(field) && !Object.prototype.hasOwnProperty.call(row, field));
65
+ if (!Object.keys(set).length && !omit.length)
66
+ return undefined;
67
+ return { source, type, var: row.var, ...(varRows !== 1 ? { varRows } : {}), ...(Object.keys(set).length ? { set } : {}), ...(omit.length ? { omit } : {}) };
68
+ }
69
+ /** Problems with a carried shape (`preserveCaseJson` payload validation), as messages. */
70
+ export function customRowShapeErrors(owner, shape) {
71
+ if (!shape || typeof shape !== 'object' || Array.isArray(shape))
72
+ return [`${owner} custom-row shape must be an object`];
73
+ const s = shape;
74
+ const errors = [];
75
+ if (typeof s.source !== 'string')
76
+ errors.push(`${owner} custom-row shape needs its "source" string`);
77
+ if (typeof s.type !== 'string' || !s.type)
78
+ errors.push(`${owner} custom-row shape needs its "type" string`);
79
+ if (typeof s.var !== 'string' || !s.var)
80
+ errors.push(`${owner} custom-row shape needs its "var" string`);
81
+ if (s.varRows !== undefined && !(Number.isInteger(s.varRows) && s.varRows > 1))
82
+ errors.push(`${owner} custom-row shape "varRows" must be an integer above 1`);
83
+ if (s.set !== undefined) {
84
+ if (!s.set || typeof s.set !== 'object' || Array.isArray(s.set))
85
+ errors.push(`${owner} custom-row shape "set" must be an object`);
86
+ else {
87
+ for (const field of Object.keys(s.set))
88
+ if (CUSTOM_ROW_TYPED_FIELDS.has(field))
89
+ errors.push(`${owner} custom row field "${field}" is owned by the typed Case serializer`);
90
+ if (s.set.id !== undefined && typeof s.set.id !== 'string')
91
+ errors.push(`${owner} custom-row shape "set.id" must be a string`);
92
+ }
93
+ }
94
+ if (s.omit !== undefined) {
95
+ if (!Array.isArray(s.omit) || s.omit.some((field) => typeof field !== 'string'))
96
+ errors.push(`${owner} custom-row shape "omit" must be an array of field names`);
97
+ else
98
+ for (const field of s.omit)
99
+ if (!CUSTOM_ROW_OMITTABLE_FIELDS.has(field))
100
+ errors.push(`${owner} custom row omits "${field}", which is not an omittable field`);
101
+ }
102
+ return errors;
103
+ }
104
+ /**
105
+ * Put carried `shape` back on compiled custom row `row`, only while `row`
106
+ * has the carried `source` and `type` and its task has `shape.varRows` custom
107
+ * rows on the variable (`varRows`, the compiled count): an edited or retyped
108
+ * row keeps compile's shape, id included, and a task that gained or lost a
109
+ * row on the variable puts no shape on the wrong row. `idFree(id)` says
110
+ * whether no other output row holds `id`.
111
+ */
112
+ export function applyCustomRowShape(row, shape, idFree, varRows = 1) {
113
+ if (row.source !== shape.source || row.type !== shape.type || varRows !== (shape.varRows ?? 1))
114
+ return;
115
+ const { id, ...rest } = shape.set ?? {};
116
+ if (typeof id === 'string' && row.id === undefined && idFree(id))
117
+ row.id = id;
118
+ for (const field of shape.omit ?? [])
119
+ delete row[field];
120
+ for (const [field, value] of Object.entries(rest))
121
+ row[field] = structuredClone(value);
122
+ }