@protobase/workflows 0.99.16 → 0.100.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/definition/check-aws.js +80 -0
  2. package/dist/definition/check-definition.d.ts +4 -0
  3. package/dist/definition/check-definition.js +27 -10
  4. package/dist/definition/check-reads.js +9 -4
  5. package/dist/definition/check-schema.js +19 -7
  6. package/dist/definition/dataflow/check-dataflow.js +36 -0
  7. package/dist/definition/dataflow/dependencies.d.ts +17 -0
  8. package/dist/definition/dataflow/dependencies.js +88 -0
  9. package/dist/definition/expression-fields.d.ts +5 -0
  10. package/dist/definition/expression-fields.js +1 -0
  11. package/dist/definition/expressions.d.ts +5 -0
  12. package/dist/definition/graph.js +1 -1
  13. package/dist/definition/parts.d.ts +21 -0
  14. package/dist/definition/parts.js +21 -0
  15. package/dist/definition/pins/check-pins.js +40 -0
  16. package/dist/definition/pins/pin-sources.d.ts +33 -0
  17. package/dist/definition/pins/pin-sources.js +78 -0
  18. package/dist/definition/pins/pin-type.d.ts +19 -0
  19. package/dist/definition/pins/pin-type.js +61 -0
  20. package/dist/definition/pins/references.d.ts +32 -0
  21. package/dist/definition/pins/references.js +118 -0
  22. package/dist/definition/pins/resolve-schema.d.ts +21 -0
  23. package/dist/definition/pins/resolve-schema.js +62 -0
  24. package/dist/definition/reads.js +17 -10
  25. package/dist/definition/schema.d.ts +285 -191
  26. package/dist/definition/schema.js +275 -245
  27. package/dist/definition/types.d.ts +16 -4
  28. package/dist/definition/types.js +5 -0
  29. package/dist/definition/visible.js +6 -4
  30. package/dist/index.d.ts +11 -3
  31. package/dist/index.js +12 -3
  32. package/dist/plugin/index.d.ts +2 -1
  33. package/dist/plugin/index.js +2 -1
  34. package/dist/plugin/value-check.d.ts +9 -0
  35. package/dist/plugin/value-check.js +24 -0
  36. package/dist/run/block-state.js +1 -1
  37. package/dist/run/context.d.ts +2 -1
  38. package/dist/run/dataflow.js +183 -0
  39. package/dist/run/position.js +16 -11
  40. package/dist/run/recovery.js +22 -3
  41. package/dist/run/rerun-from.d.ts +8 -5
  42. package/dist/run/rerun-from.js +61 -5
  43. package/dist/run/rerun.d.ts +4 -3
  44. package/dist/run/rerun.js +16 -7
  45. package/dist/run/result-states.js +3 -3
  46. package/dist/run/scope.js +5 -4
  47. package/dist/run/segment.js +5 -2
  48. package/package.json +1 -1
