@abyss-project/runtime 3.12.0 → 3.13.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 (69) hide show
  1. package/.eslintrc.js +32 -32
  2. package/.prettierrc +5 -5
  3. package/README.md +88 -88
  4. package/dist/definition/definition.schema.js +6 -0
  5. package/dist/definition/definition.schema.js.map +1 -1
  6. package/dist/definition/definition.types.d.ts +11 -0
  7. package/dist/definition/definition.types.js +6 -1
  8. package/dist/definition/definition.types.js.map +1 -1
  9. package/dist/discord/discord.types.d.ts +2 -34
  10. package/dist/discord/discord.types.js +1 -9
  11. package/dist/discord/discord.types.js.map +1 -1
  12. package/dist/engine/engine-source.js +1 -1
  13. package/dist/errors/runtime-error-code.enum.d.ts +1 -0
  14. package/dist/errors/runtime-error-code.enum.js +1 -0
  15. package/dist/errors/runtime-error-code.enum.js.map +1 -1
  16. package/dist/runner-protocol/evaluation.types.d.ts +1 -0
  17. package/dist/steps/global-references.js +7 -0
  18. package/dist/steps/global-references.js.map +1 -1
  19. package/dist/steps/step-fields.js +10 -0
  20. package/dist/steps/step-fields.js.map +1 -1
  21. package/jest.config.ts +11 -11
  22. package/package.json +1 -1
  23. package/scripts/build-engine.cjs +70 -70
  24. package/src/__tests__/engine-bundle.test.ts +121 -121
  25. package/src/__tests__/surface.test.ts +81 -88
  26. package/src/access/__tests__/host-match.test.ts +24 -24
  27. package/src/access/access.types.ts +25 -25
  28. package/src/access/host-match.ts +13 -13
  29. package/src/cost/__tests__/execution-cost.test.ts +249 -249
  30. package/src/cost/execution-cost.ts +203 -203
  31. package/src/definition/__tests__/code-step.test.ts +56 -0
  32. package/src/definition/__tests__/validate-definition.test.ts +354 -354
  33. package/src/definition/definition.limits.ts +9 -9
  34. package/src/definition/definition.schema.ts +7 -0
  35. package/src/definition/definition.types.ts +21 -1
  36. package/src/definition/validate-definition.ts +206 -206
  37. package/src/definition/walk-steps.ts +44 -44
  38. package/src/discord/__tests__/discord-event-input.test.ts +90 -108
  39. package/src/discord/discord.types.ts +696 -738
  40. package/src/engine/__tests__/run-in-isolate.test.ts +519 -519
  41. package/src/engine/engine-entry.ts +3 -3
  42. package/src/engine/engine-global.ts +2 -2
  43. package/src/engine/run-in-isolate.ts +462 -462
  44. package/src/errors/runtime-error-code.enum.ts +5 -0
  45. package/src/index.ts +32 -32
  46. package/src/interpreter/__tests__/interpreter.test.ts +854 -854
  47. package/src/interpreter/__tests__/log-respond-resume.test.ts +271 -271
  48. package/src/interpreter/interpreter-error.ts +12 -12
  49. package/src/interpreter/interpreter.ts +483 -483
  50. package/src/interpreter/interpreter.types.ts +204 -204
  51. package/src/interpreter/sequence-path.ts +67 -67
  52. package/src/interpreter/test-host.ts +85 -85
  53. package/src/runner-protocol/__tests__/file-payload.test.ts +26 -26
  54. package/src/runner-protocol/evaluation.types.ts +2 -0
  55. package/src/runner-protocol/execution-protocol.types.ts +297 -297
  56. package/src/schedule/schedule.types.ts +100 -100
  57. package/src/server/__tests__/code-runner-session.test.ts +311 -311
  58. package/src/server/code-runner-error.ts +12 -12
  59. package/src/server/code-runner-session.ts +310 -310
  60. package/src/server/index.ts +11 -11
  61. package/src/steps/__tests__/global-references.test.ts +140 -124
  62. package/src/steps/__tests__/step-fields.test.ts +58 -0
  63. package/src/steps/execute-step.ts +186 -186
  64. package/src/steps/global-references.ts +56 -48
  65. package/src/steps/step-access.ts +56 -56
  66. package/src/steps/step-fields.ts +10 -0
  67. package/src/steps/value-source.ts +69 -69
  68. package/tsconfig.check.json +15 -15
  69. package/tsconfig.json +35 -35
