@abyss-project/runtime 3.8.0 → 3.10.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 (55) hide show
  1. package/.eslintrc.js +32 -32
  2. package/dist/cost/execution-cost.d.ts +6 -0
  3. package/dist/cost/execution-cost.js +27 -12
  4. package/dist/cost/execution-cost.js.map +1 -1
  5. package/dist/discord/discord.types.d.ts +44 -2
  6. package/dist/discord/discord.types.js +12 -1
  7. package/dist/discord/discord.types.js.map +1 -1
  8. package/dist/engine/engine-source.js +1 -1
  9. package/dist/runner-protocol/execution-protocol.types.d.ts +3 -0
  10. package/dist/runner-protocol/execution-protocol.types.js +5 -1
  11. package/dist/runner-protocol/execution-protocol.types.js.map +1 -1
  12. package/jest.config.ts +11 -11
  13. package/package.json +1 -1
  14. package/scripts/build-engine.cjs +70 -70
  15. package/src/__tests__/engine-bundle.test.ts +121 -121
  16. package/src/access/__tests__/host-match.test.ts +24 -24
  17. package/src/access/access.types.ts +25 -25
  18. package/src/access/host-match.ts +13 -13
  19. package/src/cost/__tests__/execution-cost.test.ts +249 -196
  20. package/src/cost/execution-cost.ts +203 -186
  21. package/src/definition/__tests__/validate-definition.test.ts +354 -354
  22. package/src/definition/definition.limits.ts +9 -9
  23. package/src/definition/definition.schema.ts +172 -172
  24. package/src/definition/definition.types.ts +171 -171
  25. package/src/definition/validate-definition.ts +206 -206
  26. package/src/definition/walk-steps.ts +44 -44
  27. package/src/discord/__tests__/discord-event-input.test.ts +90 -89
  28. package/src/discord/discord.types.ts +56 -1
  29. package/src/engine/engine-entry.ts +3 -3
  30. package/src/engine/engine-global.ts +2 -2
  31. package/src/errors/runtime-error-code.enum.ts +37 -37
  32. package/src/index.ts +32 -32
  33. package/src/interpreter/__tests__/interpreter.test.ts +854 -854
  34. package/src/interpreter/__tests__/log-respond-resume.test.ts +271 -271
  35. package/src/interpreter/interpreter-error.ts +12 -12
  36. package/src/interpreter/interpreter.ts +483 -483
  37. package/src/interpreter/interpreter.types.ts +204 -204
  38. package/src/interpreter/sequence-path.ts +67 -67
  39. package/src/interpreter/test-host.ts +85 -85
  40. package/src/runner-protocol/__tests__/file-payload.test.ts +26 -0
  41. package/src/runner-protocol/evaluation.types.ts +21 -21
  42. package/src/runner-protocol/execution-protocol.types.ts +20 -0
  43. package/src/schedule/schedule.types.ts +100 -100
  44. package/src/server/__tests__/code-runner-session.test.ts +311 -311
  45. package/src/server/code-runner-error.ts +12 -12
  46. package/src/server/code-runner-session.ts +310 -310
  47. package/src/server/index.ts +11 -11
  48. package/src/steps/__tests__/global-references.test.ts +133 -133
  49. package/src/steps/execute-step.ts +186 -186
  50. package/src/steps/global-references.ts +48 -48
  51. package/src/steps/step-access.ts +56 -56
  52. package/src/steps/step-fields.ts +87 -87
  53. package/src/steps/value-source.ts +69 -69
  54. package/tsconfig.check.json +15 -15
  55. package/tsconfig.json +35 -35
