@uipath/maestro-builder-sdk 6.80.0 → 6.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,75 @@
1
+ /**
2
+ * case/script — the Case `script` task: a JavaScript body the engine runs,
3
+ * written as the Case Designer saves it.
4
+ *
5
+ * Read from an alpha Designer save (2026-10-22, UiPath/cli
6
+ * `packages/case-tool/tests/fixtures/script/designer-saved.json`) and the
7
+ * CLI's writer, `sdd convert` (`services/sdd-convert/script.ts` at
8
+ * UiPath/cli b37f32997c), which was read from PO.Frontend's
9
+ * `CaseManagementScriptTaskUtils.ts`. With ids masked the two agree on every
10
+ * field but the ones the Designer infers (`scriptResponse._jsonSchema`).
11
+ *
12
+ * The task's `data`:
13
+ * - `script`: the body behind a leading `=`, as the Designer stores it (its
14
+ * BPMN writer strips one `=` again, so the body runs as written);
15
+ * - `inputs`: exactly `vars` = `=vars` and `metadata` = `=metadata`, how the
16
+ * body reads case state. Without them the body gets an empty `args`;
17
+ * - `outputs`: what the body returns as `scriptResponse` (`=result.response`),
18
+ * and the activity's `Error`. Ids are claimed like every task output's.
19
+ *
20
+ * The body may be authored as a TypeScript function (`core/script-function.ts`,
21
+ * docs/SCRIPT_FUNCTION_DESIGN.md): its parameters are renamed to the runtime's
22
+ * `vars` and `metadata`, and it may read only what the engine gives a script
23
+ * (`core/script-engine.ts`), the same engine Flow's script node runs on.
24
+ */
25
+ import type { ScriptRuntime } from '../core/script-function.js';
26
+ import type { CaseScriptSpec, TaskOutputBinding } from './case-sdk.js';
27
+ /**
28
+ * The Case script runtime, as `.script(fn)` lowers for it. A Case script task's
29
+ * converter binds its two inputs as the globals `vars` and `metadata` (no `$`,
30
+ * unlike Flow's `$vars`), and the body reads case state through them.
31
+ */
32
+ export declare const CASE_SCRIPT_RUNTIME: ScriptRuntime;
33
+ /** The two inputs every script task carries, as the Designer and the CLI write them. */
34
+ export declare const SCRIPT_INPUTS: readonly Record<string, unknown>[];
35
+ /** The task's two outputs: `[name, id base, source]`, in the Designer's order. */
36
+ export declare const SCRIPT_OUTPUTS: readonly [{
37
+ readonly name: "scriptResponse";
38
+ readonly base: "scriptResponse";
39
+ readonly source: "=result.response";
40
+ }, {
41
+ readonly name: "Error";
42
+ readonly base: "error";
43
+ readonly source: "=Error";
44
+ }];
45
+ /** A refusal or finding `check`, `serialize` and `decompile` share. */
46
+ export interface ScriptFinding {
47
+ code: string;
48
+ message: string;
49
+ suggestion?: string;
50
+ }
51
+ /** The body as the Designer stores it: behind one leading `=`. */
52
+ export declare function storedScript(body: string): string;
53
+ /** The body a stored `script` holds: the Designer's leading `=` removed, once, as its BPMN writer removes it. */
54
+ export declare function scriptBody(stored: string): string;
55
+ /**
56
+ * Which output an `.outputs()` row writes to a case variable: its `source` is
57
+ * one of the two, once each; or the refusal (`lowering`: there is no row to
58
+ * write any other output to). A custom `{ assign }` row reads no result and is
59
+ * written beside them.
60
+ */
61
+ export declare function scriptOutputMappings(owner: string, outputs: readonly TaskOutputBinding[] | undefined): Map<string, string> | ScriptFinding;
62
+ /**
63
+ * The task's two output rows. `claim` gives each a document-unique id; a
64
+ * mapped output writes the case variable the author named instead, keeping
65
+ * its own id as `originalVar`, as the Designer saves `scriptResponse -> total`.
66
+ * A schema is written where the Designer keeps it: `_jsonSchema` on
67
+ * `scriptResponse`, and `_jsonSchema` and `body` on `Error`.
68
+ */
69
+ export declare function scriptOutputs(elementId: string, claim: (base: string) => string, mappings: ReadonlyMap<string, string>, spec: Pick<CaseScriptSpec, 'responseSchema' | 'errorSchema'>): Record<string, unknown>[];
70
+ /**
71
+ * What `check` says about a body compile writes as authored (`lint`): a blank
72
+ * one, which runs and returns nothing, and a string body that does not parse.
73
+ * A function body was parsed when it was lowered.
74
+ */
75
+ export declare function scriptLint(owner: string, spec: CaseScriptSpec): ScriptFinding[];
@@ -0,0 +1,124 @@
1
+ import { scriptBodySyntaxError, scriptBodyTypeScriptSyntax } from '../core/script-function.js';
2
+ import { SCRIPT_ENGINE_CONST_GLOBALS, SCRIPT_ENGINE_GLOBAL_MEMBERS, SCRIPT_ENGINE_GLOBALS } from '../core/script-engine.js';
3
+ /**
4
+ * The Case script runtime, as `.script(fn)` lowers for it. A Case script task's
5
+ * converter binds its two inputs as the globals `vars` and `metadata` (no `$`,
6
+ * unlike Flow's `$vars`), and the body reads case state through them.
7
+ */
8
+ export const CASE_SCRIPT_RUNTIME = {
9
+ scopes: [
10
+ {
11
+ global: 'vars', param: 'vars', holds: 'the case variables', reads: 'variable', example: 'amount',
12
+ // `validate` reports a `vars.<name>` that names nothing (CASE_MGMT_REFERENCE_UNBOUND,
13
+ // an error on the default profile, measured at uip 1.206.0), and it reads a script
14
+ // body like any other plan text. `check` runs the same rule once the validate rules
15
+ // move into `case/plan-check/`; this task adds no second copy of it.
16
+ checkedBy: "`uip maestro case validate`'s variable reference check (CASE_MGMT_REFERENCE_UNBOUND)",
17
+ },
18
+ {
19
+ global: 'metadata', param: 'metadata', holds: 'the instance metadata', reads: 'key', example: 'InstanceId',
20
+ checkedBy: 'no check (a case may set its own keys)',
21
+ },
22
+ ],
23
+ name: 'the Case script runtime',
24
+ constGlobals: SCRIPT_ENGINE_CONST_GLOBALS,
25
+ globalMembers: SCRIPT_ENGINE_GLOBAL_MEMBERS,
26
+ globals: SCRIPT_ENGINE_GLOBALS,
27
+ };
28
+ /** The two inputs every script task carries, as the Designer and the CLI write them. */
29
+ export const SCRIPT_INPUTS = [
30
+ { name: 'vars', type: 'object', value: '=vars' },
31
+ { name: 'metadata', type: 'object', value: '=metadata' },
32
+ ];
33
+ /** The task's two outputs: `[name, id base, source]`, in the Designer's order. */
34
+ export const SCRIPT_OUTPUTS = [
35
+ { name: 'scriptResponse', base: 'scriptResponse', source: '=result.response' },
36
+ { name: 'Error', base: 'error', source: '=Error' },
37
+ ];
38
+ /** The body as the Designer stores it: behind one leading `=`. */
39
+ export function storedScript(body) {
40
+ return body.startsWith('=') ? body : `=${body}`;
41
+ }
42
+ /** The body a stored `script` holds: the Designer's leading `=` removed, once, as its BPMN writer removes it. */
43
+ export function scriptBody(stored) {
44
+ return stored.startsWith('=') ? stored.slice(1) : stored;
45
+ }
46
+ /**
47
+ * Which output an `.outputs()` row writes to a case variable: its `source` is
48
+ * one of the two, once each; or the refusal (`lowering`: there is no row to
49
+ * write any other output to). A custom `{ assign }` row reads no result and is
50
+ * written beside them.
51
+ */
52
+ export function scriptOutputMappings(owner, outputs) {
53
+ const bySource = new Map();
54
+ for (const o of outputs ?? []) {
55
+ if (o.custom)
56
+ continue;
57
+ if (!SCRIPT_OUTPUTS.some((row) => row.source === o.source))
58
+ return {
59
+ code: 'SCRIPT_OUTPUT',
60
+ message: `${owner} output "${o.var}" reads ${JSON.stringify(o.source)}; a script task has two outputs: `
61
+ + `${SCRIPT_OUTPUTS.map((row) => row.source).join(' and ')}.`,
62
+ suggestion: "Map the body's return to a case variable, .outputs({ scriptResult: '=result.response' }), and read its fields as scriptResult.<field>.",
63
+ };
64
+ if (bySource.has(o.source))
65
+ return { code: 'SCRIPT_OUTPUT', message: `${owner} writes ${o.source} to two variables, "${bySource.get(o.source)}" and "${o.var}".` };
66
+ bySource.set(o.source, o.var);
67
+ }
68
+ return bySource;
69
+ }
70
+ /**
71
+ * The task's two output rows. `claim` gives each a document-unique id; a
72
+ * mapped output writes the case variable the author named instead, keeping
73
+ * its own id as `originalVar`, as the Designer saves `scriptResponse -> total`.
74
+ * A schema is written where the Designer keeps it: `_jsonSchema` on
75
+ * `scriptResponse`, and `_jsonSchema` and `body` on `Error`.
76
+ */
77
+ export function scriptOutputs(elementId, claim, mappings, spec) {
78
+ return SCRIPT_OUTPUTS.map((row) => {
79
+ const id = claim(row.base);
80
+ const variable = mappings.get(row.source);
81
+ const out = { name: row.name };
82
+ if (row.name === 'Error' && spec.errorSchema !== undefined)
83
+ out.displayName = 'Error';
84
+ out.type = 'jsonSchema';
85
+ out.source = row.source;
86
+ if (row.name === 'scriptResponse' && spec.responseSchema !== undefined)
87
+ out._jsonSchema = structuredClone(spec.responseSchema);
88
+ if (row.name === 'Error' && spec.errorSchema !== undefined)
89
+ out._jsonSchema = structuredClone(spec.errorSchema);
90
+ Object.assign(out, { id, var: variable ?? id, value: variable ?? id, elementId });
91
+ if (variable !== undefined) {
92
+ out.target = `=${id}`;
93
+ out.originalVar = id;
94
+ }
95
+ if (row.name === 'Error' && spec.errorSchema !== undefined)
96
+ out.body = structuredClone(spec.errorSchema);
97
+ return out;
98
+ });
99
+ }
100
+ /**
101
+ * What `check` says about a body compile writes as authored (`lint`): a blank
102
+ * one, which runs and returns nothing, and a string body that does not parse.
103
+ * A function body was parsed when it was lowered.
104
+ */
105
+ export function scriptLint(owner, spec) {
106
+ const body = scriptBody(spec.body);
107
+ if (body.trim() === '')
108
+ return [{
109
+ code: 'SCRIPT_TASK_NO_BODY',
110
+ message: `${owner} has no script body, so it runs and returns nothing.`,
111
+ suggestion: "Pass the body: .script((vars) => ({ total: vars.amount * 2 })), or a string such as 'return { total: vars.amount * 2 };'.",
112
+ }];
113
+ if (spec.fromFunction)
114
+ return [];
115
+ // The parser is TypeScript's, which also accepts TypeScript-only forms the
116
+ // engine's JavaScript rejects (`x as T`, `x!`): name those as the error.
117
+ const typed = scriptBodyTypeScriptSyntax(body);
118
+ const syntax = scriptBodySyntaxError(body) ?? (typed === undefined ? undefined : `it contains ${typed}, which is TypeScript, not JavaScript`);
119
+ return syntax === undefined ? [] : [{
120
+ code: 'SCRIPT_BODY_SYNTAX',
121
+ message: `${owner}'s script does not parse as JavaScript: ${syntax}. The body is written into the case as authored, so the task fails when it runs.`,
122
+ suggestion: 'Fix the body, or write it as a TypeScript function, .script((vars) => …), which the compiler checks.',
123
+ }];
124
+ }
@@ -37,7 +37,10 @@ import { ruleShapeProblems } from './rule-options.js';
37
37
  import { CompileRefusal } from '../core/compile-refusal.js';