@@ -1,203 +1,203 @@
1
- // Metered cost of an execution, shared by Flow and Reflex (ADR-0244). Prices are in
2
- // millicredits (thousandths of a credit). Every part is computed exactly, in integer
3
- // sub-millicredit units, and rounded half-up once, at the end.
4
-
5
- export enum ResourceProfile {
6
- S = 'S',
7
- M = 'M',
8
- L = 'L',
9
- XL = 'XL',
10
- XXL = 'XXL',
11
- }
12
-
13
- export interface ResourceProfileSpec {
14
- /** Memory of the execution's isolate. */
15
- memoryMb: number;
16
- /** Multiplies the CPU part. */
17
- cpuCoefficient: number;
18
- }
19
-
20
- export const RESOURCE_PROFILES: Readonly<Record<ResourceProfile, ResourceProfileSpec>> = {
21
- [ResourceProfile.S]: { memoryMb: 128, cpuCoefficient: 1 },
22
- [ResourceProfile.M]: { memoryMb: 256, cpuCoefficient: 1.05 },
23
- [ResourceProfile.L]: { memoryMb: 512, cpuCoefficient: 1.1 },
24
- [ResourceProfile.XL]: { memoryMb: 1024, cpuCoefficient: 1.2 },
25
- [ResourceProfile.XXL]: { memoryMb: 2048, cpuCoefficient: 1.35 },
26
- };
27
-
28
- /** The ADR-0244 price list, in millicredits. */
29
- export const COST_RATES = {
30
- /** Once per execution, whatever its number of segments. */
31
- executionMillicredits: 10,
32
- /** Once per autocomplete execution: replaces `executionMillicredits`; CPU and memory are free. */
33
- autocompleteExecutionMillicredits: 1,
34
- cpuMillicreditsPerSecond: 500,
35
- /** Per GB-second of ALLOCATED memory (the profile's), GB = 1024 MB. */
36
- memoryMillicreditsPerGbSecond: 100,
37
- /** Per MB sent out, MB = 1024 × 1024 bytes. */
38
- networkOutMillicreditsPerMb: 1000,
39
- httpCallMillicredits: 10,
40
- storeWriteMillicredits: 10,
41
- } as const;
42
-
43
- /** What started the execution: an autocomplete is priced apart (fixed price, free CPU and memory). */
44
- export enum CostedExecutionKind {
45
- STANDARD = 'STANDARD',
46
- AUTOCOMPLETE = 'AUTOCOMPLETE',
47
- }
48
-
49
- export enum CostedExecutionStatus {
50
- /** Ran (succeeded, failed or suspended): billed at the measure. */
51
- RAN = 'RAN',
52
- /** Stopped by a pod shutdown: free (ADR-0244 §6). */
53
- INTERRUPTED = 'INTERRUPTED',
54
- /** Refused before any step (401, 404, 429, paused, invalid input): free. */
55
- REFUSED = 'REFUSED',
56
- }
57
-
58
- /** What one step consumed. A refused host call is not counted in `httpCalls` nor `storeWrites`. */
59
- export interface StepUsage {
60
- cpuMs: number;
61
- wallMs: number;
62
- netOutBytes: number;
63
- httpCalls: number;
64
- storeWrites: number;
65
- }
66
-
67
- export interface ExecutionCostInput extends StepUsage {
68
- status: CostedExecutionStatus;
69
- profile: ResourceProfile;
70
- /** Defaults to `STANDARD`. */
71
- kind?: CostedExecutionKind;
72
- /**
73
- * True for the second and later segments of a suspended execution: they add their measure
74
- * but not the execution price, paid once by the first segment.
75
- */
76
- resumedSegment?: boolean;
77
- }
78
-
79
- export interface StepCostInput {
80
- /** The execution (segment) the steps belong to; its totals are what is billed. */
81
- execution: ExecutionCostInput;
82
- /** In execution order. */
83
- steps: StepUsage[];
84
- }
85
-
86
- // Exact unit: 1 / UNITS_PER_MILLICREDIT of a millicredit. Durations are taken in microseconds
87
- // (cpuMs and wallMs may carry fractions of a millisecond), coefficients in hundredths. Each part
88
- // is a product divided by a fixed denominator; UNITS_PER_MILLICREDIT is their least common
89
- // multiple, 2^20 × 5^8, so that every part is an exact integer of units.
90
- const MICROS_PER_SECOND = BigInt(1_000_000);
91
- const CPU_DENOMINATOR = MICROS_PER_SECOND * BigInt(100);
92
- const MEMORY_DENOMINATOR = BigInt(1024) * MICROS_PER_SECOND;
93
- const NETWORK_DENOMINATOR = BigInt(1024 * 1024);
94
- const UNITS_PER_MILLICREDIT = BigInt(1_048_576) * BigInt(390_625);
95
- const ZERO = BigInt(0);
96
- const ONE = BigInt(1);
97
- const TWO = BigInt(2);
98
-
99
- const assertUsage = (usage: StepUsage, subject: string): void => {
100
- (['cpuMs', 'wallMs', 'netOutBytes', 'httpCalls', 'storeWrites'] as const).forEach((key) => {
101
- const value = usage[key];
102
- if (!Number.isFinite(value) || value < 0) {
103
- throw new RangeError(`${subject}.${key} must be a finite number >= 0, got ${value}`);
104
- }
105
- });
106
- };
107
-
108
- const micros = (ms: number): bigint => BigInt(Math.round(ms * 1000));
109
- const whole = (count: number): bigint => BigInt(Math.round(count));
110
- /** Profile coefficients have at most two decimals (1.05): exact as integers. */
111
- const hundredths = (coefficient: number): bigint => BigInt(Math.round(coefficient * 100));
112
-
113
- /** Variable cost (everything but the execution price) of a usage, in exact units. */
114
- const variableUnits = (usage: StepUsage, execution: ExecutionCostInput): bigint => {
115
- const profile = RESOURCE_PROFILES[execution.profile];
116
- // cpuUs / 10^6 s × rate × coefficient% / 100
117
- const metered = execution.kind !== CostedExecutionKind.AUTOCOMPLETE;
118
- const cpu = !metered
119
- ? ZERO
120
- : (micros(usage.cpuMs) *
121
- BigInt(COST_RATES.cpuMillicreditsPerSecond) *
122
- hundredths(profile.cpuCoefficient) *
123
- UNITS_PER_MILLICREDIT) /
124
- CPU_DENOMINATOR;
125
- // memoryMb / 1024 GB × wallUs / 10^6 s × rate
126
- const memory = !metered
127
- ? ZERO
128
- : (BigInt(profile.memoryMb) *
129
- micros(usage.wallMs) *
130
- BigInt(COST_RATES.memoryMillicreditsPerGbSecond) *
131
- UNITS_PER_MILLICREDIT) /
132
- MEMORY_DENOMINATOR;
133
- // bytes / (1024 × 1024) MB × rate
134
- const network =
135
- (whole(usage.netOutBytes) *
136
- BigInt(COST_RATES.networkOutMillicreditsPerMb) *
137
- UNITS_PER_MILLICREDIT) /
138
- NETWORK_DENOMINATOR;
139
- const effects =
140
- (whole(usage.httpCalls) * BigInt(COST_RATES.httpCallMillicredits) +
141
- whole(usage.storeWrites) * BigInt(COST_RATES.storeWriteMillicredits)) *
142
- UNITS_PER_MILLICREDIT;
143
- return cpu + memory + network + effects;
144
- };
145
-
146
- /** Floor division, also for a negative numerator. */
147
- const floorDiv = (numerator: bigint, denominator: bigint): bigint => {
148
- const quotient = numerator / denominator;
149
- return numerator % denominator !== ZERO && numerator < ZERO ? quotient - ONE : quotient;
150
- };
151
-
152
- /** Exact units to whole millicredits, half-up. */
153
- const roundHalfUp = (units: bigint): number =>
154
- Number(floorDiv(units * TWO + UNITS_PER_MILLICREDIT, UNITS_PER_MILLICREDIT * TWO));
155
-
156
- const isFree = (execution: ExecutionCostInput): boolean =>
157
- execution.status !== CostedExecutionStatus.RAN;
158
-
159
- const executionPrice = (execution: ExecutionCostInput): number =>
160
- isFree(execution) || execution.resumedSegment
161
- ? 0
162
- : execution.kind === CostedExecutionKind.AUTOCOMPLETE
163
- ? COST_RATES.autocompleteExecutionMillicredits
164
- : COST_RATES.executionMillicredits;
165
-
166
- /** Cost of an execution (or of one segment of it), in whole millicredits. */
167
- export const computeExecutionCost = (input: ExecutionCostInput): number => {
168
- assertUsage(input, 'execution');
169
- if (isFree(input)) {
170
- return 0;
171
- }
172
- return executionPrice(input) + roundHalfUp(variableUnits(input, input));
173
- };
174
-
175
- /**
176
- * Spreads the variable cost of an execution over its steps, one whole number of millicredits
177
- * per step, in the order given. Each step gets its CPU, its memory (allocated memory × its
178
- * duration), its network and its effects; what the execution measured outside any step (the
179
- * engine between two steps) goes to the last step. Rounding is cumulative, so that
180
- * `sum(steps) + execution price = computeExecutionCost(execution)` holds exactly. An execution
181
- * that ran no step has nothing to spread: the result is empty.
182
- */
183
- export const computeStepCost = (input: StepCostInput): number[] => {
184
- const { execution, steps } = input;
185
- assertUsage(execution, 'execution');
186
- steps.forEach((step, index) => assertUsage(step, `steps[${index}]`));
187
- if (steps.length === 0) {
188
- return [];
189
- }
190
- if (isFree(execution)) {
191
- return steps.map(() => 0);
192
- }
193
- const total = variableUnits(execution, execution);
194
- let cumulative = ZERO;
195
- let assigned = 0;
196
- return steps.map((step, index) => {
197
- cumulative = index === steps.length - 1 ? total : cumulative + variableUnits(step, execution);
198
- const rounded = roundHalfUp(cumulative);
199
- const cost = rounded - assigned;
200
- assigned = rounded;
201
- return cost;
202
- });
203
- };
1
+ // Metered cost of an execution, shared by Flow and Reflex (ADR-0244). Prices are in
2
+ // millicredits (thousandths of a credit). Every part is computed exactly, in integer
3
+ // sub-millicredit units, and rounded half-up once, at the end.
4
+
5
+ export enum ResourceProfile {
6
+ S = 'S',
7
+ M = 'M',
8
+ L = 'L',
9
+ XL = 'XL',
10
+ XXL = 'XXL',
11
+ }
12
+
13
+ export interface ResourceProfileSpec {
14
+ /** Memory of the execution's isolate. */
15
+ memoryMb: number;
16
+ /** Multiplies the CPU part. */
17
+ cpuCoefficient: number;
18
+ }
19
+
20
+ export const RESOURCE_PROFILES: Readonly<Record<ResourceProfile, ResourceProfileSpec>> = {
21
+ [ResourceProfile.S]: { memoryMb: 128, cpuCoefficient: 1 },
22
+ [ResourceProfile.M]: { memoryMb: 256, cpuCoefficient: 1.05 },
23
+ [ResourceProfile.L]: { memoryMb: 512, cpuCoefficient: 1.1 },
24
+ [ResourceProfile.XL]: { memoryMb: 1024, cpuCoefficient: 1.2 },
25
+ [ResourceProfile.XXL]: { memoryMb: 2048, cpuCoefficient: 1.35 },
26
+ };
27
+
28
+ /** The ADR-0244 price list, in millicredits. */
29
+ export const COST_RATES = {
30
+ /** Once per execution, whatever its number of segments. */
31
+ executionMillicredits: 10,
32
+ /** Once per autocomplete execution: replaces `executionMillicredits`; CPU and memory are free. */
33
+ autocompleteExecutionMillicredits: 1,
34
+ cpuMillicreditsPerSecond: 500,
35
+ /** Per GB-second of ALLOCATED memory (the profile's), GB = 1024 MB. */
36
+ memoryMillicreditsPerGbSecond: 100,
37
+ /** Per MB sent out, MB = 1024 × 1024 bytes. */
38
+ networkOutMillicreditsPerMb: 1000,
39
+ httpCallMillicredits: 10,
40
+ storeWriteMillicredits: 10,
41
+ } as const;
42
+
43
+ /** What started the execution: an autocomplete is priced apart (fixed price, free CPU and memory). */
44
+ export enum CostedExecutionKind {
45
+ STANDARD = 'STANDARD',
46
+ AUTOCOMPLETE = 'AUTOCOMPLETE',
47
+ }
48
+
49
+ export enum CostedExecutionStatus {
50
+ /** Ran (succeeded, failed or suspended): billed at the measure. */
51
+ RAN = 'RAN',
52
+ /** Stopped by a pod shutdown: free (ADR-0244 §6). */
53
+ INTERRUPTED = 'INTERRUPTED',
54
+ /** Refused before any step (401, 404, 429, paused, invalid input): free. */
55
+ REFUSED = 'REFUSED',
56
+ }
57
+
58
+ /** What one step consumed. A refused host call is not counted in `httpCalls` nor `storeWrites`. */
59
+ export interface StepUsage {
60
+ cpuMs: number;
61
+ wallMs: number;
62
+ netOutBytes: number;
63
+ httpCalls: number;
64
+ storeWrites: number;
65
+ }
66
+
67
+ export interface ExecutionCostInput extends StepUsage {
68
+ status: CostedExecutionStatus;
69
+ profile: ResourceProfile;
70
+ /** Defaults to `STANDARD`. */
71
+ kind?: CostedExecutionKind;
72
+ /**
73
+ * True for the second and later segments of a suspended execution: they add their measure
74
+ * but not the execution price, paid once by the first segment.
75
+ */
76
+ resumedSegment?: boolean;
77
+ }
78
+
79
+ export interface StepCostInput {
80
+ /** The execution (segment) the steps belong to; its totals are what is billed. */
81
+ execution: ExecutionCostInput;
82
+ /** In execution order. */
83
+ steps: StepUsage[];
84
+ }
85
+
86
+ // Exact unit: 1 / UNITS_PER_MILLICREDIT of a millicredit. Durations are taken in microseconds
87
+ // (cpuMs and wallMs may carry fractions of a millisecond), coefficients in hundredths. Each part
88
+ // is a product divided by a fixed denominator; UNITS_PER_MILLICREDIT is their least common
89
+ // multiple, 2^20 × 5^8, so that every part is an exact integer of units.
90
+ const MICROS_PER_SECOND = BigInt(1_000_000);
91
+ const CPU_DENOMINATOR = MICROS_PER_SECOND * BigInt(100);
92
+ const MEMORY_DENOMINATOR = BigInt(1024) * MICROS_PER_SECOND;
93
+ const NETWORK_DENOMINATOR = BigInt(1024 * 1024);
94
+ const UNITS_PER_MILLICREDIT = BigInt(1_048_576) * BigInt(390_625);
95
+ const ZERO = BigInt(0);
96
+ const ONE = BigInt(1);
97
+ const TWO = BigInt(2);
98
+
99
+ const assertUsage = (usage: StepUsage, subject: string): void => {
100
+ (['cpuMs', 'wallMs', 'netOutBytes', 'httpCalls', 'storeWrites'] as const).forEach((key) => {
101
+ const value = usage[key];
102
+ if (!Number.isFinite(value) || value < 0) {
103
+ throw new RangeError(`${subject}.${key} must be a finite number >= 0, got ${value}`);
104
+ }
105
+ });
106
+ };
107
+
108
+ const micros = (ms: number): bigint => BigInt(Math.round(ms * 1000));
109
+ const whole = (count: number): bigint => BigInt(Math.round(count));
110
+ /** Profile coefficients have at most two decimals (1.05): exact as integers. */
111
+ const hundredths = (coefficient: number): bigint => BigInt(Math.round(coefficient * 100));
112
+
113
+ /** Variable cost (everything but the execution price) of a usage, in exact units. */
114
+ const variableUnits = (usage: StepUsage, execution: ExecutionCostInput): bigint => {
115
+ const profile = RESOURCE_PROFILES[execution.profile];
116
+ // cpuUs / 10^6 s × rate × coefficient% / 100
117
+ const metered = execution.kind !== CostedExecutionKind.AUTOCOMPLETE;
118
+ const cpu = !metered
119
+ ? ZERO
120
+ : (micros(usage.cpuMs) *
121
+ BigInt(COST_RATES.cpuMillicreditsPerSecond) *
122
+ hundredths(profile.cpuCoefficient) *
123
+ UNITS_PER_MILLICREDIT) /
124
+ CPU_DENOMINATOR;
125
+ // memoryMb / 1024 GB × wallUs / 10^6 s × rate
126
+ const memory = !metered
127
+ ? ZERO
128
+ : (BigInt(profile.memoryMb) *
129
+ micros(usage.wallMs) *
130
+ BigInt(COST_RATES.memoryMillicreditsPerGbSecond) *
131
+ UNITS_PER_MILLICREDIT) /
132
+ MEMORY_DENOMINATOR;
133
+ // bytes / (1024 × 1024) MB × rate
134
+ const network =
135
+ (whole(usage.netOutBytes) *
136
+ BigInt(COST_RATES.networkOutMillicreditsPerMb) *
137
+ UNITS_PER_MILLICREDIT) /
138
+ NETWORK_DENOMINATOR;
139
+ const effects =
140
+ (whole(usage.httpCalls) * BigInt(COST_RATES.httpCallMillicredits) +
141
+ whole(usage.storeWrites) * BigInt(COST_RATES.storeWriteMillicredits)) *
142
+ UNITS_PER_MILLICREDIT;
143
+ return cpu + memory + network + effects;
144
+ };
145
+
146
+ /** Floor division, also for a negative numerator. */
147
+ const floorDiv = (numerator: bigint, denominator: bigint): bigint => {
148
+ const quotient = numerator / denominator;
149
+ return numerator % denominator !== ZERO && numerator < ZERO ? quotient - ONE : quotient;
150
+ };
151
+
152
+ /** Exact units to whole millicredits, half-up. */
153
+ const roundHalfUp = (units: bigint): number =>
154
+ Number(floorDiv(units * TWO + UNITS_PER_MILLICREDIT, UNITS_PER_MILLICREDIT * TWO));
155
+
156
+ const isFree = (execution: ExecutionCostInput): boolean =>
157
+ execution.status !== CostedExecutionStatus.RAN;
158
+
159
+ const executionPrice = (execution: ExecutionCostInput): number =>
160
+ isFree(execution) || execution.resumedSegment
161
+ ? 0
162
+ : execution.kind === CostedExecutionKind.AUTOCOMPLETE
163
+ ? COST_RATES.autocompleteExecutionMillicredits
164
+ : COST_RATES.executionMillicredits;
165
+
166
+ /** Cost of an execution (or of one segment of it), in whole millicredits. */
167
+ export const computeExecutionCost = (input: ExecutionCostInput): number => {
168
+ assertUsage(input, 'execution');
169
+ if (isFree(input)) {
170
+ return 0;
171
+ }
172
+ return executionPrice(input) + roundHalfUp(variableUnits(input, input));
173
+ };
174
+
175
+ /**
176
+ * Spreads the variable cost of an execution over its steps, one whole number of millicredits
177
+ * per step, in the order given. Each step gets its CPU, its memory (allocated memory × its
178
+ * duration), its network and its effects; what the execution measured outside any step (the
179
+ * engine between two steps) goes to the last step. Rounding is cumulative, so that
180
+ * `sum(steps) + execution price = computeExecutionCost(execution)` holds exactly. An execution
181
+ * that ran no step has nothing to spread: the result is empty.
182
+ */
183
+ export const computeStepCost = (input: StepCostInput): number[] => {
184
+ const { execution, steps } = input;
185
+ assertUsage(execution, 'execution');
186
+ steps.forEach((step, index) => assertUsage(step, `steps[${index}]`));
187
+ if (steps.length === 0) {
188
+ return [];
189
+ }
190
+ if (isFree(execution)) {
191
+ return steps.map(() => 0);
192
+ }
193
+ const total = variableUnits(execution, execution);
194
+ let cumulative = ZERO;
195
+ let assigned = 0;
196
+ return steps.map((step, index) => {
197
+ cumulative = index === steps.length - 1 ? total : cumulative + variableUnits(step, execution);
198
+ const rounded = roundHalfUp(cumulative);
199
+ const cost = rounded - assigned;
200
+ assigned = rounded;
201
+ return cost;
202
+ });
203
+ };
@@ -0,0 +1,56 @@
1
+ import { AccessKind } from '../../access/access.types';
2
+ import { CodeLanguage, CURRENT_FORMAT_VERSION, StepType } from '../definition.types';
3
+ import { validateDefinition } from '../validate-definition';
4
+
5
+ const compiled = { code: 'return 1;', sourceMap: '{"version":3}', toolchain: 'esbuild@0.28.2' };
6
+
7
+ const definitionWith = (step: Record<string, unknown>) => ({
8
+ formatVersion: CURRENT_FORMAT_VERSION,
9
+ accesses: [{ kind: AccessKind.HTTP, hosts: ['api.example.com'] }],
10
+ steps: [{ id: 'code', type: StepType.CODE, source: 'return 1;', ...step }],
11
+ });
12
+
13
+ const pathsOf = (raw: unknown): string[] => {
14
+ const result = validateDefinition(raw, new Map());
15
+ if (result.ok) throw new Error('expected a refusal');
16
+ return result.errors.map((error) => error.path);
17
+ };
18
+
19
+ describe('CODE step language and compiled code', () => {
20
+ it('accepts a Flow-shaped CODE step without language nor compiled', () => {
21
+ const raw = definitionWith({});
22
+ expect(validateDefinition(raw, new Map())).toEqual({ ok: true, definition: raw });
23
+ });
24
+
25
+ it('accepts each language, with or without compiled code', () => {
26
+ for (const language of Object.values(CodeLanguage)) {
27
+ const raw = definitionWith({ language, compiled });
28
+ expect(validateDefinition(raw, new Map())).toEqual({ ok: true, definition: raw });
29
+ }
30
+ const alone = definitionWith({ language: CodeLanguage.TYPESCRIPT });
31
+ expect(validateDefinition(alone, new Map())).toEqual({ ok: true, definition: alone });
32
+ });
33
+
34
+ it('refuses an unknown language', () => {
35
+ expect(pathsOf(definitionWith({ language: 'PYTHON' }))).toEqual(['steps[0].language']);
36
+ });
37
+
38
+ it('refuses a compiled code with a missing or empty field', () => {
39
+ for (const field of ['code', 'sourceMap', 'toolchain']) {
40
+ expect(pathsOf(definitionWith({ compiled: { ...compiled, [field]: '' } }))).toEqual([
41
+ `steps[0].compiled.${field}`,
42
+ ]);
43
+ const partial: Record<string, string> = { ...compiled };
44
+ delete partial[field];
45
+ expect(pathsOf(definitionWith({ compiled: partial }))).toEqual([
46
+ `steps[0].compiled.${field}`,
47
+ ]);
48
+ }
49
+ });
50
+
51
+ it('refuses an unknown field inside compiled', () => {
52
+ expect(pathsOf(definitionWith({ compiled: { ...compiled, extra: 'x' } }))).toEqual([
53
+ 'steps[0].compiled.extra',
54
+ ]);
55
+ });
56
+ });