@@ -0,0 +1,80 @@
1
+ //#region src/definition/check-aws.ts
2
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ const jsonPathFields = [
4
+ "InputPath",
5
+ "Parameters",
6
+ "ResultSelector",
7
+ "ResultPath",
8
+ "OutputPath",
9
+ "ItemsPath"
10
+ ];
11
+ const awsFields = {
12
+ ItemReader: "is a distributed Map's reader, which does not run here; give the Map its Items",
13
+ ItemBatcher: "is a distributed Map's batcher, which does not run here",
14
+ ResultWriter: "is a distributed Map's writer, which does not run here",
15
+ ToleratedFailureCount: "is a distributed Map's, which does not run here",
16
+ ToleratedFailurePercentage: "is a distributed Map's, which does not run here",
17
+ HeartbeatSeconds: "does not run here: a step type ends or fails within its TimeoutSeconds",
18
+ Credentials: "does not run here: a step signs in through the connection its type declares"
19
+ };
20
+ const stateProblems = (states, path) => {
21
+ if (!isObject(states)) return [];
22
+ return Object.entries(states).flatMap(([name, state]) => {
23
+ if (!isObject(state)) return [];
24
+ const where = [...path, name].join("/");
25
+ const found = [];
26
+ if (state.Type === "Parallel") found.push({
27
+ state: where,
28
+ field: "Type",
29
+ message: "is Parallel, which does not run here yet; in data order, states that read nothing of each other run at once"
30
+ });
31
+ if (typeof state.Resource === "string" && state.Resource.startsWith("arn:")) found.push({
32
+ state: where,
33
+ field: "Resource",
34
+ message: `is a Step Functions service (${state.Resource}), which does not run here: write the step with one of this app's step types, such as app:http for an HTTP request`
35
+ });
36
+ for (const field of jsonPathFields) if (state[field] !== void 0) found.push({
37
+ state: where,
38
+ field,
39
+ message: "is JSONPath, which does not run here; write the state in JSONata, with Arguments, Output and Assign"
40
+ });
41
+ for (const [field, message] of Object.entries(awsFields)) if (state[field] !== void 0) found.push({
42
+ state: where,
43
+ field,
44
+ message
45
+ });
46
+ const config = isObject(state.ItemProcessor) ? state.ItemProcessor.ProcessorConfig : void 0;
47
+ if (isObject(config) && config.Mode === "DISTRIBUTED") found.push({
48
+ state: where,
49
+ field: "ItemProcessor.ProcessorConfig.Mode",
50
+ message: "is DISTRIBUTED, which does not run here; a Map runs its items inline"
51
+ });
52
+ for (const inner of [
53
+ "ItemProcessor",
54
+ "Processor",
55
+ "Iterator"
56
+ ]) if (isObject(state[inner])) found.push(...stateProblems(state[inner].States, [...path, name]));
57
+ return found;
58
+ });
59
+ };
60
+ /**
61
+ * What a state machine from Step Functions holds that this app does not run, each named: JSONPath (its query
62
+ * language by default), its service tasks, the HTTP task included, Parallel, a distributed Map, heartbeats, credentials and a
63
+ * whole-run timeout. Empty for a machine this app can check further.
64
+ */
65
+ const awsProblems = (definition) => {
66
+ const machine = isObject(definition) && isObject(definition.stateMachine) ? definition.stateMachine : void 0;
67
+ if (!machine) return [];
68
+ const found = [];
69
+ if (machine.QueryLanguage !== "JSONata") found.push({
70
+ field: "stateMachine.QueryLanguage",
71
+ message: `is ${machine.QueryLanguage === void 0 ? "missing, so the machine is JSONPath, the default of Step Functions" : JSON.stringify(machine.QueryLanguage)}; only JSONata machines run here: set "QueryLanguage": "JSONata" and write its states in JSONata`
72
+ });
73
+ if (machine.TimeoutSeconds !== void 0) found.push({
74
+ field: "stateMachine.TimeoutSeconds",
75
+ message: "is a whole run's timeout, which does not run here; give each Task its TimeoutSeconds"
76
+ });
77
+ return [...found, ...stateProblems(machine.States, [])];
78
+ };
79
+ //#endregion
80
+ export { awsProblems };
@@ -1,11 +1,14 @@
1
1
  import { Problem } from "./problem.js";
2
2
  import { TriggerCheck } from "./check-trigger.js";
3
+ import { PinSchemas } from "./pins/pin-sources.js";
3
4
  //#region src/definition/check-definition.d.ts
4
5
  /**
5
6
  * What a definition is checked against beside the language: the step types (Task resources) the app has, the
6
7
  * arguments each needs (`required`, by step type), its trigger types, each with the check of its input, and why the
7
8
  * app cannot run a type it knows (`unavailable`, by step or trigger type), and the connection `<plugin>:<connection>`
8
9
  * each type that signs in uses (`connections`, by step or trigger type); without it the bindings are not checked.
10
+ * With `pins`, the types' input and output schemas and the app's records, an argument that reads a value by name is
11
+ * checked to take that value's type.
9
12
  */