38
38
  import { implicitInArgBuiltTrigger, unboundInArgMessage } from './in-arg-binding.js';
39
39
  import { jsonClone } from '../core/json-clone.js';
40
+ import { savedDocumentExtractionData } from './document-extraction-saved.js';
40
41
  import { taskShapeProblems } from './task-shape.js';
42
+ import { SCRIPT_INPUTS, scriptOutputMappings, scriptOutputs, storedScript } from './script.js';
43
+ import { DOCUMENT_EXTRACTION_NAME, DOCUMENT_EXTRACTION_RESOURCE, DOCUMENT_EXTRACTION_SERVICE_TYPE, DOCUMENT_EXTRACTION_VERSION, documentExtractionContext, documentExtractionInputs, documentExtractionOutputMappings, documentExtractionOutputs, documentExtractionRefusal, } from './document-extraction.js';
41
44
  import { HTTP_REQUEST_CONNECTION_NAME, HTTP_REQUEST_IMPLICIT_BINDING_ID, HTTP_REQUEST_IMPLICIT_CONNECTION, HTTP_REQUEST_SERVICE_TYPE, httpRequestBody, httpRequestContext, httpRequestInputs, httpRequestOutputMappings, httpRequestOutputs, httpRequestRefusal, writeHttpRequestMetadata, } from './http-request.js';
