@uipath/maestro-builder-sdk 6.80.0 → 6.81.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.
@@ -1,22 +1,3 @@
1
- /**
2
- * case-sdk — a fluent builder for UiPath Case Management plans (`caseplan.json`,
3
- * schema V32).
4
- *
5
- * Like the Flow builder, this constructs a plain description of a case — its
6
- * stages, the tasks inside them, and the entry/exit *conditions* that drive
7
- * transitions — which `serialize()` turns into a real `caseplan.json`. A case is
8
- * a hierarchy (stages → tasks), not a graph: there are **no edges**; flow
9
- * between stages is expressed entirely through conditions (see `rule()`).
10
- *
11
- * This first cut is **reference-mode**: a task points at an already-published
12
- * process/agent/rpa/workflow by name + folder. (Embedding an inline flow/bpmn
13
- * body in a task is a later phase.) The builder uses callback closures for
14
- * nesting, matching the Flow SDK's `.branch(name, cond, b => …)` style — so a
15
- * `casePlan()` only ever exposes case methods, and each nested builder only its
16
- * own.
17
- *
18
- * `casePlan` (not `case`) is the entry point: `case` is a reserved word.
19
- */
20
1
  import type { TypeDesc } from '../core/expr.js';
21
2
  import { type ActionSpec, type ConnectorOpts, type CaseEventFilter, type EventSubscription, type TriggerOptions } from '../core/actions.js';
22
3
  import { type ConnectorDescriptor, type TriggerDescriptor } from '../core/connectors.js';
@@ -441,7 +422,7 @@ export interface BuiltCaseExitCondition {
441
422
  marksCaseComplete?: boolean;
442
423
  rules: CaseRule[][];
443
424
  }
444
- export type TaskKind = 'process' | 'agent' | 'rpa' | 'api-workflow' | 'case-management' | 'flow-process' | 'function' | 'business-rule' | 'external-agent' | 'external-workflow' | 'action' | 'connector' | 'wait-for-timer' | 'wait-for-connector' | 'http-request';
425
+ export type TaskKind = 'process' | 'agent' | 'rpa' | 'api-workflow' | 'case-management' | 'flow-process' | 'function' | 'business-rule' | 'external-agent' | 'external-workflow' | 'action' | 'connector' | 'wait-for-timer' | 'wait-for-connector' | 'script' | 'http-request';
445
426
  /**
446
427
  * Task kinds that the Case schema permits as unresolved skeletons: the
447
428
  * published-resource kinds, `action` (a human task whose Action App or form is
@@ -529,6 +510,24 @@ export interface CaseConnectorOpts extends ConnectorOpts {
529
510
  */
530
511
  carriedFields?: readonly CarriedConnectorField[];
531
512
  }
513
+ /** Options for a script task (`.script()`): the schemas the Designer keeps on its two outputs. */
514
+ export interface CaseScriptOptions {
515
+ /**
516
+ * The JSON schema of what the body returns, written as `scriptResponse`'s
517
+ * `_jsonSchema`. The Designer infers it from the body when it saves the plan;
518
+ * decompile carries the one it saved, so a recompile keeps it.
519
+ */
520
+ responseSchema?: Record<string, unknown>;
521
+ /** The JSON schema of the `Error` output, which a Designer-saved task may carry. A new task has none. */
522
+ errorSchema?: Record<string, unknown>;
523
+ }
524
+ /** A built script task: the body as it runs (no leading `=`), and how it was authored. */
525
+ export interface CaseScriptSpec extends CaseScriptOptions {
526
+ /** The JavaScript body, as the engine runs it. */
527
+ body: string;
528
+ /** Whether the body was lowered from a TypeScript function (so the compiler checked it). */
529
+ fromFunction: boolean;
530
+ }
532
531
  /** A method the HTTP request activity offers. */
533
532
  export type HttpRequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
534
533
  /**
@@ -867,6 +866,8 @@ export interface BuiltTask {
867
866
  connector?: ConnectorSpecData;
868
867
  /** Descriptor-resolved external agent/workflow configuration. */
869
868
  external?: ExternalTaskSpecData;