10
13
  export type CheckOptions = {
11
14
  resources: readonly string[];
@@ -13,6 +16,7 @@ export type CheckOptions = {
13
16
  triggers: Readonly<Record<string, TriggerCheck>>;
14
17
  unavailable?: Readonly<Record<string, string>>;
15
18
  connections?: Readonly<Record<string, string>>;
19
+ pins?: PinSchemas;
16
20
  };
17
21
  /**
18
22
  * Why a definition cannot be saved, as it is checked on every save: its size and nesting, its shape against `definitionSchema`, its
@@ -1,3 +1,4 @@
1
+ import { awsProblems } from "./check-aws.js";
1
2
  import { limits } from "../limits.js";
2
3
  import { schemaProblems } from "./check-schema.js";
3
4
  import { triggerProblems } from "./check-trigger.js";
@@ -12,6 +13,9 @@ import { connectionProblems } from "./used-connections.js";
12
13
  import { visibleVariables } from "./visible.js";
13
14
  import { blockProblems } from "./check-block.js";
14
15
  import { nestingDepth } from "../nesting.js";
16
+ import { pinProblems } from "./pins/check-pins.js";
17
+ import { dataflowProblems, dataflowVisible } from "./dataflow/check-dataflow.js";
18
+ import { orderOf } from "./types.js";
15
19
  //#region src/definition/check-definition.ts
16
20
  const missingArguments = (state, options) => {
17
21
  const needed = options.required?.[state.Resource] ?? [];
@@ -24,16 +28,19 @@ const machineProblems = (machine, scope, options) => {
24
28
  const where = (name) => [...scope.path, name].join("/");
25
29
  const prefix = scope.path.length > 0 ? { state: scope.path.join("/") } : {};
26
30
  const names = Object.keys(machine.States);
27
- if (!machine.States[machine.StartAt]) problems.push({
31
+ const { data } = scope;
32
+ const start = machine.StartAt === void 0 ? void 0 : machine.States[machine.StartAt];
33
+ if (!data && !start) problems.push({
28
34
  ...prefix,
29
35
  field: "StartAt",
30
36
  message: `names "${machine.StartAt}", which is not a state here`
31
37
  });
32
- const visible = visibleVariables(machine, scope.outer);
33
- const reached = reachable(machine);
38
+ const visible = data ? dataflowVisible(machine, scope.outer) : visibleVariables(machine, scope.outer);
39
+ const reached = data ? void 0 : reachable(machine);
40
+ const steps = /* @__PURE__ */ new Set([...scope.steps, ...names]);
34
41
  for (const name of names) {
35
42
  const state = machine.States[name];
36
- if (!reached.has(name) && machine.States[machine.StartAt]) problems.push({
43
+ if (reached && !reached.has(name) && start) problems.push({
37
44
  state: where(name),
38
45
  message: `is never reached from "${machine.StartAt}"`
39
46
  });
@@ -69,12 +76,13 @@ const machineProblems = (machine, scope, options) => {
69
76
  field: `Arguments.${missing}`,
70
77
  message: `is missing; ${state.Resource} needs it`
71
78
  });
72
- const firstOfItem = scope.item && name === machine.StartAt;
79
+ const firstOfItem = scope.item && (data || name === machine.StartAt);
73
80
  for (const { field, source, place } of stateExpressions(state)) for (const message of readProblems(source, {
74
81
  place,
75
82
  visible: visible.get(name),
76
83
  firstOfItem,
77
- inBlock: scope.blocks > 0
84
+ inBlock: scope.blocks > 0,
85
+ ...data && { steps }
78
86
  })) problems.push({
79
87
  state: where(name),
80
88
  field,
@@ -84,7 +92,8 @@ const machineProblems = (machine, scope, options) => {
84
92
  ...scope,
85
93
  path: [...scope.path, name],
86
94
  outer: visible.get(name),
87
- item: true
95
+ item: true,
96
+ steps
88
97
  }, options));
89
98
  if (state.Type === "Block") {
90
99
  problems.push(...blockProblems(state, where(name), scope.blocks + 1));
@@ -92,10 +101,13 @@ const machineProblems = (machine, scope, options) => {
92
101
  path: [...scope.path, name],
93
102
  outer: /* @__PURE__ */ new Set(),
94
103
  item: false,
95
- blocks: scope.blocks + 1
104
+ blocks: scope.blocks + 1,
105
+ data,
106
+ steps: /* @__PURE__ */ new Set()
96
107
  }, options));
97
108
  }
98
109
  }
110
+ if (data) problems.push(...dataflowProblems(machine, where));
99
111
  return problems;
100
112
  };
101
113
  const wholeProblems = (definition) => {
@@ -124,6 +136,8 @@ const checkDefinition = (definition, options) => {
124
136
  const bytes = new TextEncoder().encode(JSON.stringify(definition) ?? "").length;
125
137
  if (bytes > limits.definitionBytes) return [{ message: `The definition is ${bytes} bytes as JSON, more than the ${limits.definitionBytes} a workflow may have` }];
126
138
  if (nestingDepth(definition, limits.definitionDepth) > limits.definitionDepth) return [{ message: `The definition nests more than ${limits.definitionDepth} levels of arrays and objects` }];
139
+ const aws = awsProblems(definition);
140
+ if (aws.length > 0) return aws;
127
141
  const shape = schemaProblems(definition);
128
142
  if (shape.length > 0) return shape;
129
143
  const document = definition;
@@ -135,8 +149,11 @@ const checkDefinition = (definition, options) => {
135
149
  path: [],
136
150
  outer: /* @__PURE__ */ new Set(),
137
151
  item: false,
138
- blocks: 0
139
- }, options)
152
+ blocks: 0,
153
+ data: orderOf(document) === "data",
154
+ steps: /* @__PURE__ */ new Set()
155
+ }, options),
156
+ ...options.pins ? pinProblems(document, options.pins) : []
140
157
  ];
