@protobase/workflows 0.100.1 → 0.100.3

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.
@@ -14,7 +14,6 @@ const awsFields = {
14
14
  ResultWriter: "is a distributed Map's writer, which does not run here",
15
15
  ToleratedFailureCount: "is a distributed Map's, which does not run here",
16
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
17
  Credentials: "does not run here: a step signs in through the connection its type declares"
19
18
  };
20
19
  const stateProblems = (states, path) => {
@@ -59,8 +58,8 @@ const stateProblems = (states, path) => {
59
58
  };
60
59
  /**
61
60
  * 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.
61
+ * language by default), its service tasks, the HTTP task included, Parallel, a distributed Map, credentials and a whole-run
62
+ * timeout. Empty for a machine this app can check further.
64
63
  */
65
64
  const awsProblems = (definition) => {
66
65
  const machine = isObject(definition) && isObject(definition.stateMachine) ? definition.stateMachine : void 0;
@@ -9,6 +9,7 @@ import { reservedVariables } from "./names.js";
9
9
  import { builtInFunctions } from "./reads.js";
10
10
  import { readProblems } from "./check-reads.js";
11
11
  import { allStates } from "./inner.js";
12
+ import { taskResource } from "./task-resource.js";
12
13
  import { connectionProblems } from "./used-connections.js";
13
14
  import { visibleVariables } from "./visible.js";
14
15
  import { blockProblems } from "./check-block.js";
@@ -18,11 +19,29 @@ import { dataflowProblems, dataflowVisible } from "./dataflow/check-dataflow.js"
18
19
  import { orderOf } from "./types.js";
19
20
  //#region src/definition/check-definition.ts
20
21
  const missingArguments = (state, options) => {
21
- const needed = options.required?.[state.Resource] ?? [];
22
+ const needed = options.required?.[taskResource(state.Resource).type] ?? [];
22
23
  if (expressionSource(state.Arguments) !== void 0) return [];
23
24
  const given = typeof state.Arguments === "object" && state.Arguments !== null ? state.Arguments : {};
24
25
  return needed.filter((name) => given[name] === void 0 || given[name] === "");
25
26
  };
27
+ const waitProblems = (state) => {
28
+ const { waits } = taskResource(state.Resource);
29
+ if (!waits) return [...state.TimeoutSeconds !== void 0 && state.TimeoutSeconds > limits.taskTimeoutSeconds ? [{
30
+ field: "TimeoutSeconds",
31
+ message: `is ${state.TimeoutSeconds}, more than the ${limits.taskTimeoutSeconds} seconds a step type runs; only a Task whose Resource ends in .waitForTaskToken waits longer`
32
+ }] : [], ...state.HeartbeatSeconds !== void 0 ? [{
33
+ field: "HeartbeatSeconds",
34
+ message: "is for a Task whose Resource ends in .waitForTaskToken, whose outside executor sends heartbeats; this step type ends or fails within its TimeoutSeconds"
35
+ }] : []];
36
+ const timeout = state.TimeoutSeconds ?? limits.waitingTaskTimeoutSeconds;
37
+ return [...state.HeartbeatSeconds !== void 0 && state.HeartbeatSeconds >= timeout ? [{
38
+ field: "HeartbeatSeconds",
39
+ message: `is ${state.HeartbeatSeconds}, which must be less than the Task's TimeoutSeconds (${timeout})`
40
+ }] : [], ...state.Cache === true ? [{
41
+ field: "Cache",
42
+ message: "is true, but a Task that waits for an outside result hands its work off on every try and caches nothing"
43
+ }] : []];
44
+ };
26
45
  const machineProblems = (machine, scope, options) => {
27
46
  const problems = [];
28
47
  const where = (name) => [...scope.path, name].join("/");
@@ -61,33 +80,42 @@ const machineProblems = (machine, scope, options) => {
61
80
  message: `cannot assign $${variable}, which an outer state assigns already`
62
81
  });
63
82
  }
64
- if (state.Type === "Task" && options.unavailable && Object.hasOwn(options.unavailable, state.Resource)) problems.push({
83
+ const task = state.Type === "Task" ? taskResource(state.Resource) : void 0;
84
+ if (task && options.unavailable && Object.hasOwn(options.unavailable, task.type)) problems.push({
65
85
  state: where(name),
66
86
  field: "Resource",
67
- message: `"${state.Resource}" cannot run in this app: ${options.unavailable[state.Resource]}`
87
+ message: `"${task.type}" cannot run in this app: ${options.unavailable[task.type]}`
68
88
  });
69
- else if (state.Type === "Task" && !options.resources.includes(state.Resource)) problems.push({
89
+ else if (task && !options.resources.includes(task.type)) problems.push({
70
90
  state: where(name),
71
91
  field: "Resource",
72
- message: `"${state.Resource}" is not a step type; use one of ${options.resources.join(", ")}`
92
+ message: `"${task.type}" is not a step type; use one of ${options.resources.join(", ")}${task.waits ? ", followed by .waitForTaskToken" : ""}`
73
93
  });
74
94
  if (state.Type === "Task") for (const missing of missingArguments(state, options)) problems.push({
75
95
  state: where(name),
76
96
  field: `Arguments.${missing}`,
77
- message: `is missing; ${state.Resource} needs it`
97
+ message: `is missing; ${task.type} needs it`
78
98
  });
79
- const firstOfItem = scope.item && (data || name === machine.StartAt);
80
- for (const { field, source, place } of stateExpressions(state)) for (const message of readProblems(source, {
81
- place,
82
- visible: visible.get(name),
83
- firstOfItem,
84
- inBlock: scope.blocks > 0,
85
- ...data && { steps }
86
- })) problems.push({
99
+ if (state.Type === "Task") for (const problem of waitProblems(state)) problems.push({
87
100
  state: where(name),
88
- field,
89
- message
101
+ ...problem
90
102
  });
103
+ const firstOfItem = scope.item && (data || name === machine.StartAt);
104
+ for (const { field, source, place } of stateExpressions(state)) {
105
+ const token = Boolean(task?.waits) && /^Arguments($|[.[])/.test(field);
106
+ for (const message of readProblems(source, {
107
+ place,
108
+ visible: visible.get(name),
109
+ firstOfItem,
110
+ inBlock: scope.blocks > 0,
111
+ token,
112
+ ...data && { steps }
113
+ })) problems.push({
114
+ state: where(name),
115
+ field,
116
+ message
117
+ });
118
+ }
91
119
  if (state.Type === "Map") problems.push(...machineProblems(state.ItemProcessor, {
92
120
  ...scope,
93
121
  path: [...scope.path, name],
@@ -9,10 +9,14 @@ 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, steps) => {
12
+ const contextProblem = (path, steps, token) => {
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
+ if (startsWith(rest, ["Task"])) {
17
+ if (!token) return "reads $states.context.Task, which only the Arguments of a Task whose Resource ends in .waitForTaskToken read, as $states.context.Task.Token";
18
+ return startsWith(rest, ["Task", "Token"]) && rest.length === 2 ? void 0 : "reads $states.context.Task, whose only field is Token";
19
+ }
16
20
  if (steps && startsWith(rest, ["Steps"])) {
17
21
  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
22
  return steps.has(rest[1]) ? void 0 : `reads $states.context.Steps.${rest[1]}, but there is no state ${rest[1]} here or around it`;
@@ -28,10 +32,10 @@ const expressionParsed = (source) => {
28
32
  /**
29
33
  * Why an expression breaks the named-reads profile, if it does: it must parse, read no implicit input, read
30
34
  * `$states.input` only in the first state of a Map's item processor, read of `$states.context` only the run's input,
31
- * start time and secrets by name (inside a Block, not the start time), and read only variables a state that can run
32
- * before it assigns.
35
+ * start time and secrets by name (inside a Block, not the start time), with `token` a waiting Task's token too, and
36
+ * read only variables a state that can run before it assigns.
33
37
  */
34
- const readProblems = (source, { place, visible, firstOfItem, inBlock = false, steps }) => {
38
+ const readProblems = (source, { place, visible, firstOfItem, inBlock = false, steps, token = false }) => {
35
39
  if (source.length > limits.expressionLength) return [`is ${source.length} characters long, more than the ${limits.expressionLength} an expression may be`];
36
40
  const parsed = parse(source);
37
41
  if ("error" in parsed) return [`does not parse: ${parsed.error.message}${parsed.error.position === void 0 ? "" : ` (at character ${parsed.error.position})`}`];
@@ -48,7 +52,7 @@ const readProblems = (source, { place, visible, firstOfItem, inBlock = false, st
48
52
  "StartTime"
49
53
  ])) 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");
50
54
  else if (field === "context") {
51
- const problem = contextProblem(path, steps);
55
+ const problem = contextProblem(path, steps, token);
52
56
  if (problem) problems.push(problem);
53
57
  } 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)");
54
58
  else if (field === "") problems.push("reads $states as a whole; read one of its fields");
@@ -0,0 +1,12 @@
1
+ //#region src/definition/import/http-connection.d.ts
2
+ /**
3
+ * What an HTTP task's connection sends in this app: a header holding a secret, its whole value, such as `Bearer ...`;
4
+ * null sends nothing in its place.
5
+ */
6
+ export type ConnectionHeader = {
7
+ header: string;
8
+ secret: string;
9
+ } | null;
10
+ /** The header each connection sends, by the connection's ARN, as the import is given them. */
11
+ export type ConnectionHeaders = Record<string, ConnectionHeader>;
12
+ //#endregion
@@ -0,0 +1,84 @@
1
+ import { expressionSource } from "../expressions.js";
2
+ //#region src/definition/import/http-connection.ts
3
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
+ const secretName = /^[A-Za-z_][A-Za-z0-9_]*$/;
5
+ const literalNames = /* @__PURE__ */ new Set([
6
+ "true",
7
+ "false",
8
+ "null"
9
+ ]);
10
+ const headerName = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
11
+ const asked = (arn) => `names a connection, whose credentials this app does not hold: pass connection_headers { ${JSON.stringify(arn)}: { "header": "Authorization", "secret": "<NAME>" } }, the header its credentials go in and a secret workflows.secrets lists that holds the header's whole value, such as "Bearer ...", or null to send none`;
12
+ /**
13
+ * The ARN of the connection an HTTP task's `Authentication` or `InvocationConfig` names, or the problems that keep it
14
+ * from being read: both or neither given, another field beside `ConnectionArn`, or the ARN as an expression.
15
+ */
16
+ const connectionOf = (args, state) => {
17
+ const given = ["Authentication", "InvocationConfig"].filter((field) => args[field] !== void 0);
18
+ if (given.length === 0) return { problems: [] };
19
+ if (given.length > 1) return { problems: [{
20
+ state,
21
+ field: "Arguments.InvocationConfig",
22
+ message: "is given beside Authentication: an HTTP task names one connection"
23
+ }] };
24
+ const field = given[0];
25
+ const connection = args[field];
26
+ if (!isObject(connection)) return { problems: [{
27
+ state,
28
+ field: `Arguments.${field}`,
29
+ message: "is not { \"ConnectionArn\": \"...\" }"
30
+ }] };
31
+ const problems = Object.keys(connection).filter((key) => key !== "ConnectionArn").map((key) => ({
32
+ state,
33
+ field: `Arguments.${field}.${key}`,
34
+ message: "has no counterpart here: an HTTP task imports with its ConnectionArn alone"
35
+ }));
36
+ const arn = connection.ConnectionArn;
37
+ if (typeof arn !== "string" || expressionSource(arn) !== void 0) problems.push({
38
+ state,
39
+ field: `Arguments.${field}.ConnectionArn`,
40
+ message: "is not an ARN written out, which the import needs to know its header"
41
+ });
42
+ if (problems.length > 0) return { problems };
43
+ return {
44
+ arn,
45
+ field: `Arguments.${field}.ConnectionArn`,
46
+ problems: []
47
+ };
48
+ };
49
+ /** The problem with the header given for a connection, if any. */
50
+ const connectionHeaderProblem = (arn, given, state, field) => {
51
+ if (!Object.hasOwn(given, arn)) return {
52
+ state,
53
+ field,
54
+ message: asked(arn)
55
+ };
56
+ const header = given[arn];
57
+ if (header === null) return;
58
+ if (!isObject(header) || typeof header.header !== "string" || !headerName.test(header.header)) return {
59
+ state,
60
+ field,
61
+ message: `has a connection_headers entry whose header is not a header name: ${asked(arn)}`
62
+ };
63
+ if (typeof header.secret !== "string" || !secretName.test(header.secret) || literalNames.has(header.secret)) return {
64
+ state,
65
+ field,
66
+ message: `has a connection_headers entry whose secret is not a secret's name: ${asked(arn)}`
67
+ };
68
+ };
69
+ /**
70
+ * The request's headers with the connection's header added, taking the place of a header of that name in any case,
71
+ * as a connection's header wins in Step Functions; headers written as an expression are merged when the step runs.
72
+ */
73
+ const withConnectionHeader = (headers, { header, secret }) => {
74
+ const value = `{% $states.context.Secrets.${secret} %}`;
75
+ const source = expressionSource(headers);
76
+ if (source !== void 0) return `{% $merge([{}, $sift((${source}), function($value, $name) { $lowercase($name) != ${JSON.stringify(header.toLowerCase())} }), { ${JSON.stringify(header)}: $states.context.Secrets.${secret} }]) %}`;
77
+ const kept = Object.entries(isObject(headers) ? headers : {}).filter(([name]) => name.toLowerCase() !== header.toLowerCase());
78
+ return {
79
+ ...Object.fromEntries(kept),
80
+ [header]: value
81
+ };
82
+ };
83
+ //#endregion
84
+ export { connectionHeaderProblem, connectionOf, withConnectionHeader };
@@ -0,0 +1,130 @@
1
+ import { fieldPath } from "../problem.js";
2
+ import { expressionSource } from "../expressions.js";
3
+ import { connectionHeaderProblem, connectionOf, withConnectionHeader } from "./http-connection.js";
4
+ import { httpTaskResult, templateWithHttpTaskResult } from "./result-shape.js";
5
+ //#region src/definition/import/http-task.ts
6
+ /** The resource of the Step Functions HTTP task. */
7
+ const httpTaskResource = "arn:aws:states:::http:invoke";
8
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9
+ const argumentNames = {
10
+ ApiEndpoint: "url",
11
+ Method: "method",
12
+ Headers: "headers",
13
+ QueryParameters: "query",
14
+ RequestBody: "body"
15
+ };
16
+ const connectionFields = ["Authentication", "InvocationConfig"];
17
+ const unsentMethods = ["HEAD", "OPTIONS"];
18
+ const unreachedRead = "reads the HTTP task's result as a whole or in a form the import does not rewrite, such as $states . result: read its fields as $states.result.ResponseBody, $states.result.StatusCode, $states.result.StatusText and $states.result.Headers, or the result as $states.result";
19
+ const otherArgument = (key) => key === "Transform" ? "encodes the body as a form, which app:http does not do; send the body as text with a Content-Type header instead" : "is not an argument of the HTTP task this app imports";
20
+ const textRecordProblems = (value, state, field) => {
21
+ if (value === void 0 || expressionSource(value) !== void 0) return [];
22
+ if (!isObject(value)) return [{
23
+ state,
24
+ field,
25
+ message: "is not an object: app:http takes an object of text values"
26
+ }];
27
+ return Object.entries(value).filter(([, item]) => Array.isArray(item) || isObject(item)).map(([name]) => ({
28
+ state,
29
+ field: `${field}.${name}`,
30
+ message: "holds a list or an object: app:http sends one text value per name"
31
+ }));
32
+ };
33
+ const methodProblems = (args, state) => {
34
+ const method = args.Method;
35
+ if (typeof method !== "string" || expressionSource(method) !== void 0) return [];
36
+ const upper = method.toUpperCase();
37
+ if (unsentMethods.includes(upper)) return [{
38
+ state,
39
+ field: "Arguments.Method",
40
+ message: `is ${upper}, which app:http does not send: it sends GET, POST, PUT, PATCH and DELETE`
41
+ }];
42
+ if (upper === "GET" && args.RequestBody !== void 0) return [{
43
+ state,
44
+ field: "Arguments.RequestBody",
45
+ message: "is given with GET, which app:http sends without a body: send it with POST, PUT or PATCH"
46
+ }];
47
+ return [];
48
+ };
49
+ const errorProblem = (name) => {
50
+ if (name.startsWith("States.Http.StatusCode.")) return "is a single status, which app:http does not tell apart: it fails with Http.Status for every status outside 2xx";
51
+ if (name === "States.Http.Socket") return "is the HTTP task's timeout, which app:http does not fail with: it fails with Http.Network when no answer comes, and States.Timeout after the Task's TimeoutSeconds";
52
+ if (name === "States.TaskFailed") return "here matches only an error a step type does not name, never app:http's own: name Http.Status, Http.Network and the others list_workflow_types gives, or States.ALL";
53
+ if (name.startsWith("States.Http.") || name.startsWith("Events.ConnectionResource.")) return "is an error of the HTTP task or its connection, which app:http does not fail with";
54
+ };
55
+ const errorsProblems = (state, where) => ["Retry", "Catch"].flatMap((field) => (Array.isArray(state[field]) ? state[field] : []).flatMap((rule, index) => {
56
+ return (isObject(rule) && Array.isArray(rule.ErrorEquals) ? rule.ErrorEquals : []).flatMap((name, at) => {
57
+ const message = typeof name === "string" ? errorProblem(name) : void 0;
58
+ return message ? [{
59
+ state: where,
60
+ field: `${field}[${index}].ErrorEquals[${at}]`,
61
+ message: `is ${name}, which ${message}`
62
+ }] : [];
63
+ });
64
+ }));
65
+ const httpArguments = (args, header) => {
66
+ const mapped = Object.fromEntries(Object.entries(argumentNames).filter(([from]) => args[from] !== void 0).map(([from, to]) => [to, args[from]]));
67
+ if (args.RequestBody !== void 0) mapped.body_encoding = "json";
68
+ if (header) mapped.headers = withConnectionHeader(mapped.headers, header);
69
+ return mapped;
70
+ };
71
+ /**
72
+ * An HTTP task in JSONata as an app:http step that sends the same request and gives the same result, or the problems
73
+ * that keep it from doing so exactly, each by name: its arguments, method, connection and errors. Its `Output` and
74
+ * `Assign` read the HTTP task's result, `{ StatusCode, StatusText, Headers, ResponseBody }`, and without an `Output` it
75
+ * gives that, so later states read what they read in Step Functions.
76
+ */
77
+ const importHttpTask = (state, where, connections) => {
78
+ const args = state.Arguments;
79
+ if (!isObject(args)) return {
80
+ state,
81
+ problems: [{
82
+ state: where,
83
+ field: "Arguments",
84
+ message: args === void 0 ? "is missing: an HTTP task gives at least its ApiEndpoint and Method" : "is one expression, whose fields the import cannot tell apart: write ApiEndpoint, Method, Headers, QueryParameters and RequestBody each as a field of Arguments"
85
+ }]
86
+ };
87
+ const connection = connectionOf(args, where);
88
+ const problems = [
89
+ ...Object.keys(args).filter((key) => !Object.hasOwn(argumentNames, key) && !connectionFields.includes(key)).map((key) => ({
90
+ state: where,
91
+ field: `Arguments.${key}`,
92
+ message: otherArgument(key)
93
+ })),
94
+ ...methodProblems(args, where),
95
+ ...textRecordProblems(args.Headers, where, "Arguments.Headers"),
96
+ ...textRecordProblems(args.QueryParameters, where, "Arguments.QueryParameters"),
97
+ ...connection.problems,
98
+ ...errorsProblems(state, where)
99
+ ];
100
+ const headerProblem = connection.arn !== void 0 ? connectionHeaderProblem(connection.arn, connections, where, connection.field) : void 0;
101
+ if (headerProblem) problems.push(headerProblem);
102
+ const output = state.Output === void 0 ? {
103
+ value: `{% ${httpTaskResult} %}`,
104
+ unreached: []
105
+ } : templateWithHttpTaskResult(state.Output, ["Output"]);
106
+ const assign = state.Assign === void 0 ? void 0 : templateWithHttpTaskResult(state.Assign, ["Assign"]);
107
+ for (const path of [...output.unreached, ...assign?.unreached ?? []]) problems.push({
108
+ state: where,
109
+ field: fieldPath(path),
110
+ message: unreachedRead
111
+ });
112
+ if (problems.length > 0) return {
113
+ state,
114
+ problems
115
+ };
116
+ const header = connection.arn !== void 0 ? connections[connection.arn] : null;
117
+ const imported = {
118
+ ...state,
119
+ Resource: "app:http",
120
+ Arguments: httpArguments(args, header),
121
+ Output: output.value
122
+ };
123
+ if (assign) imported.Assign = assign.value;
124
+ return {
125
+ state: imported,
126
+ problems: []
127
+ };
128
+ };
129
+ //#endregion
130
+ export { httpTaskResource, importHttpTask };
@@ -0,0 +1,13 @@
1
+ import { Problem } from "../problem.js";
2
+ import { ConnectionHeaders } from "./http-connection.js";
3
+ //#region src/definition/import/import-machine.d.ts
4
+ /**
5
+ * A state machine exported from Step Functions with each of its HTTP tasks, in Maps and Blocks too, as an app:http step
6
+ * (see `importHttpTask`), each connection sending the header `connections` gives for it; every other state as it is.
7
+ * With problems, nothing should be saved: each names the state and field that does not import exactly.
8
+ */
9
+ export declare const importStateMachine: (machine: Record<string, unknown>, connections?: ConnectionHeaders) => {
10
+ stateMachine: Record<string, unknown>;
11
+ problems: Problem[];
12
+ };
13
+ //#endregion
@@ -0,0 +1,58 @@
1
+ import { importHttpTask } from "./http-task.js";
2
+ //#region src/definition/import/import-machine.ts
3
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4
+ const innerFields = [
5
+ "ItemProcessor",
6
+ "Iterator",
7
+ "Processor"
8
+ ];
9
+ const importStates = (states, path, connections) => {
10
+ if (!isObject(states)) return {
11
+ states,
12
+ problems: []
13
+ };
14
+ const problems = [];
15
+ return {
16
+ states: Object.fromEntries(Object.entries(states).map(([name, state]) => {
17
+ if (!isObject(state)) return [name, state];
18
+ let next = state;
19
+ if (state.Type === "Task" && state.Resource === "arn:aws:states:::http:invoke" && state.Parameters === void 0) {
20
+ const result = importHttpTask(state, [...path, name].join("/"), connections);
21
+ problems.push(...result.problems);
22
+ next = result.state;
23
+ }
24
+ for (const field of innerFields) {
25
+ const inner = next[field];
26
+ if (!isObject(inner)) continue;
27
+ const result = importStates(inner.States, [...path, name], connections);
28
+ problems.push(...result.problems);
29
+ next = {
30
+ ...next,
31
+ [field]: {
32
+ ...inner,
33
+ States: result.states
34
+ }
35
+ };
36
+ }
37
+ return [name, next];
38
+ })),
39
+ problems
40
+ };
41
+ };
42
+ /**
43
+ * A state machine exported from Step Functions with each of its HTTP tasks, in Maps and Blocks too, as an app:http step
44
+ * (see `importHttpTask`), each connection sending the header `connections` gives for it; every other state as it is.
45
+ * With problems, nothing should be saved: each names the state and field that does not import exactly.
46
+ */
47
+ const importStateMachine = (machine, connections = {}) => {
48
+ const { states, problems } = importStates(machine.States, [], connections);
49
+ return {
50
+ stateMachine: machine.States === void 0 ? machine : {
51
+ ...machine,
52
+ States: states
53
+ },
54
+ problems
55
+ };
56
+ };
57
+ //#endregion
58
+ export { importStateMachine };
@@ -0,0 +1,113 @@
1
+ import { expressionSource, parse } from "../expressions.js";
2
+ import { expressionReads } from "../reads.js";
3
+ //#region src/definition/import/result-shape.ts
4
+ /**
5
+ * The HTTP task's result, `{ StatusCode, StatusText, Headers, ResponseBody }` with each header's values as a list, as
6
+ * JSONata built from app:http's `{ status, status_text, headers, body }`.
7
+ */
8
+ const httpTaskResult = "({ \"StatusCode\": $states.result.status, \"StatusText\": $states.result.status_text, \"Headers\": $merge([{}, $each($states.result.headers, function($value, $name) { { $name: [$value] } })]), \"ResponseBody\": $states.result.body })";
9
+ const readsPerResult = 4;
10
+ const read = "$states.result";
11
+ const nameCharacter = /[\w$]/;
12
+ const operandEnd = /[\w$)\]}"'`]/;
13
+ const closing = (source, start) => {
14
+ const quote = source[start];
15
+ for (let at = start + 1; at < source.length; at++) if (source[at] === "\\") at++;
16
+ else if (source[at] === quote) return at + 1;
17
+ return source.length;
18
+ };
19
+ const lastSignificant = (text) => text.trimEnd().at(-1) ?? "";
20
+ const replaced = (source) => {
21
+ let rewritten = "";
22
+ let count = 0;
23
+ let at = 0;
24
+ while (at < source.length) {
25
+ const character = source[at];
26
+ const regex = character === "/" && source[at + 1] !== "*" && !operandEnd.test(lastSignificant(rewritten));
27
+ if (character === "\"" || character === "'" || character === "`" || regex) {
28
+ const end = closing(source, at);
29
+ rewritten += source.slice(at, end);
30
+ at = end;
31
+ continue;
32
+ }
33
+ if (source.startsWith("/*", at)) {
34
+ const end = source.indexOf("*/", at + 2);
35
+ const stop = end === -1 ? source.length : end + 2;
36
+ rewritten += source.slice(at, stop);
37
+ at = stop;
38
+ continue;
39
+ }
40
+ if (source.startsWith(read, at) && !nameCharacter.test(source[at + 14] ?? "") && !nameCharacter.test(source[at - 1] ?? "")) {
41
+ rewritten += httpTaskResult;
42
+ count++;
43
+ at += 14;
44
+ continue;
45
+ }
46
+ rewritten += character;
47
+ at++;
48
+ }
49
+ return {
50
+ rewritten,
51
+ count
52
+ };
53
+ };
54
+ const resultReads = (source) => {
55
+ const parsed = parse(source);
56
+ if ("error" in parsed) return;
57
+ const states = expressionReads(parsed.expression).states;
58
+ return {
59
+ count: states.filter((path) => path[0] === "result").length,
60
+ whole: states.some((path) => path.length === 0)
61
+ };
62
+ };
63
+ /**
64
+ * The expression with each read of `$states.result` reading the HTTP task's result, so `$states.result.ResponseBody`
65
+ * reads the body and a variable given the whole result keeps the HTTP task's shape; `undefined` when a read is written
66
+ * in a form the rewrite does not reach, such as `$states . result`, which the syntax tree tells. An expression that does
67
+ * not parse is left as it is, for the check to refuse.
68
+ */
69
+ const withHttpTaskResult = (source) => {
70
+ const before = resultReads(source);
71
+ if (!before) return source;
72
+ const { rewritten, count } = replaced(source);
73
+ const after = resultReads(rewritten);
74
+ if (before.whole || before.count !== count || after?.count !== count * readsPerResult) return;
75
+ return rewritten;
76
+ };
77
+ /**
78
+ * A template, such as an `Output` or an `Assign`, with every expression in it reading the HTTP task's result, and the
79
+ * path of each expression whose reads the rewrite does not reach.
80
+ */
81
+ const templateWithHttpTaskResult = (value, path = []) => {
82
+ const source = expressionSource(value);
83
+ if (source !== void 0) {
84
+ const rewritten = withHttpTaskResult(source);
85
+ return rewritten === void 0 ? {
86
+ value,
87
+ unreached: [path]
88
+ } : {
89
+ value: `{%${rewritten}%}`,
90
+ unreached: []
91
+ };
92
+ }
93
+ if (Array.isArray(value)) {
94
+ const items = value.map((item, index) => templateWithHttpTaskResult(item, [...path, index]));
95
+ return {
96
+ value: items.map((item) => item.value),
97
+ unreached: items.flatMap((item) => item.unreached)
98
+ };
99
+ }
100
+ if (typeof value === "object" && value !== null) {
101
+ const entries = Object.entries(value).map(([key, item]) => [key, templateWithHttpTaskResult(item, [...path, key])]);
102
+ return {
103
+ value: Object.fromEntries(entries.map(([key, item]) => [key, item.value])),
104
+ unreached: entries.flatMap(([, item]) => item.unreached)
105
+ };
106
+ }
107
+ return {
108
+ value,
109
+ unreached: []
110
+ };
111
+ };
112
+ //#endregion
113
+ export { httpTaskResult, templateWithHttpTaskResult, withHttpTaskResult };
@@ -11,7 +11,10 @@ export type PinSchemas = {
11
11
  };
12
12
  /** The state outside any Block that keeps its whole result in `variable`, when exactly one does; its name. */
13
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. */
14
+ /**
15
+ * A Task's result as its type gives it, with what its arguments name filled in; undefined for any other state, an
16
+ * unknown type, or a Task that waits for an outside result, which is what its executor sends back.
17
+ */
15
18
  export declare const resultSchema: (state: State, schemas: PinSchemas) => {
16
19
  [x: string]: unknown;
17
20
  } | undefined;
@@ -1,5 +1,6 @@
1
1
  import { expressionSource } from "../expressions.js";
2
2
  import { innerMachine } from "../inner.js";
3
+ import { taskResource } from "../task-resource.js";
3
4
  import { resolveSchema, schemaAt } from "./resolve-schema.js";
4
5
  //#region src/definition/pins/pin-sources.ts
5
6
  const argumentsOf = (state) => {
@@ -19,8 +20,15 @@ const resultState = (machine, variable) => {
19
20
  const [name, state] = keeping[0];
20
21
  return expressionSource(state.Assign[variable])?.trim() === "$states.result" ? [name, state] : void 0;
21
22
  };
22
- /** 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. */
23
- const resultSchema = (state, schemas) => state.Type === "Task" && schemas.outputs[state.Resource] ? resolveSchema(schemas.outputs[state.Resource], argumentsOf(state), schemas.records) : void 0;
23
+ /**
24
+ * A Task's result as its type gives it, with what its arguments name filled in; undefined for any other state, an
25
+ * unknown type, or a Task that waits for an outside result, which is what its executor sends back.
26
+ */
27
+ const resultSchema = (state, schemas) => {
28
+ if (state.Type !== "Task") return;
29
+ const { type, waits } = taskResource(state.Resource);
30
+ return !waits && schemas.outputs[type] ? resolveSchema(schemas.outputs[type], argumentsOf(state), schemas.records) : void 0;
31
+ };
24
32
  /** The run's input as the trigger gives it, with what its input names filled in; undefined for a manual workflow. */
25
33
  const triggerSchema = (definition, schemas) => {
26
34
  const [id, input] = Object.entries(definition.trigger ?? {})[0] ?? [];
@@ -55,7 +63,11 @@ const referenceSchema = (definition, reference, schemas) => {
55
63
  return found && schemaAt(resultSchema(found[1], schemas), path);
56
64
  };
57
65
  /** A Task's input as its type takes it, with what its arguments name filled in, such as the record a records step writes. */
58
- const inputSchema = (state, schemas) => state.Type === "Task" && schemas.inputs[state.Resource] ? resolveSchema(schemas.inputs[state.Resource], argumentsOf(state), schemas.records) : void 0;
66
+ const inputSchema = (state, schemas) => {
67
+ if (state.Type !== "Task") return;
68
+ const { type } = taskResource(state.Resource);
69
+ return schemas.inputs[type] ? resolveSchema(schemas.inputs[type], argumentsOf(state), schemas.records) : void 0;
70
+ };
59
71
  /** Every Task of a machine outside any Block, with its path, the ones in Maps too: a Block's steps read only its own input. */
60
72
  /** Every Block of a machine outside any other Block, with its path, the ones in Maps too. */
61
73
  const blocksOutsideBlocks = (machine, scope = []) => Object.entries(machine.States).flatMap(([name, state]) => {
@@ -151,7 +151,12 @@ const schemaFor = (order) => {
151
151
  TimeoutSeconds: {
152
152
  type: "integer",
153
153
  minimum: 1,
154
- maximum: limits.taskTimeoutSeconds
154
+ maximum: limits.waitingTaskTimeoutSeconds
155
+ },
156
+ HeartbeatSeconds: {
157
+ type: "integer",
158
+ minimum: 1,
159
+ maximum: limits.waitingTaskTimeoutSeconds
155
160
  },
156
161
  Cache: { type: "boolean" }
157
162
  }, {
@@ -0,0 +1,16 @@
1
+ import { State } from "./types.js";
2
+ //#region src/definition/task-resource.d.ts
3
+ /**
4
+ * The States Language's suffix for a Task that hands its work off and waits for an outside result: its step type gets
5
+ * the try's token as `$states.context.Task.Token`, and the Task ends when someone sends that token back with a result
6
+ * or a failure, or when its `TimeoutSeconds` or `HeartbeatSeconds` pass.
7
+ */
8
+ export declare const waitSuffix = ".waitForTaskToken";
9
+ /** A Task's step type, and whether it waits for an outside result once that type handed the work off. */
10
+ export declare const taskResource: (resource: string) => {
11
+ type: string;
12
+ waits: boolean;
13
+ };
14
+ /** Whether a state is a Task that waits for an outside result. */
15
+ export declare const waitsForToken: (state: State) => boolean;
16
+ //#endregion