869
+ /** script task: the body. */
870
+ script?: CaseScriptSpec;
870
871
  /** http-request task: the request. */
871
872
  http?: CaseHttpRequestSpec;
872
873
  timer?: TimerSpecData;
@@ -1126,6 +1127,7 @@ declare class TaskBuilder {
1126
1127
  private _action?;
1127
1128
  private _connector?;
1128
1129
  private _external?;
1130
+ private _script?;
1129
1131
  private _http?;
1130
1132
  private _timer?;
1131
1133
  private _waitConnector?;
@@ -1372,6 +1374,36 @@ declare class TaskBuilder {
1372
1374
  * @returns This builder, so calls chain.
1373
1375
  */
1374
1376
  waitForTimer(spec: TimerSpecData): this;
1377
+ /**
1378
+ * A script task: a JavaScript body the engine runs, reading case state
1379
+ * through `vars` (the case variables) and `metadata` (the instance metadata).
1380
+ * The task writes two outputs: what the body returns, as `scriptResponse`
1381
+ * (`=result.response`), and `Error`. Map the return to a case variable with
1382
+ * `.outputs({ scriptResult: '=result.response' })`.
1383
+ *
1384
+ * Pass a TypeScript function and the compiler checks the body like the rest
1385
+ * of the module. It is never called: its body, exactly as written, becomes
1386
+ * the script, and its parameters are renamed to the runtime's `vars` and
1387
+ * `metadata` (take neither, `vars` alone, or both). It may read only what the
1388
+ * engine gives a script (the ES2020 built-ins and `console`), so a module
1389
+ * constant, an import or a library is refused, because in the run it would be
1390
+ * a `ReferenceError`.
1391
+ *
1392
+ * ```ts
1393
+ * .task('Double', (t) => t.script((vars: { amount: number }) => ({ total: vars.amount * 2 }))
1394
+ * .outputs({ scriptResult: '=result.response' }))
1395
+ * ```
1396
+ *
1397
+ * A string is the body as written, unchecked by the compiler.
1398
+ *
1399
+ * @param body - The script, as a function of the case variables and the instance metadata (or of fewer), or its JavaScript text.
1400
+ * @param options - The schemas the Designer keeps on the two outputs, which decompile carries.
1401
+ * @returns This builder, so calls chain.
1402
+ * @enforcedBy SCRIPT_FUNCTION_UNLOWERABLE A function that cannot be a script body is refused at the call.
1403
+ * @enforcedBy SCRIPT_TASK_NO_BODY `check` reports a blank body.
1404
+ * @enforcedBy SCRIPT_BODY_SYNTAX `check` reports a string body that does not parse as JavaScript.
1405
+ */
1406
+ script<V, M = unknown>(body: ((vars: V, metadata: M) => unknown) | string, options?: CaseScriptOptions): this;
1375
1407
  /**
1376
1408
  * An HTTP request through Integration Service's generic HTTP connector, the
1377
1409
  * Case Designer's HTTP request task. The task writes four outputs, `code`,
@@ -1,3 +1,24 @@
1
+ /**
2
+ * case-sdk — a fluent builder for UiPath Case Management plans (`caseplan.json`,
3
+ * schema V32).
4
+ *
5
+ * Like the Flow builder, this constructs a plain description of a case — its
6
+ * stages, the tasks inside them, and the entry/exit *conditions* that drive
7
+ * transitions — which `serialize()` turns into a real `caseplan.json`. A case is
8
+ * a hierarchy (stages → tasks), not a graph: there are **no edges**; flow
9
+ * between stages is expressed entirely through conditions (see `rule()`).
10
+ *
11
+ * This first cut is **reference-mode**: a task points at an already-published
12
+ * process/agent/rpa/workflow by name + folder. (Embedding an inline flow/bpmn
13
+ * body in a task is a later phase.) The builder uses callback closures for
14
+ * nesting, matching the Flow SDK's `.branch(name, cond, b => …)` style — so a
15
+ * `casePlan()` only ever exposes case methods, and each nested builder only its
16
+ * own.
17
+ *
18
+ * `casePlan` (not `case`) is the entry point: `case` is a reserved word.
19
+ */
20
+ import { lowerScriptFunction } from '../core/script-function.js';
21
+ import { CASE_SCRIPT_RUNTIME } from './script.js';
1
22
  import { ACTION_PASSTHROUGH_SETTINGS } from './action-settings.js';
2
23
  import { connector as makeConnector, subscriptionFrom, } from '../core/actions.js';
3
24
  import { isTriggerDescriptor } from '../core/connectors.js';
@@ -222,6 +243,7 @@ class TaskBuilder {
222
243
  _action;
223
244
  _connector;
224
245
  _external;
246
+ _script;
225
247
  _http;
226
248
  _timer;
227
249
  _waitConnector;
@@ -486,6 +508,44 @@ class TaskBuilder {
486
508
  this._timer = spec;
487
509
  return this;
488
510
  }
511
+ /**
512
+ * A script task: a JavaScript body the engine runs, reading case state
513
+ * through `vars` (the case variables) and `metadata` (the instance metadata).
514
+ * The task writes two outputs: what the body returns, as `scriptResponse`
515
+ * (`=result.response`), and `Error`. Map the return to a case variable with
516
+ * `.outputs({ scriptResult: '=result.response' })`.
517
+ *
518
+ * Pass a TypeScript function and the compiler checks the body like the rest
519
+ * of the module. It is never called: its body, exactly as written, becomes
520
+ * the script, and its parameters are renamed to the runtime's `vars` and
521
+ * `metadata` (take neither, `vars` alone, or both). It may read only what the
522
+ * engine gives a script (the ES2020 built-ins and `console`), so a module
523
+ * constant, an import or a library is refused, because in the run it would be
524
+ * a `ReferenceError`.
525
+ *
526
+ * ```ts
527
+ * .task('Double', (t) => t.script((vars: { amount: number }) => ({ total: vars.amount * 2 }))
528
+ * .outputs({ scriptResult: '=result.response' }))
529
+ * ```
530
+ *
531
+ * A string is the body as written, unchecked by the compiler.
532
+ *
533
+ * @param body - The script, as a function of the case variables and the instance metadata (or of fewer), or its JavaScript text.
534
+ * @param options - The schemas the Designer keeps on the two outputs, which decompile carries.
535
+ * @returns This builder, so calls chain.
536
+ * @enforcedBy SCRIPT_FUNCTION_UNLOWERABLE A function that cannot be a script body is refused at the call.
537
+ * @enforcedBy SCRIPT_TASK_NO_BODY `check` reports a blank body.
538
+ * @enforcedBy SCRIPT_BODY_SYNTAX `check` reports a string body that does not parse as JavaScript.
539
+ */
540
+ script(body, options = {}) {
541
+ this.setKind('script');
542
+ const fromFunction = typeof body === 'function';
543
+ const text = fromFunction
544
+ ? lowerScriptFunction(body, CASE_SCRIPT_RUNTIME, `task "${this._name}": .script(${body.name || 'function'})`)
545
+ : body;
546
+ this._script = { body: text, fromFunction, ...options };
547
+ return this;
548
+ }
489
549
  /**
490
550
  * An HTTP request through Integration Service's generic HTTP connector, the
491
551
  * Case Designer's HTTP request task. The task writes four outputs, `code`,
@@ -698,8 +758,9 @@ class TaskBuilder {
698
758
  // more row after them, as `uip maestro case sdd convert` and `case splice`
699
759
  // write an SDD row `app_id -> postAppId`.
700
760
  const REF_IO = new Set(['process', 'agent', 'rpa', 'api-workflow', 'case-management', 'flow-process', 'function', 'business-rule']);
701
- // An http-request task writes the activity's four outputs; an extract maps one to a variable.
702
- const CONNECTOR_OUTPUTS = new Set(['connector', 'wait-for-connector', 'http-request']);
761
+ // A script task writes its two outputs, an http-request task the activity's
762
+ // four; an extract maps one to a variable.
763
+ const CONNECTOR_OUTPUTS = new Set(['connector', 'wait-for-connector', 'script', 'http-request']);
703
764
  if (this._inputs && !REF_IO.has(this._kind))
704
765
  throw new CompileRefusal('TASK_INPUTS_UNSUPPORTED', `task "${this._name}": .inputs() is only supported on reference-mode tasks (process/agent/rpa/api-workflow/case-management/flow-process/function/business-rule), not "${this._kind}". A connector task takes its inputs in .connector() / .waitForConnector().`);
705
766
  // Which rows a kind accepts depends on the row: an extract reads the task's
@@ -731,6 +792,7 @@ class TaskBuilder {
731
792
  action: this._action,
732
793
  connector: this._connector,
733
794
  external: this._external,
795
+ script: this._script,
734
796
  http: this._http,
735
797
  timer: this._timer,
736
798
  waitConnector: this._waitConnector,
@@ -3,6 +3,7 @@ import { CASE_FORMAT_PROFILE, CASE_SCHEMA_VERSIONS, authoredCaseVersion } from '
3
3
  import { schemaVersionRefusal } from '../schema-version.js';
4
4
  import { EQUALS_EXPR_DIALECT, checkConnectorLookups, checkConnectorResources, checkConnectorSchema, } from '../core/connector-checks.js';
5
5
  import { isConnectorPlaceholder } from './connector-placeholder.js';
6
+ import { scriptLint } from './script.js';
6
7
  import { httpRequestLint } from './http-request.js';
7
8
  import { checkRuleSemantics } from './check-rule-semantics.js';
8
9
  import { serialize } from './serialize.js';
@@ -208,6 +209,13 @@ export function check(built, opts = {}) {
208
209
  refStage(r, 'case-exit');
209
210
  refPlacement(r, 'case-exit', 'case-exit');
210
211
  }
212
+ // A script body compile writes as authored but a person should fix (lint).
213
+ for (const stage of built.stages)
214
+ for (const lane of stage.lanes)
215
+ for (const t of lane)
216
+ if (t.kind === 'script' && t.script)
217
+ for (const f of scriptLint(`Script task "${t.name}"`, t.script))
218
+ diags.push({ level: 'error', code: f.code, message: f.message, ...(f.suggestion ? { suggestion: f.suggestion } : {}), where: t.name });
211
219
  // An HTTP request compile writes as authored but a person should fix (lint;
212
220
  // what it cannot write is the serializer's, through collect mode).
213
221
  for (const stage of built.stages)
@@ -0,0 +1,23 @@
1
+ /**
2
+ * case/decompile-script — the decompile half of the Case `script` task
3
+ * (`./script.ts` holds the shape compile writes). It lifts a saved task's
4
+ * `data` to the `.script()` call that compiles back to it, and throws, naming
5
+ * the field, on anything a recompile would not write back. Decompile-side, so
6
+ * its refusals are plain Errors (FB017 scopes it out by name).
7
+ *
8
+ * The body is lifted as a string, exactly as stored: printing it as a typed
9
+ * function, as Flow's decompile can (`printAsFunction`), is a follow-up.
10
+ */
11
+ import type { CaseScriptOptions } from './case-sdk.js';
12
+ /** What a script task's `data` lifts to: the body and the schemas the Designer kept on its outputs. */
13
+ export interface LiftedScript {
14
+ body: string;
15
+ options: CaseScriptOptions;
16
+ }
17
+ export declare function liftScript(owner: string, data: Record<string, unknown>): LiftedScript;
18
+ /** One of the task's own output rows, which compile writes itself; a custom row is never one. */
19
+ export declare function isScriptOwnOutput(row: {
20
+ custom?: unknown;
21
+ name?: unknown;
22
+ source?: unknown;
23
+ }): boolean;
@@ -0,0 +1,53 @@
1
+ import { SCRIPT_INPUTS, SCRIPT_OUTPUTS, scriptBody } from './script.js';
2
+ /** The output-row fields compile writes, per output; any other is refused. */
3
+ const OWN_FIELDS = new Map([
4
+ ['scriptResponse', new Set(['name', 'type', 'source', 'id', 'var', 'value', 'elementId', 'target', 'originalVar', '_jsonSchema'])],
5
+ ['Error', new Set(['name', 'displayName', 'type', 'source', 'id', 'var', 'value', 'elementId', 'target', 'originalVar', '_jsonSchema', 'body'])],
6
+ ]);
7
+ export function liftScript(owner, data) {
8
+ const fail = (why) => {
9
+ throw new Error(`${owner} ${why}`);
10
+ };
11
+ const unknown = Object.keys(data).find((k) => !['script', 'inputs', 'outputs'].includes(k));
12
+ if (unknown)
13
+ fail(`has unsupported data field "${unknown}".`);
14
+ if (typeof data.script !== 'string')
15
+ fail('has no script body.');
16
+ const inputs = Array.isArray(data.inputs) ? data.inputs : [];
17
+ if (JSON.stringify(inputs) !== JSON.stringify(SCRIPT_INPUTS))
18
+ fail(`has inputs ${JSON.stringify(inputs)}; a script task's are exactly vars = "=vars" and metadata = "=metadata", which compile writes.`);
19
+ const outputs = (Array.isArray(data.outputs) ? data.outputs : []);
20
+ const own = outputs.filter((o) => o.custom !== true);
21
+ if (own.map((o) => `${String(o.name)}:${String(o.source)}`).join(',') !== SCRIPT_OUTPUTS.map((o) => `${o.name}:${o.source}`).join(','))
22
+ fail(`has outputs ${JSON.stringify(own.map((o) => o.name))}; a script task writes scriptResponse (=result.response) and Error (=Error), in that order.`);
23
+ const options = {};
24
+ for (const row of own) {
25
+ const name = String(row.name);
26
+ const fields = OWN_FIELDS.get(name) ?? new Set();
27
+ const odd = Object.keys(row).find((k) => !fields.has(k));
28
+ if (odd)
29
+ fail(`output "${name}" has field "${odd}", which compile does not write.`);
30
+ if (row.type !== 'jsonSchema')
31
+ fail(`output "${name}" has type ${JSON.stringify(row.type)}; it is "jsonSchema".`);
32
+ const schema = row._jsonSchema;
33
+ if (schema !== undefined && (typeof schema !== 'object' || schema === null || Array.isArray(schema)))
34
+ fail(`output "${name}" has a _jsonSchema that is not an object.`);
35
+ if (name === 'scriptResponse' && schema !== undefined)
36
+ options.responseSchema = schema;
37
+ if (name === 'Error') {
38
+ // Compile writes an Error schema as the Designer keeps it: `_jsonSchema`, `body` and `displayName`, together.
39
+ const carried = [schema !== undefined, row.body !== undefined, row.displayName === 'Error'];
40
+ if (carried.some(Boolean) && !carried.every(Boolean))
41
+ fail('output "Error" carries part of a schema; compile writes _jsonSchema, body and displayName together.');
42
+ if (schema !== undefined && JSON.stringify(schema) !== JSON.stringify(row.body))
43
+ fail('output "Error" has a body that is not its _jsonSchema; compile writes the one schema to both.');
44
+ if (schema !== undefined)
45
+ options.errorSchema = schema;
46
+ }
47
+ }
48
+ return { body: scriptBody(String(data.script)), options };
49
+ }
50
+ /** One of the task's own output rows, which compile writes itself; a custom row is never one. */
51
+ export function isScriptOwnOutput(row) {
52
+ return row.custom !== true && SCRIPT_OUTPUTS.some((o) => o.name === row.name && o.source === row.source);
53
+ }
@@ -3,6 +3,7 @@ import { cachedFieldValues, connectorTaskIdentity, savedOptionalConfiguration }
3
3
  import { commentText } from '../core/comment-text.js';
4
4
  import { implicitInArgTrigger } from './in-arg-binding.js';
5
5
  import { tsLiteral, tsNumber } from '../core/ts-literal.js';
6
+ import { isScriptOwnOutput, liftScript } from './decompile-script.js';
6
7
  import { isHttpRequestOwnOutput, liftHttpRequest } from './decompile-http-request.js';
7
8
  import { savedHttpRequestMetadata } from './http-request.js';
8
9
  import { CASE_FORMAT_PROFILE, CASE_SCHEMA_VERSIONS } from './format-profile.js';
@@ -1094,6 +1095,14 @@ function emitTaskKind(task, refs, library) {
1094
1095
  }
1095
1096
  if (kind === 'execute-connector-activity')
1096
1097
  return connectorCall(task, refs, library);
1098
+ if (kind === 'script') {
1099
+ const lifted = liftScript(`script task "${task.displayName ?? task.id ?? '?'}"`, (data ?? {}));
1100
+ const options = opts([
1101
+ ['responseSchema', lifted.options.responseSchema !== undefined ? tsLiteral(lifted.options.responseSchema) : undefined],
1102
+ ['errorSchema', lifted.options.errorSchema !== undefined ? tsLiteral(lifted.options.errorSchema) : undefined],
1103
+ ]);
1104
+ return `.script(${tsLiteral(lifted.body)}${options ? `, ${options}` : ''})`;
1105
+ }
1097
1106
  if (kind === 'http-request') {
1098
1107
  const spec = liftHttpRequest(`http-request task "${task.displayName ?? task.id ?? '?'}"`, (data ?? {}), {
1099
1108
  binding: (id) => refs.bindingById.get(id),
@@ -1328,6 +1337,12 @@ function taskOutputRows(task) {
1328
1337
  plan = customOnly(actionFormOutputs(task));
1329
1338
  else if (kind === 'wait-for-timer')
1330
1339
  plan = customOnly([]);
1340
+ // A script task writes its two rows itself; one it maps to a case variable is lifted too.
1341
+ else if (kind === 'script')
1342
+ plan = {
1343
+ lifted: rows.filter((row) => row.custom === true || (isScriptOwnOutput(row) && row.var !== row.id)),
1344
+ rebuilt: rows.filter(isScriptOwnOutput),
1345
+ };
1331
1346
  // An HTTP request writes its four rows itself; a row it maps to a case variable is lifted too.
1332
1347
  else if (kind === 'http-request')
1333
1348
  plan = {
package/dist/case/load.js CHANGED
@@ -4,6 +4,8 @@ import { resolve } from 'node:path';
4
4
  import { existsSync, statSync } from 'node:fs';
5
5
  import { useThisSdkForAuthoredSource } from '../sdk-resolve.js';
6
6
  import { CompileRefusal } from '../core/compile-refusal.js';
7
+ import { scriptFunctionLowerings } from '../core/script-function.js';
8
+ import { scriptFunctionScopeProblem } from '../script-function-scope.js';
7
9
  /**
8
10
  * Resolve a user argument (a `.ts` path or a BaseName) to a case source file.
9
11
  *
@@ -24,6 +26,7 @@ export function resolveCaseFile(arg) {
24
26
  }
25
27
  export async function loadBuiltCase(file) {
26
28
  useThisSdkForAuthoredSource();
29
+ const firstLowering = scriptFunctionLowerings().length;
27
30
  const mod = await import(pathToFileURL(file).href);
28
31
  const exp = mod.default ?? mod.casePlan ?? mod.case;
29
32
  if (!exp)
@@ -31,5 +34,14 @@ export async function loadBuiltCase(file) {
31
34
  const built = typeof exp.build === 'function' ? exp.build() : exp;
32
35
  if (!built || !Array.isArray(built.stages))
33
36
  throw new CompileRefusal('CASE_EXPORT_NOT_BUILT', `${file} default export is not a built case. Did you call .build()?`);
37
+ // A `.script(fn)` function was lowered from its own text, which cannot show a
38
+ // name it takes from its module; this source can (script-function-scope.ts),
39
+ // as Flow's loader does. Only a case that lowered one pays for the program.
40
+ const lowered = scriptFunctionLowerings().slice(firstLowering);
41
+ if (lowered.length > 0) {
42
+ const problem = scriptFunctionScopeProblem(file, lowered);
43
+ if (problem)
44
+ throw new CompileRefusal('SCRIPT_FUNCTION_SCOPE', problem);
45
+ }
34
46
  return built;
35
47
  }
@@ -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
+ }