141
158
  };
142
159
  //#endregion
@@ -9,11 +9,16 @@ const statesFields = {
9
9
  error: "errorOutput"
10
10
  };
11
11
  const startsWith = (path, prefix) => prefix.every((name, index) => path[index] === name);
12
- const contextProblem = (path) => {
12
+ const contextProblem = (path, steps) => {
13
13
  const rest = path.slice(1);
14
14
  if (startsWith(rest, ["Secrets"])) return rest.length >= 2 ? void 0 : "reads $states.context.Secrets as a whole; read one secret by its name, such as $states.context.Secrets.API_TOKEN";
15
15
  if (contextReads.some((read) => startsWith(rest, read))) return void 0;
16
- return `reads $states.${path.join(".")}; $states.context holds only Execution.Input, Execution.StartTime and Secrets.<NAME>`;
16
+ if (steps && startsWith(rest, ["Steps"])) {
17
+ if (rest[1] === void 0) return "reads $states.context.Steps as a whole; read one state's status by its name, such as $states.context.Steps.Save.Status";
18
+ return steps.has(rest[1]) ? void 0 : `reads $states.context.Steps.${rest[1]}, but there is no state ${rest[1]} here or around it`;
19
+ }
20
+ const held = steps ? "Execution.Input, Execution.StartTime, Secrets.<NAME> and Steps.<state>" : "Execution.Input, Execution.StartTime and Secrets.<NAME>";
21
+ return `reads $states.${path.join(".")}; $states.context holds only ${held}`;
17
22
  };
18
23
  /** The reads of an expression, or undefined when it does not parse. */
19
24
  const expressionParsed = (source) => {
@@ -26,7 +31,7 @@ const expressionParsed = (source) => {
26
31
  * start time and secrets by name (inside a Block, not the start time), and read only variables a state that can run
27
32
  * before it assigns.
28
33
  */
29
- const readProblems = (source, { place, visible, firstOfItem, inBlock = false }) => {
34
+ const readProblems = (source, { place, visible, firstOfItem, inBlock = false, steps }) => {
30
35
  if (source.length > limits.expressionLength) return [`is ${source.length} characters long, more than the ${limits.expressionLength} an expression may be`];
31
36
  const parsed = parse(source);
32
37
  if ("error" in parsed) return [`does not parse: ${parsed.error.message}${parsed.error.position === void 0 ? "" : ` (at character ${parsed.error.position})`}`];
@@ -43,7 +48,7 @@ const readProblems = (source, { place, visible, firstOfItem, inBlock = false })
43
48
  "StartTime"
44
49
  ])) problems.push("reads $states.context.Execution.StartTime, which inside a Block is its own run's start, not part of what it is cached by");
45
50
  else if (field === "context") {
46
- const problem = contextProblem(path);
51
+ const problem = contextProblem(path, steps);
47
52
  if (problem) problems.push(problem);
48
53
  } else if (field === "input") problems.push("reads $states.input, which only the first state of a Map's item processor may read (as the item)");
49
54
  else if (field === "") problems.push("reads $states as a whole; read one of its fields");
@@ -1,12 +1,16 @@
1
- import { definitionSchema } from "./schema.js";
1
+ import { dataflowDefinitionSchema, definitionSchema } from "./schema.js";
2
2
  import { fieldPath } from "./problem.js";
3
3
  import { Ajv } from "ajv";
4
4
  //#region src/definition/check-schema.ts
5
- const validate = new Ajv({
5
+ const ajv = new Ajv({
6
6
  allErrors: true,
7
7
  discriminator: true,
8
8
  strict: false
9
- }).compile(definitionSchema);
9
+ });
10
+ const validators = {
11
+ sequence: ajv.compile(definitionSchema),
12
+ data: ajv.compile(dataflowDefinitionSchema)
13
+ };
10
14
  const located = (pointer) => {
11
15
  const all = pointer.split("/").slice(1).map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
12
16
  const parts = all[0] === "stateMachine" && all[1] === "States" ? all.slice(1) : all;
@@ -25,12 +29,18 @@ const located = (pointer) => {
25
29
  ...field.length > 0 && { field: fieldPath(field) }
26
30
  };
27
31
  };
28
- const message = (error) => {
32
+ const message = (error, data) => {
33
+ if (error.keyword === "additionalProperties" && data && [
34
+ "Next",
35
+ "End",
36
+ "StartAt"
37
+ ].includes(String(error.params.additionalProperty))) return `${error.params.additionalProperty} is not a field in dataflow order, where a state runs once the states it reads from have ended`;
38
+ if (error.keyword === "additionalProperties" && !data && error.params.additionalProperty === "Condition") return "Condition is a field only in dataflow order (\"order\": \"data\"); in sequence order a Choice decides";
29
39
  if (error.keyword === "additionalProperties") return `${error.params.additionalProperty} is not a field here`;
30
40
  if (error.keyword === "required") return `${error.params.missingProperty} is missing`;
31
41
  if (error.keyword === "minItems") return `is missing; it needs at least ${String(error.params.limit)}`;
32
42
  if (error.keyword === "const") return `must be ${JSON.stringify(error.params.allowedValue)}`;
33
- if (error.keyword === "discriminator") return "must be one of Task, Choice, Pass, Map, Block, Wait, Succeed and Fail";
43
+ if (error.keyword === "discriminator") return data ? "must be one of Task, Pass, Map, Block, Wait and Fail; in dataflow order a Condition takes the place of Choice, and the run ends when no state is left to run" : "must be one of Task, Choice, Pass, Map, Block, Wait, Succeed and Fail";
34
44
  if (error.keyword === "pattern" && error.instancePath === "/trigger") return "names a trigger type <plugin>:<key>, such as app:record, or manual";
35
45
  if (error.keyword === "pattern" && error.instancePath.endsWith("/Assign")) return "names a variable with letters, digits and _, starting with a letter";
36
46
  if (error.keyword === "pattern") return "must be an expression written as {% ... %}";
@@ -43,8 +53,10 @@ const choices = {
43
53
  Next: "needs either Next or End",
44
54
  Seconds: "needs either Seconds or Timestamp"
45
55
  };
46
- /** The ways a definition does not fit the schema, each with the state and field it is about. */
56
+ /** The ways a definition does not fit the schema of its order, each with the state and field it is about. */
47
57
  const schemaProblems = (definition) => {
58
+ const data = typeof definition === "object" && definition !== null && definition.order === "data";
59
+ const validate = data ? validators.data : validators.sequence;
48
60
  if (validate(definition)) return [];
49
61
  const problems = [];
50
62
  const seen = /* @__PURE__ */ new Set();
@@ -56,7 +68,7 @@ const schemaProblems = (definition) => {
56
68
  ...located(error.instancePath),
57
69
  ...error.keyword === "discriminator" && { field: "Type" }
58
70
  };
59
- let text = message(error);
71
+ let text = message(error, data);
60
72
  if (error.keyword === "oneOf") {
61
73
  const branch = errors.find((other) => other.instancePath === error.instancePath && other.schemaPath.startsWith(error.schemaPath.replace(/\/oneOf$/, "/oneOf/")) && other.keyword === "required");
62
74
  text = choices[String(branch?.params.missingProperty)] ?? text;
@@ -0,0 +1,36 @@
1
+ import { assignedNames } from "../expression-fields.js";
2
+ import { dependencyCycle, machineDependencies } from "./dependencies.js";
3
+ //#region src/definition/dataflow/check-dataflow.ts
4
+ /**
5
+ * The variables each state of a dataflow machine may read: those of the scopes around it, and each one another state of
6
+ * the machine assigns, which makes that state one it runs after. A state does not read its own.
7
+ */
8
+ const dataflowVisible = (machine, outer) => {
9
+ const all = Object.entries(machine.States).map(([name, state]) => [name, assignedNames(state)]);
10
+ return new Map(all.map(([name, own]) => [name, /* @__PURE__ */ new Set([...outer, ...all.flatMap(([other, names]) => other === name ? [] : names).filter((variable) => !own.includes(variable))])]));
11
+ };
12
+ /**
13
+ * What a dataflow machine needs beside its states' own checks: each variable assigned by one state alone, so a read names
14
+ * the one state it runs after, and no state that runs after itself through the states it reads from.
15
+ */
16
+ const dataflowProblems = (machine, where) => {
17
+ const problems = [];
18
+ const first = /* @__PURE__ */ new Map();
19
+ for (const [name, state] of Object.entries(machine.States)) for (const variable of new Set(assignedNames(state))) {
20
+ const earlier = first.get(variable);
21
+ if (earlier === void 0) first.set(variable, name);
22
+ else problems.push({
23
+ state: where(name),
24
+ field: "Assign",
25
+ message: `assigns $${variable}, which ${earlier} assigns already; in dataflow order each variable has one state that assigns it`
26
+ });
27
+ }
28
+ const cycle = dependencyCycle(machineDependencies(machine));
29
+ if (cycle) problems.push({
30
+ state: where(cycle[0]),
31
+ message: `runs after itself: ${cycle.join(" reads ")}; a state cannot read what runs after it`
32
+ });
33
+ return problems;
34
+ };
35
+ //#endregion
36
+ export { dataflowProblems, dataflowVisible };
@@ -0,0 +1,17 @@
1
+ import { Machine } from "../types.js";
2
+ //#region src/definition/dataflow/dependencies.d.ts
3
+ /**
4
+ * What a state of a dataflow machine runs after: the states whose variables it reads (`data`), and those whose
5
+ * `$states.context.Steps.<name>` it reads (`status`), of which `handled` are those its `Condition` reads, which take
6
+ * the default skip away for them.
7
+ */
8
+ export type Dependencies = {
9
+ data: Set<string>;
10
+ status: Set<string>;
11
+ handled: Set<string>;
12
+ };
13
+ /** Each state's dependencies on the other states of its dataflow machine, by name. Reads of the scopes around it are not among them. */
14
+ export declare const machineDependencies: (machine: Machine) => Map<string, Dependencies>;
15
+ /** Every state a state depends on, data and status alike. */
16
+ export declare const dependsOn: (dependencies: Dependencies) => Set<string>;
17
+ //#endregion
@@ -0,0 +1,88 @@
1
+ import { parse } from "../expressions.js";
2
+ import { assignedNames, stateExpressions } from "../expression-fields.js";
3
+ import { expressionReads } from "../reads.js";
4
+ import { innerMachine } from "../inner.js";
5
+ //#region src/definition/dataflow/dependencies.ts
6
+ const readsOf = (state) => {
7
+ const found = [];
8
+ for (const { field, source } of stateExpressions(state)) {
9
+ const parsed = parse(source);
10
+ if ("error" in parsed) continue;
11
+ const reads = expressionReads(parsed.expression);
12
+ const steps = reads.states.filter((path) => path[0] === "context" && path[1] === "Steps" && path[2] !== void 0).map((path) => path[2]);
13
+ found.push({
14
+ variables: [...reads.variables],
15
+ steps,
16
+ condition: field === "Condition"
17
+ });
18
+ }
19
+ const inner = state.Type === "Map" ? innerMachine(state) : void 0;
20
+ if (inner) {
21
+ const own = new Set(Object.values(inner.States).flatMap(assignedNames));
22
+ const innerNames = new Set(Object.keys(inner.States));
23
+ for (const read of Object.values(inner.States).flatMap(readsOf)) found.push({
24
+ variables: read.variables.filter((name) => !own.has(name)),
25
+ steps: read.steps.filter((name) => !innerNames.has(name)),
26
+ condition: read.condition
27
+ });
28
+ }
29
+ return found;
30
+ };
31
+ /** The state of `machine` that assigns each variable, by the variable; a variable two states assign maps to the first. */
32
+ const assigners = (machine) => {
33
+ const by = /* @__PURE__ */ new Map();
34
+ for (const [name, state] of Object.entries(machine.States)) for (const variable of assignedNames(state)) if (!by.has(variable)) by.set(variable, name);
35
+ return by;
36
+ };
37
+ /** Each state's dependencies on the other states of its dataflow machine, by name. Reads of the scopes around it are not among them. */
38
+ const machineDependencies = (machine) => {
39
+ const by = assigners(machine);
40
+ return new Map(Object.entries(machine.States).map(([name, state]) => {
41
+ const dependencies = {
42
+ data: /* @__PURE__ */ new Set(),
43
+ status: /* @__PURE__ */ new Set(),
44
+ handled: /* @__PURE__ */ new Set()
45
+ };
46
+ for (const read of readsOf(state)) {
47
+ for (const variable of read.variables) {
48
+ const from = by.get(variable);
49
+ if (from !== void 0) dependencies.data.add(from);
50
+ }
51
+ for (const step of read.steps) {
52
+ if (!Object.hasOwn(machine.States, step)) continue;
53
+ dependencies.status.add(step);
54
+ if (read.condition) dependencies.handled.add(step);
55
+ }
56
+ }
57
+ return [name, dependencies];
58
+ }));
59
+ };
60
+ /** Every state a state depends on, data and status alike. */
61
+ const dependsOn = (dependencies) => /* @__PURE__ */ new Set([...dependencies.data, ...dependencies.status]);
62
+ /** A cycle among the dependencies, as the state names around it with the first again at the end; none when there is none. */
63
+ const dependencyCycle = (dependencies) => {
64
+ const state = /* @__PURE__ */ new Map();
65
+ const path = [];
66
+ const visit = (name) => {
67
+ if (state.get(name) === "done") return;
68
+ if (state.get(name) === "open") return [...path.slice(path.indexOf(name)), name];
69
+ state.set(name, "open");
70
+ path.push(name);
71
+ for (const next of dependsOn(dependencies.get(name) ?? {
72
+ data: /* @__PURE__ */ new Set(),
73
+ status: /* @__PURE__ */ new Set(),
74
+ handled: /* @__PURE__ */ new Set()
75
+ })) {
76
+ const found = visit(next);
77
+ if (found) return found;
78
+ }
79
+ path.pop();
80
+ state.set(name, "done");
81
+ };
82
+ for (const name of dependencies.keys()) {
83
+ const found = visit(name);
84
+ if (found) return found;
85
+ }
86
+ };
87
+ //#endregion
88
+ export { assigners, dependencyCycle, dependsOn, machineDependencies };
@@ -0,0 +1,5 @@
1
+ import { State } from "./types.js";
2
+ //#region src/definition/expression-fields.d.ts
3
+ /** The variables a state assigns, in its own Assign, its choice rules' and its catchers'. */
4
+ export declare const assignedNames: (state: State) => string[];
5
+ //#endregion
@@ -12,6 +12,7 @@ const stateExpressions = (state) => {
12
12
  });
13
13
  };
14
14
  const after = state.Type === "Task" || state.Type === "Map" || state.Type === "Block" ? "result" : "state";
15
+ add(state.Condition, ["Condition"], "state");
15
16
  if (state.Type === "Fail") {
16
17
  add(state.Error, ["Error"], "state");
17
18
  add(state.Cause, ["Cause"], "state");
@@ -0,0 +1,5 @@
1
+ import "jsonata";
2
+ //#region src/definition/expressions.d.ts
3
+ /** The JSONata source of a `{% ... %}` string, or `undefined` for any other value. */
4
+ export declare const expressionSource: (value: unknown) => string | undefined;
5
+ //#endregion
@@ -16,7 +16,7 @@ const edges = (state) => {
16
16
  target: state.Default
17
17
  });
18
18
  }
19
- if ("Catch" in state) state.Catch?.forEach((catcher, index) => found.push({
19
+ if ("Catch" in state) state.Catch?.forEach((catcher, index) => catcher.Next !== void 0 && found.push({
20
20
  field: `Catch[${index}].Next`,
21
21
  target: catcher.Next
22
22
  }));
@@ -0,0 +1,21 @@
1
+ import { Definition, Order } from "./types.js";
2
+ //#region src/definition/parts.d.ts
3
+ /**
4
+ * A definition as a workflow and each of its versions keep it, in fields of their own: the state machine, exactly as the
5
+ * States Language writes it, what starts its runs, the order its states run in, the account each of its connections
6
+ * signs in with, and which of its runs keep a trace.
7
+ */
8
+ export type DefinitionParts = {
9
+ state_machine: unknown;
10
+ trigger: unknown;
11
+ execution_order?: Order | null;
12
+ connections?: Record<string, string> | null;
13
+ trace?: Definition['trace'] | null;
14
+ };
15
+ /** The definition its parts make, as the runner and the check read it. */
16
+ export declare const definitionFromParts: (parts: DefinitionParts) => Definition;
17
+ /** A definition's parts, to save as a workflow's fields. */
18
+ export declare const partsOfDefinition: (definition: Definition) => Required<DefinitionParts>;
19
+ /** The field a definition's problem is about: the trigger's, or the state machine's. */
20
+ export declare const partOfProblem: (field: string | undefined) => "trigger" | "execution_order" | "state_machine";
21
+ //#endregion
@@ -0,0 +1,21 @@
1
+ //#region src/definition/parts.ts
2
+ /** The definition its parts make, as the runner and the check read it. */
3
+ const definitionFromParts = (parts) => ({
4
+ trigger: parts.trigger,
5
+ order: parts.execution_order ?? "sequence",
6
+ stateMachine: parts.state_machine,
7
+ ...parts.connections && { connections: parts.connections },
8
+ ...parts.trace && { trace: parts.trace }
9
+ });
10
+ /** A definition's parts, to save as a workflow's fields. */
11
+ const partsOfDefinition = (definition) => ({
12
+ state_machine: definition.stateMachine,
13
+ trigger: definition.trigger,
14
+ execution_order: definition.order ?? "sequence",
15
+ connections: definition.connections ?? null,
16
+ trace: definition.trace ?? null
17
+ });
18
+ /** The field a definition's problem is about: the trigger's, or the state machine's. */
19
+ const partOfProblem = (field) => field?.startsWith("trigger") ? "trigger" : field === "order" ? "execution_order" : "state_machine";
20
+ //#endregion
21
+ export { definitionFromParts, partOfProblem, partsOfDefinition };
@@ -0,0 +1,40 @@
1
+ import { fits, pinType, pinTypeText } from "./pin-type.js";
2
+ import { schemaAt } from "./resolve-schema.js";
3
+ import { argumentsOf, blocksOutsideBlocks, inputSchema, referenceSchema, tasksOutsideBlocks } from "./pin-sources.js";
4
+ import { parseReference, readText } from "./references.js";
5
+ //#region src/definition/pins/check-pins.ts
6
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7
+ /**
8
+ * Where a Task's argument, or a field at any depth of an argument written as an object, is one read by name of a value
9
+ * whose type does not fit what the step type takes there, as a wire between pins of those types is refused: a problem
10
+ * naming both. A read of a value of any type, or into an input of any type, fits.
11
+ */
12
+ const pinProblems = (definition, schemas) => [...tasksOutsideBlocks(definition.stateMachine).flatMap(({ path, state }) => {
13
+ const input = inputSchema(state, schemas);
14
+ if (!input) return [];
15
+ const mismatch = (value, target, field) => {
16
+ const reference = parseReference(value);
17
+ if (!reference || !target) return [];
18
+ const source = pinType(referenceSchema(definition, reference, schemas));
19
+ const taken = pinType(target);
20
+ if (fits(source, taken)) return [];
21
+ return [{
22
+ state: path,
23
+ field: ["Arguments", ...field].join("."),
24
+ message: `reads ${readText(reference)}, ${pinTypeText(source)}, where ${field.join(".")} takes ${pinTypeText(taken)}`
25
+ }];
26
+ };
27
+ const walk = (value, target, field) => isObject(value) ? Object.entries(value).flatMap(([name, inner]) => walk(inner, schemaAt(target, [name]), [...field, name])) : mismatch(value, target, field);
28
+ return Object.entries(argumentsOf(state)).flatMap(([key, value]) => walk(value, schemaAt(input, [key]), [key]));
29
+ }), ...blocksOutsideBlocks(definition.stateMachine).flatMap(({ path, state }) => pinProblems({
30
+ trigger: { manual: {} },
31
+ stateMachine: {
32
+ ...state.Processor,
33
+ QueryLanguage: "JSONata"
34
+ }
35
+ }, schemas).map((problem) => ({
36
+ ...problem,
37
+ ...problem.state !== void 0 && { state: `${path}/${problem.state}` }
38
+ })))];
39
+ //#endregion
40
+ export { pinProblems };
@@ -0,0 +1,33 @@
1
+ import { Definition, Machine, State } from "../types.js";
2
+ import { Reference } from "./references.js";
3
+ import { RecordSchemas } from "./resolve-schema.js";
4
+ //#region src/definition/pins/pin-sources.d.ts
5
+ type JsonSchema = Record<string, unknown>;
6
+ /** What the types of pins are read from: each step type's input and each step and trigger type's output, by id, and the records of the app's resources. */
7
+ export type PinSchemas = {
8
+ inputs: Readonly<Record<string, JsonSchema>>;
9
+ outputs: Readonly<Record<string, JsonSchema>>;
10
+ records: RecordSchemas;
11
+ };
12
+ /** The state outside any Block that keeps its whole result in `variable`, when exactly one does; its name. */
13
+ export declare const resultState: (machine: Machine, variable: string) => [string, State] | undefined;
14
+ /** A Task's result as its type gives it, with what its arguments name filled in; undefined for any other state or an unknown type. */
15
+ export declare const resultSchema: (state: State, schemas: PinSchemas) => {
16
+ [x: string]: unknown;
17
+ } | undefined;
18
+ /** The run's input as the trigger gives it, with what its input names filled in; undefined for a manual workflow. */
19
+ export declare const triggerSchema: (definition: Definition, schemas: PinSchemas) => {
20
+ [x: string]: unknown;
21
+ } | undefined;
22
+ /**
23
+ * The schema of the value a reference reads, in a state outside any Block: the trigger's run input, or the result a
24
+ * state keeps whole in a variable, down the reference's path; undefined when nothing says, so it is of any type.
25
+ */
26
+ /** What `$states.context.Steps.<name>` gives in data order: a state's status, its error and cause. */
27
+ export declare const stepStatusSchema: JsonSchema;
28
+ export declare const referenceSchema: (definition: Definition, reference: Reference, schemas: PinSchemas) => JsonSchema | undefined;
29
+ /** A Task's input as its type takes it, with what its arguments name filled in, such as the record a records step writes. */
30
+ export declare const inputSchema: (state: State, schemas: PinSchemas) => {
31
+ [x: string]: unknown;
32
+ } | undefined;
33
+ //#endregion