@@ -1,133 +1,133 @@
1
- import { CURRENT_FORMAT_VERSION, HttpMethod, StepType } from '../../definition/definition.types';
2
- import type { RuntimeDefinition, Step } from '../../definition/definition.types';
3
- import { collectGlobalReferences } from '../global-references';
4
-
5
- const definitionOf = (steps: Step[]): RuntimeDefinition => ({
6
- formatVersion: CURRENT_FORMAT_VERSION,
7
- accesses: [],
8
- steps,
9
- });
10
-
11
- describe('collectGlobalReferences', () => {
12
- it('finds a reference in a template placeholder, an expression and a CODE source', () => {
13
- const definition = definitionOf([
14
- {
15
- id: 'call',
16
- type: StepType.HTTP,
17
- method: HttpMethod.GET,
18
- url: 'https://api.example.com/{{ input.id }}',
19
- headers: { Authorization: 'Bearer {{ secrets.API_KEY }}' },
20
- body: { $expression: 'secrets.BODY_KEY + "x"' },
21
- },
22
- { id: 'code', type: StepType.CODE, source: 'const t = secrets.CODE_KEY; return t;' },
23
- ]);
24
- expect(collectGlobalReferences(definition, 'secrets')).toEqual([
25
- 'API_KEY',
26
- 'BODY_KEY',
27
- 'CODE_KEY',
28
- ]);
29
- });
30
-
31
- it('reads the references of the branches of CONDITION and SWITCH steps', () => {
32
- const definition = definitionOf([
33
- {
34
- id: 'cond',
35
- type: StepType.CONDITION,
36
- if: { $expression: 'true' },
37
- then: [{ id: 'a', type: StepType.SET, variable: 'a', value: '{{ secrets.THEN }}' }],
38
- else: [{ id: 'b', type: StepType.SET, variable: 'b', value: '{{ secrets.ELSE }}' }],
39
- },
40
- {
41
- id: 'sw',
42
- type: StepType.SWITCH,
43
- value: { $expression: 'input.kind' },
44
- cases: [
45
- {
46
- match: 'x',
47
- steps: [
48
- {
49
- id: 'deep',
50
- type: StepType.CONDITION,
51
- if: { $expression: 'secrets.CASE_CONDITION === "1"' },
52
- then: [],
53
- },
54
- ],
55
- },
56
- ],
57
- default: [{ id: 'c', type: StepType.SET, variable: 'c', value: '{{ secrets.DEFAULT }}' }],
58
- },
59
- ]);
60
- expect(collectGlobalReferences(definition, 'secrets')).toEqual([
61
- 'THEN',
62
- 'ELSE',
63
- 'CASE_CONDITION',
64
- 'DEFAULT',
65
- ]);
66
- });
67
-
68
- it('reads the bracket form with either quote, and the optional chain', () => {
69
- const definition = definitionOf([
70
- {
71
- id: 'code',
72
- type: StepType.CODE,
73
- source: `return [secrets['A'], secrets["B"], secrets [ 'C' ], secrets?.D];`,
74
- },
75
- ]);
76
- expect(collectGlobalReferences(definition, 'secrets')).toEqual(['A', 'B', 'C', 'D']);
77
- });
78
-
79
- it('lists a name once, in order of first appearance', () => {
80
- const definition = definitionOf([
81
- { id: 'one', type: StepType.SET, variable: 'x', value: '{{ secrets.B }}-{{ secrets.A }}' },
82
- {
83
- id: 'two',
84
- type: StepType.SET,
85
- variable: 'y',
86
- value: { $expression: 'secrets.B + secrets["A"]' },
87
- },
88
- ]);
89
- expect(collectGlobalReferences(definition, 'secrets')).toEqual(['B', 'A']);
90
- });
91
-
92
- it('ignores dynamic access, other globals, member chains and text outside placeholders', () => {
93
- const definition = definitionOf([
94
- {
95
- id: 'code',
96
- type: StepType.CODE,
97
- source: 'const n = "K"; return [secrets[n], other.secrets.X, mysecrets.Y, secrets];',
98
- },
99
- { id: 'text', type: StepType.SET, variable: 't', value: 'secrets.OUTSIDE {{ input.x }}' },
100
- { id: 'literal', type: StepType.SET, variable: 'l', value: 'secrets.LITERAL' },
101
- ]);
102
- expect(collectGlobalReferences(definition, 'secrets')).toEqual([]);
103
- });
104
-
105
- it('finds the config variables in fields, expressions and code, apart from the secrets', () => {
106
- const definition = definitionOf([
107
- {
108
- id: 'http',
109
- type: StepType.SET,
110
- variable: 'u',
111
- value: 'https://{{ config.HOST }}/x?k={{ secrets.KEY }}',
112
- },
113
- { id: 'expr', type: StepType.SET, variable: 'e', value: { $expression: 'config.MODE + 1' } },
114
- { id: 'code', type: StepType.CODE, source: 'return [config["REGION"], config?.TIER];' },
115
- ]);
116
- expect(collectGlobalReferences(definition, 'config')).toEqual([
117
- 'HOST',
118
- 'MODE',
119
- 'REGION',
120
- 'TIER',
121
- ]);
122
- expect(collectGlobalReferences(definition, 'secrets')).toEqual(['KEY']);
123
- });
124
-
125
- it('works for any global name, and escapes it', () => {
126
- const definition = definitionOf([
127
- { id: 'a', type: StepType.SET, variable: 'a', value: '{{ workflow.project + secrets.S }}' },
128
- ]);
129
- expect(collectGlobalReferences(definition, 'workflow')).toEqual(['project']);
130
- expect(collectGlobalReferences(definition, 'work.low')).toEqual([]);
131
- expect(collectGlobalReferences(definition, '$')).toEqual([]);
132
- });
133
- });
1
+ import { CURRENT_FORMAT_VERSION, HttpMethod, StepType } from '../../definition/definition.types';
2
+ import type { RuntimeDefinition, Step } from '../../definition/definition.types';
3
+ import { collectGlobalReferences } from '../global-references';
4
+
5
+ const definitionOf = (steps: Step[]): RuntimeDefinition => ({
6
+ formatVersion: CURRENT_FORMAT_VERSION,
7
+ accesses: [],
8
+ steps,
9
+ });
10
+
11
+ describe('collectGlobalReferences', () => {
12
+ it('finds a reference in a template placeholder, an expression and a CODE source', () => {
13
+ const definition = definitionOf([
14
+ {
15
+ id: 'call',
16
+ type: StepType.HTTP,
17
+ method: HttpMethod.GET,
18
+ url: 'https://api.example.com/{{ input.id }}',
19
+ headers: { Authorization: 'Bearer {{ secrets.API_KEY }}' },
20
+ body: { $expression: 'secrets.BODY_KEY + "x"' },
21
+ },
22
+ { id: 'code', type: StepType.CODE, source: 'const t = secrets.CODE_KEY; return t;' },
23
+ ]);
24
+ expect(collectGlobalReferences(definition, 'secrets')).toEqual([
25
+ 'API_KEY',
26
+ 'BODY_KEY',
27
+ 'CODE_KEY',
28
+ ]);
29
+ });
30
+
31
+ it('reads the references of the branches of CONDITION and SWITCH steps', () => {
32
+ const definition = definitionOf([
33
+ {
34
+ id: 'cond',
35
+ type: StepType.CONDITION,
36
+ if: { $expression: 'true' },
37
+ then: [{ id: 'a', type: StepType.SET, variable: 'a', value: '{{ secrets.THEN }}' }],
38
+ else: [{ id: 'b', type: StepType.SET, variable: 'b', value: '{{ secrets.ELSE }}' }],
39
+ },
40
+ {
41
+ id: 'sw',
42
+ type: StepType.SWITCH,
43
+ value: { $expression: 'input.kind' },
44
+ cases: [
45
+ {
46
+ match: 'x',
47
+ steps: [
48
+ {
49
+ id: 'deep',
50
+ type: StepType.CONDITION,
51
+ if: { $expression: 'secrets.CASE_CONDITION === "1"' },
52
+ then: [],
53
+ },
54
+ ],
55
+ },
56
+ ],
57
+ default: [{ id: 'c', type: StepType.SET, variable: 'c', value: '{{ secrets.DEFAULT }}' }],
58
+ },
59
+ ]);
60
+ expect(collectGlobalReferences(definition, 'secrets')).toEqual([
61
+ 'THEN',
62
+ 'ELSE',
63
+ 'CASE_CONDITION',
64
+ 'DEFAULT',
65
+ ]);
66
+ });
67
+
68
+ it('reads the bracket form with either quote, and the optional chain', () => {
69
+ const definition = definitionOf([
70
+ {
71
+ id: 'code',
72
+ type: StepType.CODE,
73
+ source: `return [secrets['A'], secrets["B"], secrets [ 'C' ], secrets?.D];`,
74
+ },
75
+ ]);
76
+ expect(collectGlobalReferences(definition, 'secrets')).toEqual(['A', 'B', 'C', 'D']);
77
+ });
78
+
79
+ it('lists a name once, in order of first appearance', () => {
80
+ const definition = definitionOf([
81
+ { id: 'one', type: StepType.SET, variable: 'x', value: '{{ secrets.B }}-{{ secrets.A }}' },
82
+ {
83
+ id: 'two',
84
+ type: StepType.SET,
85
+ variable: 'y',
86
+ value: { $expression: 'secrets.B + secrets["A"]' },
87
+ },
88
+ ]);
89
+ expect(collectGlobalReferences(definition, 'secrets')).toEqual(['B', 'A']);
90
+ });
91
+
92
+ it('ignores dynamic access, other globals, member chains and text outside placeholders', () => {
93
+ const definition = definitionOf([
94
+ {
95
+ id: 'code',
96
+ type: StepType.CODE,
97
+ source: 'const n = "K"; return [secrets[n], other.secrets.X, mysecrets.Y, secrets];',
98
+ },
99
+ { id: 'text', type: StepType.SET, variable: 't', value: 'secrets.OUTSIDE {{ input.x }}' },
100
+ { id: 'literal', type: StepType.SET, variable: 'l', value: 'secrets.LITERAL' },
101
+ ]);
102
+ expect(collectGlobalReferences(definition, 'secrets')).toEqual([]);
103
+ });
104
+
105
+ it('finds the config variables in fields, expressions and code, apart from the secrets', () => {
106
+ const definition = definitionOf([
107
+ {
108
+ id: 'http',
109
+ type: StepType.SET,
110
+ variable: 'u',
111
+ value: 'https://{{ config.HOST }}/x?k={{ secrets.KEY }}',
112
+ },
113
+ { id: 'expr', type: StepType.SET, variable: 'e', value: { $expression: 'config.MODE + 1' } },
114
+ { id: 'code', type: StepType.CODE, source: 'return [config["REGION"], config?.TIER];' },
115
+ ]);
116
+ expect(collectGlobalReferences(definition, 'config')).toEqual([
117
+ 'HOST',
118
+ 'MODE',
119
+ 'REGION',
120
+ 'TIER',
121
+ ]);
122
+ expect(collectGlobalReferences(definition, 'secrets')).toEqual(['KEY']);
123
+ });
124
+
125
+ it('works for any global name, and escapes it', () => {
126
+ const definition = definitionOf([
127
+ { id: 'a', type: StepType.SET, variable: 'a', value: '{{ workflow.project + secrets.S }}' },
128
+ ]);
129
+ expect(collectGlobalReferences(definition, 'workflow')).toEqual(['project']);
130
+ expect(collectGlobalReferences(definition, 'work.low')).toEqual([]);
131
+ expect(collectGlobalReferences(definition, '$')).toEqual([]);
132
+ });
133
+ });
@@ -1,186 +1,186 @@
1
- import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
2
- import type { RuntimeErrorDetail } from '../errors/runtime-error-code.enum';
3
- import { MAX_RESPONSE_STATUS, MIN_RESPONSE_STATUS } from '../definition/definition.limits';
4
- import { StepType } from '../definition/definition.types';
5
- import type {
6
- LogLevel,
7
- LogStep,
8
- RespondStep,
9
- Step,
10
- StopStatus,
11
- WaitStep,
12
- } from '../definition/definition.types';
13
- import type { HttpRequest, HttpResponseToSend } from '../interpreter/interpreter.types';
14
- import { propertyPath } from './value-source';
15
- import type { ResolvedFields } from './step-fields';
16
-
17
- export enum StepActionKind {
18
- /** The step finished without any effect. */
19
- DONE = 'DONE',
20
- STOP = 'STOP',
21
- WAIT = 'WAIT',
22
- HTTP = 'HTTP',
23
- HOST = 'HOST',
24
- LOG = 'LOG',
25
- RESPOND = 'RESPOND',
26
- FAIL = 'FAIL',
27
- }
28
-
29
- export type StepAction =
30
- | {
31
- kind: StepActionKind.DONE;
32
- output: unknown;
33
- variable?: { name: string; value: unknown };
34
- /** Sequence to enter, relative to the step: `then`, `else`, `cases[2].steps`, `default`. */
35
- branch?: string;
36
- }
37
- | { kind: StepActionKind.STOP; status: StopStatus; output: unknown }
38
- | { kind: StepActionKind.WAIT; durationMs?: number; until?: string }
39
- | { kind: StepActionKind.HTTP; request: HttpRequest }
40
- | { kind: StepActionKind.HOST; action: string; input: Record<string, unknown> }
41
- | { kind: StepActionKind.LOG; level: LogLevel; message: string; data?: unknown }
42
- | { kind: StepActionKind.RESPOND; response: HttpResponseToSend }
43
- | { kind: StepActionKind.FAIL; error: RuntimeErrorDetail };
44
-
45
- const fail = (message: string): StepAction => ({
46
- kind: StepActionKind.FAIL,
47
- error: { code: RuntimeErrorCode.EXPRESSION_ERROR, message },
48
- });
49
-
50
- const headerValue = (value: unknown): string =>
51
- typeof value === 'string' ? value : JSON.stringify(value) ?? '';
52
-
53
- const resolvedRecord = (
54
- base: string,
55
- keys: string[],
56
- fields: ResolvedFields,
57
- ): Record<string, unknown> =>
58
- Object.fromEntries(keys.map((key) => [key, fields.get(propertyPath(base, key))]));
59
-
60
- const executeWait = (step: WaitStep, fields: ResolvedFields): StepAction => {
61
- if (step.durationMs !== undefined) {
62
- const durationMs = fields.get('durationMs');
63
- if (typeof durationMs !== 'number' || !Number.isInteger(durationMs) || durationMs < 0) {
64
- return fail('Wait duration must resolve to a non-negative integer number of milliseconds');
65
- }
66
- return { kind: StepActionKind.WAIT, durationMs };
67
- }
68
- const until = fields.get('until');
69
- if (typeof until !== 'string' || Number.isNaN(Date.parse(until))) {
70
- return fail('Wait date must resolve to an ISO 8601 date');
71
- }
72
- return { kind: StepActionKind.WAIT, until };
73
- };
74
-
75
- const executeLog = (step: LogStep, fields: ResolvedFields): StepAction => {
76
- const message = fields.get('message');
77
- const action: Extract<StepAction, { kind: StepActionKind.LOG }> = {
78
- kind: StepActionKind.LOG,
79
- level: step.level,
80
- message: typeof message === 'string' ? message : JSON.stringify(message) ?? '',
81
- };
82
- if (step.data !== undefined) {
83
- action.data = fields.get('data');
84
- }
85
- return action;
86
- };
87
-
88
- const executeRespond = (step: RespondStep, fields: ResolvedFields): StepAction => {
89
- const status = fields.get('status');
90
- if (
91
- typeof status !== 'number' ||
92
- !Number.isInteger(status) ||
93
- status < MIN_RESPONSE_STATUS ||
94
- status > MAX_RESPONSE_STATUS
95
- ) {
96
- return fail(
97
- `Response status must resolve to an integer from ${MIN_RESPONSE_STATUS} to ${MAX_RESPONSE_STATUS}`,
98
- );
99
- }
100
- const headers = resolvedRecord('headers', Object.keys(step.headers ?? {}), fields);
101
- const response: HttpResponseToSend = {
102
- status,
103
- headers: Object.fromEntries(
104
- Object.entries(headers).map(([key, value]) => [key, headerValue(value)]),
105
- ),
106
- };
107
- if (step.body !== undefined) {
108
- response.body = fields.get('body');
109
- }
110
- return { kind: StepActionKind.RESPOND, response };
111
- };
112
-
113
- /**
114
- * Decides what a step does once its values are resolved. Pure: the access and schema checks of
115
- * HTTP and HOST effects belong to the caller.
116
- */
117
- export const executeStep = (step: Step, fields: ResolvedFields): StepAction => {
118
- switch (step.type) {
119
- case StepType.CONDITION: {
120
- if (fields.get('if')) {
121
- return { kind: StepActionKind.DONE, output: 'then', branch: 'then' };
122
- }
123
- return step.else
124
- ? { kind: StepActionKind.DONE, output: 'else', branch: 'else' }
125
- : { kind: StepActionKind.DONE, output: 'else' };
126
- }
127
- case StepType.SWITCH: {
128
- const value = fields.get('value');
129
- const index = step.cases.findIndex(
130
- (_, caseIndex) => fields.get(`cases[${caseIndex}].match`) === value,
131
- );
132
- if (index >= 0) {
133
- const branch = `cases[${index}].steps`;
134
- return { kind: StepActionKind.DONE, output: `cases[${index}]`, branch };
135
- }
136
- return step.default
137
- ? { kind: StepActionKind.DONE, output: 'default', branch: 'default' }
138
- : { kind: StepActionKind.DONE, output: null };
139
- }
140
- case StepType.WAIT:
141
- return executeWait(step, fields);
142
- case StepType.SET: {
143
- const value = fields.get('value');
144
- return {
145
- kind: StepActionKind.DONE,
146
- output: value,
147
- variable: { name: step.variable, value },
148
- };
149
- }
150
- case StepType.CODE:
151
- return { kind: StepActionKind.DONE, output: fields.get('source') };
152
- case StepType.HTTP: {
153
- const url = fields.get('url');
154
- if (typeof url !== 'string') {
155
- return fail('HTTP url must resolve to a string');
156
- }
157
- const headers = resolvedRecord('headers', Object.keys(step.headers ?? {}), fields);
158
- const request: HttpRequest = {
159
- method: step.method,
160
- url,
161
- headers: Object.fromEntries(
162
- Object.entries(headers).map(([key, value]) => [key, headerValue(value)]),
163
- ),
164
- };
165
- if (step.body !== undefined) {
166
- request.body = fields.get('body');
167
- }
168
- if (step.timeoutMs !== undefined) {
169
- request.timeoutMs = step.timeoutMs;
170
- }
171
- return { kind: StepActionKind.HTTP, request };
172
- }
173
- case StepType.HOST:
174
- return {
175
- kind: StepActionKind.HOST,
176
- action: step.action,
177
- input: resolvedRecord('input', Object.keys(step.input), fields),
178
- };
179
- case StepType.LOG:
180
- return executeLog(step, fields);
181
- case StepType.RESPOND:
182
- return executeRespond(step, fields);
183
- case StepType.STOP:
184
- return { kind: StepActionKind.STOP, status: step.status, output: fields.get('output') };
185
- }
186
- };
1
+ import { RuntimeErrorCode } from '../errors/runtime-error-code.enum';
2
+ import type { RuntimeErrorDetail } from '../errors/runtime-error-code.enum';
3
+ import { MAX_RESPONSE_STATUS, MIN_RESPONSE_STATUS } from '../definition/definition.limits';
4
+ import { StepType } from '../definition/definition.types';
5
+ import type {
6
+ LogLevel,
7
+ LogStep,
8
+ RespondStep,
9
+ Step,
10
+ StopStatus,
11
+ WaitStep,
12
+ } from '../definition/definition.types';
13
+ import type { HttpRequest, HttpResponseToSend } from '../interpreter/interpreter.types';
14
+ import { propertyPath } from './value-source';
15
+ import type { ResolvedFields } from './step-fields';
16
+
17
+ export enum StepActionKind {
18
+ /** The step finished without any effect. */
19
+ DONE = 'DONE',
20
+ STOP = 'STOP',
21
+ WAIT = 'WAIT',
22
+ HTTP = 'HTTP',
23
+ HOST = 'HOST',
24
+ LOG = 'LOG',
25
+ RESPOND = 'RESPOND',
26
+ FAIL = 'FAIL',
27
+ }
28
+
29
+ export type StepAction =
30
+ | {
31
+ kind: StepActionKind.DONE;
32
+ output: unknown;
33
+ variable?: { name: string; value: unknown };
34
+ /** Sequence to enter, relative to the step: `then`, `else`, `cases[2].steps`, `default`. */
35
+ branch?: string;
36
+ }
37
+ | { kind: StepActionKind.STOP; status: StopStatus; output: unknown }
38
+ | { kind: StepActionKind.WAIT; durationMs?: number; until?: string }
39
+ | { kind: StepActionKind.HTTP; request: HttpRequest }
40
+ | { kind: StepActionKind.HOST; action: string; input: Record<string, unknown> }
41
+ | { kind: StepActionKind.LOG; level: LogLevel; message: string; data?: unknown }
42
+ | { kind: StepActionKind.RESPOND; response: HttpResponseToSend }
43
+ | { kind: StepActionKind.FAIL; error: RuntimeErrorDetail };
44
+
45
+ const fail = (message: string): StepAction => ({
46
+ kind: StepActionKind.FAIL,
47
+ error: { code: RuntimeErrorCode.EXPRESSION_ERROR, message },
48
+ });
49
+
50
+ const headerValue = (value: unknown): string =>
51
+ typeof value === 'string' ? value : JSON.stringify(value) ?? '';
52
+
53
+ const resolvedRecord = (
54
+ base: string,
55
+ keys: string[],
56
+ fields: ResolvedFields,
57
+ ): Record<string, unknown> =>
58
+ Object.fromEntries(keys.map((key) => [key, fields.get(propertyPath(base, key))]));
59
+
60
+ const executeWait = (step: WaitStep, fields: ResolvedFields): StepAction => {
61
+ if (step.durationMs !== undefined) {
62
+ const durationMs = fields.get('durationMs');
63
+ if (typeof durationMs !== 'number' || !Number.isInteger(durationMs) || durationMs < 0) {
64
+ return fail('Wait duration must resolve to a non-negative integer number of milliseconds');
65
+ }
66
+ return { kind: StepActionKind.WAIT, durationMs };
67
+ }
68
+ const until = fields.get('until');
69
+ if (typeof until !== 'string' || Number.isNaN(Date.parse(until))) {
70
+ return fail('Wait date must resolve to an ISO 8601 date');
71
+ }
72
+ return { kind: StepActionKind.WAIT, until };
73
+ };
74
+
75
+ const executeLog = (step: LogStep, fields: ResolvedFields): StepAction => {
76
+ const message = fields.get('message');
77
+ const action: Extract<StepAction, { kind: StepActionKind.LOG }> = {
78
+ kind: StepActionKind.LOG,
79
+ level: step.level,
80
+ message: typeof message === 'string' ? message : JSON.stringify(message) ?? '',
81
+ };
82
+ if (step.data !== undefined) {
83
+ action.data = fields.get('data');
84
+ }
85
+ return action;
86
+ };
87
+
88
+ const executeRespond = (step: RespondStep, fields: ResolvedFields): StepAction => {
89
+ const status = fields.get('status');
90
+ if (
91
+ typeof status !== 'number' ||
92
+ !Number.isInteger(status) ||
93
+ status < MIN_RESPONSE_STATUS ||
94
+ status > MAX_RESPONSE_STATUS
95
+ ) {
96
+ return fail(
97
+ `Response status must resolve to an integer from ${MIN_RESPONSE_STATUS} to ${MAX_RESPONSE_STATUS}`,
98
+ );
99
+ }
100
+ const headers = resolvedRecord('headers', Object.keys(step.headers ?? {}), fields);
101
+ const response: HttpResponseToSend = {
102
+ status,
103
+ headers: Object.fromEntries(
104
+ Object.entries(headers).map(([key, value]) => [key, headerValue(value)]),
105
+ ),
106
+ };
107
+ if (step.body !== undefined) {
108
+ response.body = fields.get('body');
109
+ }
110
+ return { kind: StepActionKind.RESPOND, response };
111
+ };
112
+
113
+ /**
114
+ * Decides what a step does once its values are resolved. Pure: the access and schema checks of
115
+ * HTTP and HOST effects belong to the caller.
116
+ */
117
+ export const executeStep = (step: Step, fields: ResolvedFields): StepAction => {
118
+ switch (step.type) {
119
+ case StepType.CONDITION: {
120
+ if (fields.get('if')) {
121
+ return { kind: StepActionKind.DONE, output: 'then', branch: 'then' };
122
+ }
123
+ return step.else
124
+ ? { kind: StepActionKind.DONE, output: 'else', branch: 'else' }
125
+ : { kind: StepActionKind.DONE, output: 'else' };
126
+ }
127
+ case StepType.SWITCH: {
128
+ const value = fields.get('value');
129
+ const index = step.cases.findIndex(
130
+ (_, caseIndex) => fields.get(`cases[${caseIndex}].match`) === value,
131
+ );
132
+ if (index >= 0) {
133
+ const branch = `cases[${index}].steps`;
134
+ return { kind: StepActionKind.DONE, output: `cases[${index}]`, branch };
135
+ }
136
+ return step.default
137
+ ? { kind: StepActionKind.DONE, output: 'default', branch: 'default' }
138
+ : { kind: StepActionKind.DONE, output: null };
139
+ }
140
+ case StepType.WAIT:
141
+ return executeWait(step, fields);
142
+ case StepType.SET: {
143
+ const value = fields.get('value');
144
+ return {
145
+ kind: StepActionKind.DONE,
146
+ output: value,
147
+ variable: { name: step.variable, value },
148
+ };
149
+ }
150
+ case StepType.CODE:
151
+ return { kind: StepActionKind.DONE, output: fields.get('source') };
152
+ case StepType.HTTP: {
153
+ const url = fields.get('url');
154
+ if (typeof url !== 'string') {
155
+ return fail('HTTP url must resolve to a string');
156
+ }
157
+ const headers = resolvedRecord('headers', Object.keys(step.headers ?? {}), fields);
158
+ const request: HttpRequest = {
159
+ method: step.method,
160
+ url,
161
+ headers: Object.fromEntries(
162
+ Object.entries(headers).map(([key, value]) => [key, headerValue(value)]),
163
+ ),
164
+ };
165
+ if (step.body !== undefined) {
166
+ request.body = fields.get('body');
167
+ }
168
+ if (step.timeoutMs !== undefined) {
169
+ request.timeoutMs = step.timeoutMs;
170
+ }
171
+ return { kind: StepActionKind.HTTP, request };
172
+ }
173
+ case StepType.HOST:
174
+ return {
175
+ kind: StepActionKind.HOST,
176
+ action: step.action,
177
+ input: resolvedRecord('input', Object.keys(step.input), fields),
178
+ };
179
+ case StepType.LOG:
180
+ return executeLog(step, fields);
181
+ case StepType.RESPOND:
182
+ return executeRespond(step, fields);
183
+ case StepType.STOP:
184
+ return { kind: StepActionKind.STOP, status: step.status, output: fields.get('output') };
185
+ }
186
+ };