42
45
  import { connectorPlaceholderData, isConnectorPlaceholder } from './connector-placeholder.js';
43
46
  import { lowerTaskOutputRefs, planTaskOutputs, resolveInPlan, unresolvedTaskOutputRef } from './task-output-ref.js';
@@ -214,7 +217,9 @@ function serializeCase(built, opts) {
214
217
  offlineBindingIds: new Map(),
215
218
  varCompanions: new Map(),
216
219
  ownNameRows: new Map(),
217
- outputIds: new Set(),
220
+ // A carried task's saved output rows keep their ids: no other row takes one.
221
+ outputIds: new Set(savedOutputIds(caseJsonPreservation(built)?.documentExtractionData)),
222
+ savedDocumentExtractions: caseJsonPreservation(built)?.documentExtractionData ?? [],
218
223
  ownOutputVars: ownOutputVars(built),
219
224
  caseVarNames: new Set([...built.vars.map((v) => v.name), ...mappedFixedOutputVars(built)]),
220
225
  slaId: new Map(),
@@ -853,6 +858,7 @@ export function applyPreservation(result, preservation, options = {}) {
853
858
  // (preserve.ts `unreadBindings` / `readBindings` / `bindings`): a row the
854
859
  // original read nowhere stays, as Studio Web keeps it; any other stays while
855
860
  // something in the result still reads it, and goes with its last reader.
861
+ applySavedIxpBindings(result, preservation.readBindings);
856
862
  const carried = [...(preservation.unreadBindings ?? []), ...(preservation.readBindings ?? []), ...(preservation.bindings ?? [])];
857
863
  if (carried.length) {
858
864
  const rows = (result.bindings ??= []);
@@ -867,6 +873,51 @@ export function applyPreservation(result, preservation, options = {}) {
867
873
  }
868
874
  return result;
869
875
  }
876
+ /**
877
+ * Point each document-extraction task back at the `ixpDeployment` row it was
878
+ * saved with. Compile mints one row per deployment and key (`bIxp<n>`); the
879
+ * source's row for that deployment and key travels in `readBindings`, and it
880
+ * is written back under its own id, `context.name` with it, so a decompile ->
881
+ * compile (and a merge) keeps the Designer's binding. A fresh row no task
882
+ * reads any more is dropped. The carried-row pass below then appends the
883
+ * saved row, which the task now reads.
884
+ */
885
+ function applySavedIxpBindings(result, carried) {
886
+ const key = (row) => JSON.stringify([row.default, row.resourceKey ?? null]);
887
+ const saved = new Map();
888
+ for (const row of carried ?? [])
889
+ if (row.resource === DOCUMENT_EXTRACTION_RESOURCE && typeof row.id === 'string' && !saved.has(key(row)))
890
+ saved.set(key(row), row.id);
891
+ if (!saved.size)
892
+ return;
893
+ const rows = (result.bindings ?? []);
894
+ const written = new Set(rows.map((row) => row.id));
895
+ const renamed = new Map();
896
+ for (const row of rows) {
897
+ if (row.resource !== DOCUMENT_EXTRACTION_RESOURCE)
898
+ continue;
899
+ const id = saved.get(key(row));
900
+ if (id !== undefined && id !== row.id && !written.has(id))
901
+ renamed.set(row.id, id);
902
+ }
903
+ if (!renamed.size)
904
+ return;
905
+ for (const node of (result.nodes ?? [])) {
906
+ if (!String(node.type ?? '').endsWith('Stage'))
907
+ continue;
908
+ for (const task of (node.data?.tasks ?? []).flat()) {
909
+ if (task.type !== 'document-extraction')
910
+ continue;
911
+ for (const row of (task.data?.context ?? [])) {
912
+ const id = row.name === 'name' ? bindingRefId(row.value) : undefined;
913
+ if (id !== undefined && renamed.has(id))
914
+ row.value = `=bindings.${renamed.get(id)}`;
915
+ }
916
+ }
917
+ }
918
+ const reads = readBindingIds(result);
919
+ result.bindings = rows.filter((row) => !renamed.has(row.id) || reads.has(row.id));
920
+ }
870
921
  /**
871
922
  * Write each decompiled resource task's saved `=bindings.<id>` pair back over
872
923
  * the fresh one compile wrote (resource-wire.ts), while the task still names the
@@ -1112,6 +1163,7 @@ export function followRenames(result, preservation) {
1112
1163
  ...(preservation.connectorConfigurations ? { connectorConfigurations: preservation.connectorConfigurations.map(ref) } : {}),
1113
1164
  ...(preservation.httpRequestMetadata ? { httpRequestMetadata: preservation.httpRequestMetadata.map(ref) } : {}),
1114
1165
  ...(preservation.actionDataFields ? { actionDataFields: preservation.actionDataFields.map(ref) } : {}),
1166
+ ...(preservation.documentExtractionData ? { documentExtractionData: preservation.documentExtractionData.map(ref) } : {}),
1115
1167
  ...(preservation.omitTaskElementIds ? { omitTaskElementIds: preservation.omitTaskElementIds.map(ref) } : {}),
1116
1168
  ...(preservation.omitStagePositions ? { omitStagePositions: preservation.omitStagePositions.map(stageName) } : {}),
1117
1169
  ...(preservation.stageDataFields ? { stageDataFields: preservation.stageDataFields.map((entry) => ({ ...entry, stage: stageName(entry.stage) })) } : {}),
@@ -1933,7 +1985,9 @@ function emitTask(task, stageLabel, taskId, ids, resolver) {
1933
1985
  /** One task node (see {@link emitTask}). */
1934
1986
  function emitTaskNode(task, stageLabel, stageId, taskId, type, ids, resolver) {
1935
1987
  const node = { id: taskId, displayName: task.name, [CASE_FORMAT_PROFILE.nodeTypeField]: type };
1936
- node.data = taskData(task, resolver, taskId, stageId, ids);
1988
+ node.data = task.documentExtractionSaved
1989
+ ? savedDocumentExtractionData(`Document extraction task "${task.name}"`, resolver.savedDocumentExtractions, stageLabel, task.name, (task.outputs?.length ?? 0) > 0)
1990
+ : taskData(task, resolver, taskId, stageId, ids);
1937
1991
  // Every task carries `elementId: "<stageId>-<taskId>"`, the identity the
1938
1992
  // converter matches a task's io rows against:
1939
1993
  //
@@ -2064,6 +2118,12 @@ function taskData(task, resolver, taskId, stageId, ids) {
2064
2118
  : {};
2065
2119
  return withCustomOutputs(data, task, resolver);
2066
2120
  }
2121
+ case 'document-extraction':
2122
+ // Only `{ assign }` rows are written beside the two: a mapped row is one of them.
2123
+ return withCustomOutputs(documentExtractionTaskData(task, resolver, `${stageId}-${taskId}`), { ...task, outputs: task.outputs?.filter((o) => o.custom) }, resolver);
2124
+ case 'script':
2125
+ // Only `{ assign }` rows are written beside the two: a mapped row is one of them.
2126
+ return withCustomOutputs(scriptTaskData(task, resolver, `${stageId}-${taskId}`), { ...task, outputs: task.outputs?.filter((o) => o.custom) }, resolver);
2067
2127
  case 'http-request':
2068
2128
  // Only `{ assign }` rows are written beside the four: a mapped row is one of them.
2069
2129
  return withCustomOutputs(httpRequestTaskData(task, resolver, `${stageId}-${taskId}`), { ...task, outputs: task.outputs?.filter((o) => o.custom) }, resolver);
@@ -2733,6 +2793,95 @@ function externalTaskData(kind, spec, resolver, elementId, where) {
2733
2793
  context.push(io('activityConfigurationVersion', 'string', { value: 'v2' }));
2734
2794
  return { ...data, serviceType: externalServiceType(kind, mode) };
2735
2795
  }
2796
+ /**
2797
+ * A document-extraction task (`case/document-extraction.ts`): the Designer's
2798
+ * context naming the IXP deployment through one `ixpDeployment` name binding
2799
+ * per deployment and key (as convert writes it), the two inputs, and the two
2800
+ * outputs, claimed like any task output's and kept off the case's variables.
2801
+ */
2802
+ function documentExtractionTaskData(task, resolver, elementId) {
2803
+ const where = `Document extraction task "${task.name}"`;
2804
+ const spec = task.documentExtraction;
2805
+ if (!spec)
2806
+ throw new Error(`internal SDK error: ${where} has no deployment.`);
2807
+ const refused = documentExtractionRefusal(where, spec);
2808
+ if (refused)
2809
+ throw new CompileRefusal(refused.code, refused.message, refused.suggestion);
2810
+ const mappings = documentExtractionOutputMappings(where, task.outputs);
2811
+ if (!(mappings instanceof Map))
2812
+ throw new CompileRefusal(mappings.code, mappings.message, mappings.suggestion);
2813
+ let nameRef = '';
2814
+ if (spec.deployment.trim() !== '') {
2815
+ const key = spec.deploymentKey;
2816
+ const rows = [...resolver.bindingSink.values()];
2817
+ const found = rows.find((row) => row.resource === DOCUMENT_EXTRACTION_RESOURCE && row.default === spec.deployment
2818
+ && row.resourceKey === key);
2819
+ let id = found?.id;
2820
+ if (id === undefined) {
2821
+ const ordinal = rows.filter((row) => row.resource === DOCUMENT_EXTRACTION_RESOURCE).length + 1;
2822
+ id = `bIxp${ordinal}`;
2823
+ for (let n = ordinal + 1; resolver.bindingSink.has(id); n++)
2824
+ id = `bIxp${n}`;
2825
+ resolver.bindingSink.set(id, {
2826
+ id, name: 'name', type: 'string', resource: DOCUMENT_EXTRACTION_RESOURCE,
2827
+ resourceKey: key, default: spec.deployment, propertyAttribute: 'name',
2828
+ });
2829
+ }
2830
+ nameRef = `=bindings.${id}`;
2831
+ }
2832
+ const claim = (base) => {
2833
+ let id = claimOutputId(resolver, base);
2834
+ while (resolver.caseVarNames.has(id))
2835
+ id = claimOutputId(resolver, base);
2836
+ return id;
2837
+ };
2838
+ registerMappedCompanions(resolver, mappings);
2839
+ return {
2840
+ name: DOCUMENT_EXTRACTION_NAME,
2841
+ serviceType: DOCUMENT_EXTRACTION_SERVICE_TYPE,
2842
+ context: documentExtractionContext(spec, nameRef),
2843
+ // The `v` ids follow `ioSlot`, every connector task's.
2844
+ inputs: documentExtractionInputs(spec, elementId, (name) => `v${name}`),
2845
+ outputs: documentExtractionOutputs(elementId, claim, mappings),
2846
+ version: DOCUMENT_EXTRACTION_VERSION,
2847
+ };
2848
+ }
2849
+ /**
2850
+ * A script task (`case/script.ts`): the body behind the Designer's leading `=`,
2851
+ * its two inputs, and its two outputs, each claimed like any task output's and
2852
+ * kept off the case's own variable names (an output's `var` is its id).
2853
+ */
2854
+ function scriptTaskData(task, resolver, elementId) {
2855
+ const where = `Script task "${task.name}"`;
2856
+ const spec = task.script;
2857
+ if (!spec)
2858
+ throw new Error(`internal SDK error: ${where} has no body.`);
2859
+ const mappings = scriptOutputMappings(where, task.outputs);
2860
+ if (!(mappings instanceof Map))
2861
+ throw new CompileRefusal(mappings.code, mappings.message, mappings.suggestion);
2862
+ const claim = (base) => {
2863
+ let id = claimOutputId(resolver, base);
2864
+ while (resolver.caseVarNames.has(id))
2865
+ id = claimOutputId(resolver, base);
2866
+ return id;
2867
+ };
2868
+ registerMappedCompanions(resolver, mappings);
2869
+ return {
2870
+ script: storedScript(spec.body),
2871
+ inputs: SCRIPT_INPUTS.map((row) => ({ ...row })),
2872
+ outputs: scriptOutputs(elementId, claim, mappings, spec),
2873
+ };
2874
+ }
2875
+ /**
2876
+ * A mapped output writes a case variable the source may not declare. Its row
2877
+ * is reassigned (`var` is not its id), so like a connector extract's it needs a
2878
+ * root entry for `=vars.<name>` to read; a declared `.var()` wins the name.
2879
+ */
2880
+ function registerMappedCompanions(resolver, mappings) {
2881
+ for (const variable of mappings.values())
2882
+ if (!resolver.varCompanions.has(variable))
2883
+ resolver.varCompanions.set(variable, { id: variable, name: variable, type: 'object', elementId: 'root', custom: true });
2884
+ }
2736
2885
  /**
2737
2886
  * An HTTP request task (`case/http-request.ts`): the generic HTTP connector's
2738
2887
  * activity, with the request in the `body` input. A manual request names the
@@ -2752,12 +2901,7 @@ function httpRequestTaskData(task, resolver, elementId) {
2752
2901
  const mappings = httpRequestOutputMappings(where, task.outputs);
2753
2902
  if (!(mappings instanceof Map))
2754
2903
  throw new CompileRefusal(mappings.code, mappings.message, mappings.suggestion);
2755
- // A mapped output writes a case variable the source may not declare. Its row
2756
- // is reassigned (`var` is not its id), so like a connector extract's it needs
2757
- // a root entry for `=vars.<name>` to read; a declared `.var()` wins the name.
2758
- for (const variable of mappings.values())
2759
- if (!resolver.varCompanions.has(variable))
2760
- resolver.varCompanions.set(variable, { id: variable, name: variable, type: 'object', elementId: 'root', custom: true });
2904
+ registerMappedCompanions(resolver, mappings);
2761
2905
  let connection;
2762
2906
  let resourceKey = null;
2763
2907
  let folderKey = null;
@@ -3110,29 +3254,42 @@ function isOwnNameOutput(o) {
3110
3254
  const field = o.source.replace(/^=/, '').split('.').pop() ?? '';
3111
3255
  return keepsOwnName(o.var, field);
3112
3256
  }
3257
+ /** The ids of the carried document-extraction tasks' saved output rows. */
3258
+ function savedOutputIds(entries) {
3259
+ return (entries ?? []).flatMap((entry) => (Array.isArray(entry.data.outputs) ? entry.data.outputs : [])
3260
+ .map((row) => row?.id).filter((id) => typeof id === 'string'));
3261
+ }
3113
3262
  /**
3114
- * Every variable a task in the plan writes under its own name: own-name task
3115
- * outputs and action form outputs (whose row id is the variable). Collected
3116
- * before any row is emitted, so `claimOutputId` can keep suffixes off them.
3263
+ * The task kinds whose output rows are fixed (the task writes its own rows and
3264
+ * a `.outputs()` mapping reassigns one to a case variable), so a mapped
3265
+ * variable must be reserved before any row id is claimed. A document
3266
+ * extraction carried in the older shape (`.savedDocumentExtraction()`) maps
3267
+ * none: its saved rows are reserved by id instead (`savedOutputIds`).
3117
3268
  */
3269
+ const FIXED_OUTPUT_KINDS = new Set(['document-extraction', 'http-request', 'script']);
3118
3270
  /**
3119
- * The case variables a fixed-output task's `.outputs()` maps (an HTTP
3120
- * request's), declared or not. Collected before any task is emitted, so no
3121
- * task's own output row takes one of them as its id, whatever the task order:
3122
- * an undeclared one gets a root companion, and a row id equal to it would make
3123
- * two writers of one variable, or read back as unmapped.
3271
+ * The case variables a fixed-output task's `.outputs()` maps, declared or not.
3272
+ * Collected before any task is emitted, so no task's own output row takes one
3273
+ * of them as its id, whatever the task order: an undeclared one gets a root
3274
+ * companion, and a row id equal to it would make two writers of one variable,
3275
+ * or read back as unmapped.
3124
3276
  */
3125
3277
  function mappedFixedOutputVars(built) {
3126
3278
  const vars = new Set();
3127
3279
  for (const stage of built.stages)
3128
3280
  for (const lane of stage.lanes)
3129
3281
  for (const task of lane)
3130
- if (task.kind === 'http-request')
3282
+ if (FIXED_OUTPUT_KINDS.has(task.kind) && !task.documentExtractionSaved)
3131
3283
  for (const o of task.outputs ?? [])
3132
3284
  if (!o.custom)
3133
3285
  vars.add(o.var);
3134
3286
  return vars;
3135
3287
  }
3288
+ /**
3289
+ * Every variable a task in the plan writes under its own name: own-name task
3290
+ * outputs and action form outputs (whose row id is the variable). Collected
3291
+ * before any row is emitted, so `claimOutputId` can keep suffixes off them.
3292
+ */
3136
3293
  function ownOutputVars(built) {
3137
3294
  const vars = new Set();
3138
3295
  for (const stage of built.stages)
@@ -160,6 +160,17 @@ export declare const REFUSALS: {
160
160
  readonly CASE_IN_ARG_UNBOUND: "lowering";
161
161
  readonly CASE_LAYOUT_NODE_MATCH: "lowering";
162
162
  readonly CASE_LAYOUT_UNKNOWN_FIELD: "lowering";
163
+ readonly DOCUMENT_EXTRACTION_NO_MODEL: "lint";
164
+ readonly DOCUMENT_EXTRACTION_NO_DEPLOYMENT: "lint";
165
+ readonly DOCUMENT_EXTRACTION_NO_FOLDER_KEY: "lint";
166
+ readonly DOCUMENT_EXTRACTION_NO_FOLDER: "lint";
167
+ readonly DOCUMENT_EXTRACTION_NO_DEPLOYMENT_KEY: "lowering";
168
+ readonly DOCUMENT_EXTRACTION_NO_FILE: "lint";
169
+ readonly DOCUMENT_EXTRACTION_OUTPUT: "lowering";
170
+ readonly DOCUMENT_EXTRACTION_OLDER_SHAPE: "lint";
171
+ readonly DOCUMENT_EXTRACTION_SAVED_DATA: "lowering";
172
+ readonly SCRIPT_BODY_SYNTAX: "lint";
173
+ readonly SCRIPT_OUTPUT: "lowering";
163
174
  readonly HTTP_REQUEST_CONNECTOR: "lowering";
164
175
  readonly HTTP_REQUEST_TARGET: "lowering";
165
176
  readonly HTTP_REQUEST_FIELD: "lowering";
@@ -209,6 +209,28 @@ export const REFUSALS = {
209
209
  CASE_IN_ARG_UNBOUND: 'lowering',
210
210
  CASE_LAYOUT_NODE_MATCH: 'lowering',
211
211
  CASE_LAYOUT_UNKNOWN_FIELD: 'lowering',
212
+ // Case document-extraction task (case/document-extraction.ts). A missing
213
+ // model, folder key or file is written as authored (`lint`). A missing
214
+ // deployment key leaves the binding no resourceKey, which the platform
215
+ // rejects and decompile cannot read back, and an output other than the two
216
+ // has no row (`lowering`).
217
+ DOCUMENT_EXTRACTION_NO_MODEL: 'lint',
218
+ DOCUMENT_EXTRACTION_NO_DEPLOYMENT: 'lint',
219
+ DOCUMENT_EXTRACTION_NO_FOLDER_KEY: 'lint',
220
+ DOCUMENT_EXTRACTION_NO_FOLDER: 'lint',
221
+ DOCUMENT_EXTRACTION_NO_DEPLOYMENT_KEY: 'lowering',
222
+ DOCUMENT_EXTRACTION_NO_FILE: 'lint',
223
+ DOCUMENT_EXTRACTION_OUTPUT: 'lowering',
224
+ // The older, flat shape, carried as saved (case/document-extraction-saved.ts):
225
+ // check warns it is not editable (`lint`); compile refuses a carried task with
226
+ // no saved data, or with outputs it cannot add to the saved rows (`lowering`).
227
+ DOCUMENT_EXTRACTION_OLDER_SHAPE: 'lint',
228
+ DOCUMENT_EXTRACTION_SAVED_DATA: 'lowering',
229
+ // Case script task (case/script.ts). A string body that does not parse is
230
+ // written as authored (`lint`); an output other than the two has no row to
231
+ // write it to (`lowering`).
232
+ SCRIPT_BODY_SYNTAX: 'lint',
233
+ SCRIPT_OUTPUT: 'lowering',
212
234
  // Case http-request task (case/http-request.ts). `lowering`: compile would
213
235
  // drop or rewrite what the source says. `lint`: compile writes it as
214
236
  // authored, and only `check` reports it.
@@ -0,0 +1,34 @@
1
+ /**
2
+ * core/script-engine — what the engine gives a script body, whichever family
3
+ * wrote the task: a Flow script node and a Case script task both run on
4
+ * UiPath/PO.BpmnEngine's script service, Jint 4.4.0
5
+ * (`ScriptTaskService.InvokeScriptAsync`,
6
+ * `src/BpmnEngine/UiPath.PO.Worker/Services/ElementExecution/Script/ScriptTaskService.cs`).
7
+ * Each family's `ScriptRuntime` (`core/script-function.ts`) names its own scope
8
+ * globals and takes these facts from here, so the two lists cannot drift.
9
+ * Moved from `nodes/script/flow/runtime.ts`, where the measurements are
10
+ * described; change them when the engine does.
11
+ */
12
+ /**
13
+ * The names the engine's preludes declare with `const` before the script runs
14
+ * (`ScriptTaskService.cs`, `WithBuiltInFunctions` and `WithConsole`). At the
15
+ * body's top level, a `const`, `let`, `var`, `function` or `class` of one fails
16
+ * with "Identifier '…' has already been declared", and an assignment to one with
17
+ * "Assignment to constant variable." (both measured on Jint 4.4.0). Inside a
18
+ * nested block or function the name is the author's own and is fine.
19
+ */
20
+ export declare const SCRIPT_ENGINE_CONST_GLOBALS: ReadonlySet<string>;
21
+ /**
22
+ * The members the engine's own objects have; any other member reads
23
+ * `undefined`, so calling it throws "Property '…' of object is not a function"
24
+ * (measured on Jint 4.4.0). `crypto` holds only `randomUUID`
25
+ * (`JavaScriptEvaluator.cs`), and `console` only the five no-ops `WithConsole`
26
+ * declares (`ScriptTaskService.cs`).
27
+ */
28
+ export declare const SCRIPT_ENGINE_GLOBAL_MEMBERS: ReadonlyMap<string, ReadonlySet<string>>;
29
+ /**
30
+ * Every global a script body can read besides its family's scope globals: the
31
+ * language's ES2020 built-ins, the globals the engine registers (`btoa`,
32
+ * `atob`, `randomUUID`, `crypto`), and `console`.
33
+ */
34
+ export declare const SCRIPT_ENGINE_GLOBALS: ReadonlySet<string>;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * core/script-engine — what the engine gives a script body, whichever family
3
+ * wrote the task: a Flow script node and a Case script task both run on
4
+ * UiPath/PO.BpmnEngine's script service, Jint 4.4.0
5
+ * (`ScriptTaskService.InvokeScriptAsync`,
6
+ * `src/BpmnEngine/UiPath.PO.Worker/Services/ElementExecution/Script/ScriptTaskService.cs`).
7
+ * Each family's `ScriptRuntime` (`core/script-function.ts`) names its own scope
8
+ * globals and takes these facts from here, so the two lists cannot drift.
9
+ * Moved from `nodes/script/flow/runtime.ts`, where the measurements are
10
+ * described; change them when the engine does.
11
+ */
12
+ /**
13
+ * The names the engine's preludes declare with `const` before the script runs
14
+ * (`ScriptTaskService.cs`, `WithBuiltInFunctions` and `WithConsole`). At the
15
+ * body's top level, a `const`, `let`, `var`, `function` or `class` of one fails
16
+ * with "Identifier '…' has already been declared", and an assignment to one with
17
+ * "Assignment to constant variable." (both measured on Jint 4.4.0). Inside a
18
+ * nested block or function the name is the author's own and is fine.
19
+ */
20
+ export const SCRIPT_ENGINE_CONST_GLOBALS = new Set(['console', 'uipath', 'aggregate', '_aggregate', '_pipe']);
21
+ /**
22
+ * The members the engine's own objects have; any other member reads
23
+ * `undefined`, so calling it throws "Property '…' of object is not a function"
24
+ * (measured on Jint 4.4.0). `crypto` holds only `randomUUID`
25
+ * (`JavaScriptEvaluator.cs`), and `console` only the five no-ops `WithConsole`
26
+ * declares (`ScriptTaskService.cs`).
27
+ */
28
+ export const SCRIPT_ENGINE_GLOBAL_MEMBERS = new Map([
29
+ ['crypto', new Set(['randomUUID'])],
30
+ ['console', new Set(['debug', 'error', 'info', 'log', 'warn'])],
31
+ ]);
32
+ /**
33
+ * Every global a script body can read besides its family's scope globals: the
34
+ * language's ES2020 built-ins, the globals the engine registers (`btoa`,
35
+ * `atob`, `randomUUID`, `crypto`), and `console`.
36
+ */
37
+ export const SCRIPT_ENGINE_GLOBALS = new Set([
38
+ 'undefined', 'NaN', 'Infinity', 'globalThis', 'console',
39
+ 'btoa', 'atob', 'randomUUID', 'crypto',
40
+ 'Object', 'Function', 'Array', 'Number', 'Boolean', 'String', 'Symbol', 'BigInt', 'Date', 'RegExp', 'Math', 'JSON',
41
+ 'Promise', 'Proxy', 'Reflect', 'Map', 'Set', 'WeakMap', 'WeakSet',
42
+ 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError',
43
+ 'ArrayBuffer', 'SharedArrayBuffer', 'DataView', 'Atomics',
44
+ 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array',
45
+ 'Float32Array', 'Float64Array', 'BigInt64Array', 'BigUint64Array',
46
+ 'parseInt', 'parseFloat', 'isNaN', 'isFinite',
47
+ 'encodeURI', 'encodeURIComponent', 'decodeURI', 'decodeURIComponent', 'eval',
48
+ ]);
@@ -20,7 +20,7 @@ import type { ScriptRuntime } from '../../../core/script-function.js';
20
20
  * the body goes to `Engine.Evaluate` as a script, after `btoa`/`atob` (UTF-8),
21
21
  * `randomUUID` and `crypto` (holding only `randomUUID`) are set
22
22
  * (`src/BpmnEngine/UiPath.PO.BpmnEngine/Expressions/JavaScriptEvaluator.cs`) and
23
- * two preludes declare {@link FLOW_SCRIPT_CONST_GLOBALS} with `const`. `Intl`,
23
+ * two preludes declare {@link SCRIPT_ENGINE_CONST_GLOBALS} with `const`. `Intl`,
24
24
  * `URL`, `TextEncoder`, `Buffer`, `fetch`, `require` and `structuredClone` read
25
25
  * `undefined` there, so they are absent here. Change this when the engine does.
26
26
  *