aws-local-stepfunctions 0.3.2 → 0.4.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.
package/build/main.cjs CHANGED
@@ -1,5 +1,927 @@
1
- "use strict";var K=Object.create;var E=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames,q=Object.getOwnPropertySymbols,Z=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty,R=Object.prototype.propertyIsEnumerable;var M=(s,t,e)=>t in s?E(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,A=(s,t)=>{for(var e in t||(t={}))G.call(t,e)&&M(s,e,t[e]);if(q)for(var e of q(t))R.call(t,e)&&M(s,e,t[e]);return s};var tt=(s,t)=>{for(var e in t)E(s,e,{get:t[e],enumerable:!0})},B=(s,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Y(t))!G.call(s,r)&&r!==e&&E(s,r,{get:()=>t[r],enumerable:!(a=X(t,r))||a.enumerable});return s};var c=(s,t,e)=>(e=s!=null?K(Z(s)):{},B(t||!s||!s.__esModule?E(e,"default",{value:s,enumerable:!0}):e,s)),et=s=>B(E({},"__esModule",{value:!0}),s);var l=(s,t,e)=>new Promise((a,r)=>{var i=m=>{try{u(e.next(m))}catch(p){r(p)}},o=m=>{try{u(e.throw(m))}catch(p){r(p)}},u=m=>m.done?a(m.value):Promise.resolve(m.value).then(i,o);u((e=e.apply(s,t)).next())});var at={};tt(at,{ExecutionAbortedError:()=>y,StateMachine:()=>O});module.exports=et(at);var S=class{constructor(t){this.stateDefinition=t}buildExecutionResult(t){let e={stateResult:t,nextState:"",isEndState:!1};return"Next"in this.stateDefinition&&(e.nextState=this.stateDefinition.Next),"End"in this.stateDefinition&&(e.isEndState=this.stateDefinition.End),e}};var N=require("@aws-sdk/client-lambda");var V=class extends Error{constructor(t){super(t)}};var g=class extends V{constructor(e,a){super(`Execution of Lambda function "${a}" failed`);this.name="LambdaExecutionError",this.wrappedError=new Error(e.errorMessage),this.wrappedError.stack=e.trace.join(`
2
- `)}toString(){return`${this.name}: ${this.message}. The error thrown by the Lambda was:
3
- ${this.wrappedError.stack}`}};var b=class{constructor(t){this.client=new N.LambdaClient(t!=null?t:{})}invokeFunction(t,e){return l(this,null,function*(){let a=Buffer.from(JSON.stringify(e)),r=new N.InvokeCommand({FunctionName:t,Payload:a}),i=yield this.client.send(r),o=null;if(i.Payload&&(o=Buffer.from(i.Payload).toString(),o=JSON.parse(o)),i.FunctionError)throw new g(o,t);return o})}};var P=class extends S{constructor(t){super(t)}executeState(t,e,a){return l(this,null,function*(){let r=this.stateDefinition,i=new b;try{if(a!=null&&a.overrideFn){let u=yield a.overrideFn(t);return this.buildExecutionResult(u)}let o=yield i.invokeFunction(r.Resource,t);return this.buildExecutionResult(o)}catch(o){throw o instanceof g?console.error(o.toString()):console.error(o),o}})}};var H=require("jsonpath-plus");function n(s,t,e){return s.startsWith("$$")?(0,H.JSONPath)({path:s.slice(1),json:e!=null?e:null,wrap:!1}):(0,H.JSONPath)({path:s,json:t,wrap:!1})}function k(s){return!!s&&Object.getPrototypeOf(s)===Object.prototype}function x(s,t){return new Promise(e=>{let a=setTimeout(e,s);t==null||t.addEventListener("abort",()=>{a.unref()})})}var F=c(require("lodash/cloneDeep.js"),1),W=c(require("lodash/set.js"),1);function j(s,t,e){return s===void 0?t:s===null?{}:n(s,t,e)}function T(s,t,e){let a=Object.entries(s).map(([r,i])=>{let o=r,u=i;return k(i)&&(u=T(i,t)),r.endsWith(".$")&&typeof i=="string"&&(o=r.replace(".$",""),u=n(i,t,e)),[o,u]});return Object.fromEntries(a)}function $(s,t,e){if(s===void 0)return e;if(s===null)return t;let a=s.replace("$.","");if(k(t)){let r=(0,F.default)(t);return(0,W.default)(r,a,e)}else throw new Error("TODO: Change this error message for a more descriptive one")}function Q(s,t,e){return s===void 0?t:s===null?{}:n(s,t,e)}var z=c(require("p-limit"),1);var w=class extends S{constructor(t){super(t)}processItem(t,e,a,r,i){let o=this.stateDefinition,u;a.Map={Item:{Index:r,Value:t}},o.Parameters&&(u=T(o.Parameters,e,a));let m=new O(o.Iterator,i==null?void 0:i.validationOptions),{result:p}=m.run(u!=null?u:t,i==null?void 0:i.runOptions);return p}executeState(t,e,a){return l(this,null,function*(){let r=this.stateDefinition,i=t;if(r.ItemsPath&&(i=n(r.ItemsPath,t,e)),!Array.isArray(i))return this.buildExecutionResult([]);let o=40,u=(0,z.default)(r.MaxConcurrency||o),m=i.map((d,f)=>u(()=>this.processItem(d,t,e,f,a))),p=yield Promise.all(m);return delete e.Map,this.buildExecutionResult(p)})}};var v=class extends S{constructor(t){super(t)}executeState(t,e,a){return l(this,null,function*(){return this.stateDefinition.Result?this.buildExecutionResult(this.stateDefinition.Result):this.buildExecutionResult(t)})}};var h=class extends S{constructor(t){super(t)}executeState(t,e,a){return l(this,null,function*(){let r=this.stateDefinition;if((a==null?void 0:a.waitTimeOverrideOption)!==void 0)return yield x(a.waitTimeOverrideOption,a.abortSignal),this.buildExecutionResult(t);if(r.Seconds)yield x(r.Seconds*1e3,a==null?void 0:a.abortSignal);else if(r.Timestamp){let i=new Date(r.Timestamp),o=Date.now(),u=i.getTime()-o;yield x(u,a==null?void 0:a.abortSignal)}else if(r.SecondsPath){let i=n(r.SecondsPath,t,e);yield x(i*1e3,a==null?void 0:a.abortSignal)}else if(r.TimestampPath){let i=n(r.TimestampPath,t,e),o=new Date(i),u=Date.now(),m=o.getTime()-u;yield x(m,a==null?void 0:a.abortSignal)}return this.buildExecutionResult(t)})}};var U=c(require("wildcard-match"),1);var J=class extends S{constructor(t){super(t)}testChoiceRule(t,e){if("And"in t)return t.And.every(a=>this.testChoiceRule(a,e));if("Or"in t)return t.Or.some(a=>this.testChoiceRule(a,e));if("Not"in t)return!this.testChoiceRule(t.Not,e);if("StringEquals"in t)return n(t.Variable,e)===t.StringEquals;if("StringEqualsPath"in t){let a=n(t.Variable,e),r=n(t.StringEqualsPath,e);return a===r}if("StringLessThan"in t)return n(t.Variable,e)<t.StringLessThan;if("StringLessThanPath"in t){let a=n(t.Variable,e),r=n(t.StringLessThanPath,e);return a<r}if("StringGreaterThan"in t)return n(t.Variable,e)>t.StringGreaterThan;if("StringGreaterThanPath"in t){let a=n(t.Variable,e),r=n(t.StringGreaterThanPath,e);return a>r}if("StringLessThanEquals"in t)return n(t.Variable,e)<=t.StringLessThanEquals;if("StringLessThanEqualsPath"in t){let a=n(t.Variable,e),r=n(t.StringLessThanEqualsPath,e);return a<=r}if("StringGreaterThanEquals"in t)return n(t.Variable,e)>=t.StringGreaterThanEquals;if("StringGreaterThanEqualsPath"in t){let a=n(t.Variable,e),r=n(t.StringGreaterThanEqualsPath,e);return a>=r}if("StringMatches"in t){let a=n(t.Variable,e);return(0,U.default)(t.StringMatches,{separator:!1})(a)}if("NumericEquals"in t)return n(t.Variable,e)===t.NumericEquals;if("NumericEqualsPath"in t){let a=n(t.Variable,e),r=n(t.NumericEqualsPath,e);return a===r}if("NumericLessThan"in t)return n(t.Variable,e)<t.NumericLessThan;if("NumericLessThanPath"in t){let a=n(t.Variable,e),r=n(t.NumericLessThanPath,e);return a<r}if("NumericGreaterThan"in t)return n(t.Variable,e)>t.NumericGreaterThan;if("NumericGreaterThanPath"in t){let a=n(t.Variable,e),r=n(t.NumericGreaterThanPath,e);return a>r}if("NumericLessThanEquals"in t)return n(t.Variable,e)<=t.NumericLessThanEquals;if("NumericLessThanEqualsPath"in t){let a=n(t.Variable,e),r=n(t.NumericLessThanEqualsPath,e);return a<=r}if("NumericGreaterThanEquals"in t)return n(t.Variable,e)>=t.NumericGreaterThanEquals;if("NumericGreaterThanEqualsPath"in t){let a=n(t.Variable,e),r=n(t.NumericGreaterThanEqualsPath,e);return a>=r}if("BooleanEquals"in t)return n(t.Variable,e)===t.BooleanEquals;if("BooleanEqualsPath"in t){let a=n(t.Variable,e),r=n(t.BooleanEqualsPath,e);return a===r}if("TimestampEquals"in t){let a=new Date(n(t.Variable,e)),r=new Date(t.TimestampEquals);return a.getTime()===r.getTime()}if("TimestampEqualsPath"in t){let a=new Date(n(t.Variable,e)),r=new Date(n(t.TimestampEqualsPath,e));return a.getTime()===r.getTime()}if("TimestampLessThan"in t){let a=new Date(n(t.Variable,e)),r=new Date(t.TimestampLessThan);return a<r}if("TimestampLessThanPath"in t){let a=new Date(n(t.Variable,e)),r=new Date(n(t.TimestampLessThanPath,e));return a<r}if("TimestampGreaterThan"in t){let a=new Date(n(t.Variable,e)),r=new Date(t.TimestampGreaterThan);return a>r}if("TimestampGreaterThanPath"in t){let a=new Date(n(t.Variable,e)),r=new Date(n(t.TimestampGreaterThanPath,e));return a>r}if("TimestampLessThanEquals"in t){let a=new Date(n(t.Variable,e)),r=new Date(t.TimestampLessThanEquals);return a<=r}if("TimestampLessThanEqualsPath"in t){let a=new Date(n(t.Variable,e)),r=new Date(n(t.TimestampLessThanEqualsPath,e));return a<=r}if("TimestampGreaterThanEquals"in t){let a=new Date(n(t.Variable,e)),r=new Date(t.TimestampGreaterThanEquals);return a>=r}if("TimestampGreaterThanEqualsPath"in t){let a=new Date(n(t.Variable,e)),r=new Date(n(t.TimestampGreaterThanEqualsPath,e));return a>=r}if("IsNull"in t){let a=n(t.Variable,e);return t.IsNull&&a===null}if("IsPresent"in t){let a=n(t.Variable,e);return t.IsPresent&&a!==void 0}if("IsNumeric"in t){let a=n(t.Variable,e);return t.IsNumeric&&typeof a=="number"}if("IsString"in t){let a=n(t.Variable,e);return t.IsString&&typeof a=="string"}if("IsBoolean"in t){let a=n(t.Variable,e);return t.IsBoolean&&typeof a=="boolean"}if("IsTimestamp"in t){let a=n(t.Variable,e);return t.IsTimestamp&&/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|(\+|-)\d{2}:\d{2})/.test(a)}return!1}executeState(t,e,a){return l(this,null,function*(){let r=this.stateDefinition;for(let i of r.Choices)if(this.testChoiceRule(i,t))return{stateResult:t,nextState:i.Next,isEndState:!1};if(r.Default)return{stateResult:t,nextState:r.Default,isEndState:!1};throw new Error("States.NoChoiceMatched")})}};var D=class extends S{constructor(t){super(t)}executeState(t,e,a){return l(this,null,function*(){return{stateResult:t,nextState:"",isEndState:!0}})}};var I=class extends S{constructor(t){super(t)}executeState(t,e,a){return l(this,null,function*(){return{stateResult:t,nextState:"",isEndState:!0}})}};var y=class extends V{constructor(){super("Execution aborted"),this.name="ExecutionAbortedError"}toString(){return"Execution aborted"}};var _=c(require("asl-validator"),1),C=c(require("lodash/cloneDeep.js"),1);var O=class{constructor(t,e){let{isValid:a,errorsText:r}=(0,_.default)(t,A({checkArn:!0,checkPaths:!0},e));if(!a)throw new Error(`State machine definition is invalid, see error(s) below:
4
- ${r(`
5
- `)}`);this.definition=t,this.stateExecutors={Task:this.executeTaskState,Map:this.executeMapState,Pass:this.executePassState,Wait:this.executeWaitState,Choice:this.executeChoiceState,Succeed:this.executeSucceedState,Fail:this.executeFailState},this.validationOptions=e}run(t,e){let a=new AbortController,r=new Promise((u,m)=>{e!=null&&e.noThrowOnAbort?a.signal.addEventListener("abort",()=>u(null)):a.signal.addEventListener("abort",()=>m(new y))}),i=this.execute(t,{validationOptions:this.validationOptions,runOptions:e,abortSignal:a.signal}),o=Promise.race([i,r]);return{abort:()=>a.abort(),result:o}}execute(t,e){return l(this,null,function*(){let a=this.definition.States[this.definition.StartAt],r=this.definition.StartAt,i=(0,C.default)(t),o=(0,C.default)(t),u=null,m="",p=!1,d={};do o=this.processInput(a,o,d),{stateResult:u,nextState:m,isEndState:p}=yield this.stateExecutors[a.Type](a,o,d,r,e),u=this.processResult(a,u,i,d),i=u,o=u,a=this.definition.States[m],r=m;while(!p&&!e.abortSignal.aborted);return u})}processInput(t,e,a){let r=e;return"InputPath"in t&&(r=j(t.InputPath,r,a)),"Parameters"in t&&t.Type!=="Map"&&(r=T(t.Parameters,r,a)),r}processResult(t,e,a,r){let i=e;return"ResultSelector"in t&&(i=T(t.ResultSelector,i,r)),"ResultPath"in t&&(i=$(t.ResultPath,a,i)),"OutputPath"in t&&(i=Q(t.OutputPath,i,r)),i}executeTaskState(t,e,a,r,i){return l(this,null,function*(){var p,d,f;let o=(f=(d=(p=i.runOptions)==null?void 0:p.overrides)==null?void 0:d.taskResourceLocalHandlers)==null?void 0:f[r];return yield new P(t).executeState(e,a,{overrideFn:o})})}executeMapState(t,e,a,r,i){return l(this,null,function*(){return yield new w(t).executeState(e,a,{validationOptions:i.validationOptions,runOptions:i.runOptions})})}executePassState(t,e,a,r,i){return l(this,null,function*(){return yield new v(t).executeState(e,a)})}executeWaitState(t,e,a,r,i){return l(this,null,function*(){var d,f,L;let o=(L=(f=(d=i.runOptions)==null?void 0:d.overrides)==null?void 0:f.waitTimeOverrides)==null?void 0:L[r],u=i.abortSignal;return yield new h(t).executeState(e,a,{waitTimeOverrideOption:o,abortSignal:u})})}executeChoiceState(t,e,a,r,i){return l(this,null,function*(){return yield new J(t).executeState(e,a)})}executeSucceedState(t,e,a,r,i){return l(this,null,function*(){return yield new D(t).executeState(e,a)})}executeFailState(t,e,a,r,i){return l(this,null,function*(){return yield new I(t).executeState(e,a)})}};0&&(module.exports={ExecutionAbortedError,StateMachine});
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var __accessCheck = (obj, member, msg) => {
30
+ if (!member.has(obj))
31
+ throw TypeError("Cannot " + msg);
32
+ };
33
+ var __privateGet = (obj, member, getter) => {
34
+ __accessCheck(obj, member, "read from private field");
35
+ return getter ? getter.call(obj) : member.get(obj);
36
+ };
37
+ var __privateAdd = (obj, member, value) => {
38
+ if (member.has(obj))
39
+ throw TypeError("Cannot add the same private member more than once");
40
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
41
+ };
42
+ var __privateSet = (obj, member, value, setter) => {
43
+ __accessCheck(obj, member, "write to private field");
44
+ setter ? setter.call(obj, value) : member.set(obj, value);
45
+ return value;
46
+ };
47
+
48
+ // src/main.ts
49
+ var main_exports = {};
50
+ __export(main_exports, {
51
+ ExecutionAbortedError: () => ExecutionAbortedError,
52
+ ExecutionError: () => ExecutionError,
53
+ StateMachine: () => StateMachine
54
+ });
55
+ module.exports = __toCommonJS(main_exports);
56
+
57
+ // src/error/ExecutionAbortedError.ts
58
+ var ExecutionAbortedError = class extends Error {
59
+ constructor() {
60
+ super("Execution aborted");
61
+ this.name = "ExecutionAbortedError";
62
+ }
63
+ };
64
+
65
+ // src/error/ExecutionError.ts
66
+ var _wrappedError;
67
+ var ExecutionError = class extends Error {
68
+ constructor(caughtError) {
69
+ super(`Execution has failed with the following error: ${caughtError.message}`);
70
+ __privateAdd(this, _wrappedError, void 0);
71
+ this.name = "ExecutionError";
72
+ __privateSet(this, _wrappedError, caughtError);
73
+ }
74
+ get getWrappedError() {
75
+ return __privateGet(this, _wrappedError);
76
+ }
77
+ };
78
+ _wrappedError = new WeakMap();
79
+
80
+ // src/util/index.ts
81
+ function isPlainObj(value) {
82
+ return !!value && Object.getPrototypeOf(value) === Object.prototype;
83
+ }
84
+ function sleep(ms, abortSignal) {
85
+ return new Promise((resolve) => {
86
+ const timeout = setTimeout(resolve, ms);
87
+ abortSignal?.addEventListener("abort", () => {
88
+ clearTimeout(timeout);
89
+ });
90
+ });
91
+ }
92
+
93
+ // src/stateMachine/JsonPath.ts
94
+ var import_jsonpath_plus = require("jsonpath-plus");
95
+ function jsonPathQuery(pathExpression, json, context) {
96
+ if (pathExpression.startsWith("$$")) {
97
+ return (0, import_jsonpath_plus.JSONPath)({ path: pathExpression.slice(1), json: context ?? null, wrap: false });
98
+ }
99
+ return (0, import_jsonpath_plus.JSONPath)({ path: pathExpression, json, wrap: false });
100
+ }
101
+
102
+ // src/error/RuntimeError.ts
103
+ var RuntimeError = class extends Error {
104
+ constructor(message) {
105
+ super(message);
106
+ this.name = "RuntimeError";
107
+ this.retryable = true;
108
+ this.catchable = true;
109
+ }
110
+ get isRetryable() {
111
+ return this.retryable;
112
+ }
113
+ get isCatchable() {
114
+ return this.catchable;
115
+ }
116
+ };
117
+
118
+ // src/error/predefined/StatesResultPathMatchFailureError.ts
119
+ var StatesResultPathMatchFailureError = class extends RuntimeError {
120
+ constructor() {
121
+ super("States.ResultPathMatchFailure");
122
+ this.name = "States.ResultPathMatchFailure";
123
+ }
124
+ };
125
+
126
+ // src/stateMachine/InputOutputProcessing.ts
127
+ var import_cloneDeep = __toESM(require("lodash/cloneDeep.js"), 1);
128
+ var import_set = __toESM(require("lodash/set.js"), 1);
129
+ function processInputPath(path, input, context) {
130
+ if (path === void 0) {
131
+ return input;
132
+ }
133
+ if (path === null) {
134
+ return {};
135
+ }
136
+ return jsonPathQuery(path, input, context);
137
+ }
138
+ function processPayloadTemplate(payloadTemplate, json, context) {
139
+ const resolvedProperties = Object.entries(payloadTemplate).map(([key, value]) => {
140
+ let sanitizedKey = key;
141
+ let resolvedValue = value;
142
+ if (isPlainObj(value)) {
143
+ resolvedValue = processPayloadTemplate(value, json);
144
+ }
145
+ if (key.endsWith(".$") && typeof value === "string") {
146
+ sanitizedKey = key.replace(".$", "");
147
+ resolvedValue = jsonPathQuery(value, json, context);
148
+ }
149
+ return [sanitizedKey, resolvedValue];
150
+ });
151
+ return Object.fromEntries(resolvedProperties);
152
+ }
153
+ function processResultPath(path, rawInput, result) {
154
+ if (path === void 0) {
155
+ return result;
156
+ }
157
+ if (path === null) {
158
+ return rawInput;
159
+ }
160
+ const sanitizedPath = path.replace("$.", "");
161
+ if (isPlainObj(rawInput)) {
162
+ const clonedRawInput = (0, import_cloneDeep.default)(rawInput);
163
+ return (0, import_set.default)(clonedRawInput, sanitizedPath, result);
164
+ }
165
+ throw new StatesResultPathMatchFailureError();
166
+ }
167
+ function processOutputPath(path, result, context) {
168
+ if (path === void 0) {
169
+ return result;
170
+ }
171
+ if (path === null) {
172
+ return {};
173
+ }
174
+ return jsonPathQuery(path, result, context);
175
+ }
176
+
177
+ // src/stateMachine/stateActions/BaseStateAction.ts
178
+ var BaseStateAction = class {
179
+ constructor(stateDefinition) {
180
+ this.stateDefinition = stateDefinition;
181
+ }
182
+ buildExecutionResult(stateResult) {
183
+ const executionResult = { stateResult, nextState: "", isEndState: false };
184
+ if ("Next" in this.stateDefinition) {
185
+ executionResult.nextState = this.stateDefinition.Next;
186
+ }
187
+ if ("End" in this.stateDefinition) {
188
+ executionResult.isEndState = this.stateDefinition.End;
189
+ }
190
+ return executionResult;
191
+ }
192
+ };
193
+
194
+ // src/error/predefined/StatesNoChoiceMatchedError.ts
195
+ var StatesNoChoiceMatchedError = class extends RuntimeError {
196
+ constructor() {
197
+ super("States.NoChoiceMatched");
198
+ this.name = "States.NoChoiceMatched";
199
+ }
200
+ };
201
+
202
+ // src/stateMachine/stateActions/ChoiceStateAction.ts
203
+ var import_wildcard_match = __toESM(require("wildcard-match"), 1);
204
+ var ChoiceStateAction = class extends BaseStateAction {
205
+ constructor(stateDefinition) {
206
+ super(stateDefinition);
207
+ }
208
+ testChoiceRule(choiceRule, input) {
209
+ if ("And" in choiceRule) {
210
+ return choiceRule.And.every((rule) => this.testChoiceRule(rule, input));
211
+ }
212
+ if ("Or" in choiceRule) {
213
+ return choiceRule.Or.some((rule) => this.testChoiceRule(rule, input));
214
+ }
215
+ if ("Not" in choiceRule) {
216
+ return !this.testChoiceRule(choiceRule.Not, input);
217
+ }
218
+ if ("StringEquals" in choiceRule) {
219
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
220
+ return varValue === choiceRule.StringEquals;
221
+ }
222
+ if ("StringEqualsPath" in choiceRule) {
223
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
224
+ const stringValue = jsonPathQuery(choiceRule.StringEqualsPath, input);
225
+ return varValue === stringValue;
226
+ }
227
+ if ("StringLessThan" in choiceRule) {
228
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
229
+ return varValue < choiceRule.StringLessThan;
230
+ }
231
+ if ("StringLessThanPath" in choiceRule) {
232
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
233
+ const stringValue = jsonPathQuery(choiceRule.StringLessThanPath, input);
234
+ return varValue < stringValue;
235
+ }
236
+ if ("StringGreaterThan" in choiceRule) {
237
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
238
+ return varValue > choiceRule.StringGreaterThan;
239
+ }
240
+ if ("StringGreaterThanPath" in choiceRule) {
241
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
242
+ const stringValue = jsonPathQuery(choiceRule.StringGreaterThanPath, input);
243
+ return varValue > stringValue;
244
+ }
245
+ if ("StringLessThanEquals" in choiceRule) {
246
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
247
+ return varValue <= choiceRule.StringLessThanEquals;
248
+ }
249
+ if ("StringLessThanEqualsPath" in choiceRule) {
250
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
251
+ const stringValue = jsonPathQuery(choiceRule.StringLessThanEqualsPath, input);
252
+ return varValue <= stringValue;
253
+ }
254
+ if ("StringGreaterThanEquals" in choiceRule) {
255
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
256
+ return varValue >= choiceRule.StringGreaterThanEquals;
257
+ }
258
+ if ("StringGreaterThanEqualsPath" in choiceRule) {
259
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
260
+ const stringValue = jsonPathQuery(choiceRule.StringGreaterThanEqualsPath, input);
261
+ return varValue >= stringValue;
262
+ }
263
+ if ("StringMatches" in choiceRule) {
264
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
265
+ const isMatch = (0, import_wildcard_match.default)(choiceRule.StringMatches, { separator: false });
266
+ return isMatch(varValue);
267
+ }
268
+ if ("NumericEquals" in choiceRule) {
269
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
270
+ return varValue === choiceRule.NumericEquals;
271
+ }
272
+ if ("NumericEqualsPath" in choiceRule) {
273
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
274
+ const numberValue = jsonPathQuery(choiceRule.NumericEqualsPath, input);
275
+ return varValue === numberValue;
276
+ }
277
+ if ("NumericLessThan" in choiceRule) {
278
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
279
+ return varValue < choiceRule.NumericLessThan;
280
+ }
281
+ if ("NumericLessThanPath" in choiceRule) {
282
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
283
+ const numberValue = jsonPathQuery(choiceRule.NumericLessThanPath, input);
284
+ return varValue < numberValue;
285
+ }
286
+ if ("NumericGreaterThan" in choiceRule) {
287
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
288
+ return varValue > choiceRule.NumericGreaterThan;
289
+ }
290
+ if ("NumericGreaterThanPath" in choiceRule) {
291
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
292
+ const numberValue = jsonPathQuery(choiceRule.NumericGreaterThanPath, input);
293
+ return varValue > numberValue;
294
+ }
295
+ if ("NumericLessThanEquals" in choiceRule) {
296
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
297
+ return varValue <= choiceRule.NumericLessThanEquals;
298
+ }
299
+ if ("NumericLessThanEqualsPath" in choiceRule) {
300
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
301
+ const numberValue = jsonPathQuery(choiceRule.NumericLessThanEqualsPath, input);
302
+ return varValue <= numberValue;
303
+ }
304
+ if ("NumericGreaterThanEquals" in choiceRule) {
305
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
306
+ return varValue >= choiceRule.NumericGreaterThanEquals;
307
+ }
308
+ if ("NumericGreaterThanEqualsPath" in choiceRule) {
309
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
310
+ const numberValue = jsonPathQuery(choiceRule.NumericGreaterThanEqualsPath, input);
311
+ return varValue >= numberValue;
312
+ }
313
+ if ("BooleanEquals" in choiceRule) {
314
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
315
+ return varValue === choiceRule.BooleanEquals;
316
+ }
317
+ if ("BooleanEqualsPath" in choiceRule) {
318
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
319
+ const booleanValue = jsonPathQuery(choiceRule.BooleanEqualsPath, input);
320
+ return varValue === booleanValue;
321
+ }
322
+ if ("TimestampEquals" in choiceRule) {
323
+ const varValue = new Date(jsonPathQuery(choiceRule.Variable, input));
324
+ const timestampValue = new Date(choiceRule.TimestampEquals);
325
+ return varValue.getTime() === timestampValue.getTime();
326
+ }
327
+ if ("TimestampEqualsPath" in choiceRule) {
328
+ const varValue = new Date(jsonPathQuery(choiceRule.Variable, input));
329
+ const timestampValue = new Date(jsonPathQuery(choiceRule.TimestampEqualsPath, input));
330
+ return varValue.getTime() === timestampValue.getTime();
331
+ }
332
+ if ("TimestampLessThan" in choiceRule) {
333
+ const varValue = new Date(jsonPathQuery(choiceRule.Variable, input));
334
+ const timestampValue = new Date(choiceRule.TimestampLessThan);
335
+ return varValue < timestampValue;
336
+ }
337
+ if ("TimestampLessThanPath" in choiceRule) {
338
+ const varValue = new Date(jsonPathQuery(choiceRule.Variable, input));
339
+ const timestampValue = new Date(jsonPathQuery(choiceRule.TimestampLessThanPath, input));
340
+ return varValue < timestampValue;
341
+ }
342
+ if ("TimestampGreaterThan" in choiceRule) {
343
+ const varValue = new Date(jsonPathQuery(choiceRule.Variable, input));
344
+ const timestampValue = new Date(choiceRule.TimestampGreaterThan);
345
+ return varValue > timestampValue;
346
+ }
347
+ if ("TimestampGreaterThanPath" in choiceRule) {
348
+ const varValue = new Date(jsonPathQuery(choiceRule.Variable, input));
349
+ const timestampValue = new Date(jsonPathQuery(choiceRule.TimestampGreaterThanPath, input));
350
+ return varValue > timestampValue;
351
+ }
352
+ if ("TimestampLessThanEquals" in choiceRule) {
353
+ const varValue = new Date(jsonPathQuery(choiceRule.Variable, input));
354
+ const timestampValue = new Date(choiceRule.TimestampLessThanEquals);
355
+ return varValue <= timestampValue;
356
+ }
357
+ if ("TimestampLessThanEqualsPath" in choiceRule) {
358
+ const varValue = new Date(jsonPathQuery(choiceRule.Variable, input));
359
+ const timestampValue = new Date(jsonPathQuery(choiceRule.TimestampLessThanEqualsPath, input));
360
+ return varValue <= timestampValue;
361
+ }
362
+ if ("TimestampGreaterThanEquals" in choiceRule) {
363
+ const varValue = new Date(jsonPathQuery(choiceRule.Variable, input));
364
+ const timestampValue = new Date(choiceRule.TimestampGreaterThanEquals);
365
+ return varValue >= timestampValue;
366
+ }
367
+ if ("TimestampGreaterThanEqualsPath" in choiceRule) {
368
+ const varValue = new Date(jsonPathQuery(choiceRule.Variable, input));
369
+ const timestampValue = new Date(jsonPathQuery(choiceRule.TimestampGreaterThanEqualsPath, input));
370
+ return varValue >= timestampValue;
371
+ }
372
+ if ("IsNull" in choiceRule) {
373
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
374
+ const isNullTrue = choiceRule.IsNull;
375
+ return isNullTrue && varValue === null;
376
+ }
377
+ if ("IsPresent" in choiceRule) {
378
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
379
+ const IsPresentTrue = choiceRule.IsPresent;
380
+ return IsPresentTrue && varValue !== void 0;
381
+ }
382
+ if ("IsNumeric" in choiceRule) {
383
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
384
+ const IsNumericTrue = choiceRule.IsNumeric;
385
+ return IsNumericTrue && typeof varValue === "number";
386
+ }
387
+ if ("IsString" in choiceRule) {
388
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
389
+ const IsStringTrue = choiceRule.IsString;
390
+ return IsStringTrue && typeof varValue === "string";
391
+ }
392
+ if ("IsBoolean" in choiceRule) {
393
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
394
+ const IsBooleanTrue = choiceRule.IsBoolean;
395
+ return IsBooleanTrue && typeof varValue === "boolean";
396
+ }
397
+ if ("IsTimestamp" in choiceRule) {
398
+ const varValue = jsonPathQuery(choiceRule.Variable, input);
399
+ const IsTimestampTrue = choiceRule.IsTimestamp;
400
+ return IsTimestampTrue && /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(Z|(\+|-)\d{2}:\d{2})/.test(varValue);
401
+ }
402
+ return false;
403
+ }
404
+ async execute(input, context, options) {
405
+ const state = this.stateDefinition;
406
+ for (const choice of state.Choices) {
407
+ const choiceIsMatch = this.testChoiceRule(choice, input);
408
+ if (choiceIsMatch) {
409
+ return { stateResult: input, nextState: choice.Next, isEndState: false };
410
+ }
411
+ }
412
+ if (state.Default) {
413
+ return { stateResult: input, nextState: state.Default, isEndState: false };
414
+ }
415
+ throw new StatesNoChoiceMatchedError();
416
+ }
417
+ };
418
+
419
+ // src/error/FailStateError.ts
420
+ var FailStateError = class extends RuntimeError {
421
+ constructor(name = "FailStateError", message = "Execution failed because of a Fail state") {
422
+ super(message);
423
+ this.name = name;
424
+ }
425
+ };
426
+
427
+ // src/stateMachine/stateActions/FailStateAction.ts
428
+ var FailStateAction = class extends BaseStateAction {
429
+ constructor(stateDefinition) {
430
+ super(stateDefinition);
431
+ }
432
+ async execute(input, context, options) {
433
+ throw new FailStateError(this.stateDefinition.Error, this.stateDefinition.Cause);
434
+ }
435
+ };
436
+
437
+ // src/error/predefined/StatesRuntimeError.ts
438
+ var StatesRuntimeError = class extends RuntimeError {
439
+ constructor(message = "States.Runtime") {
440
+ super(message);
441
+ this.name = "States.Runtime";
442
+ this.retryable = false;
443
+ this.catchable = false;
444
+ }
445
+ };
446
+
447
+ // src/stateMachine/stateActions/MapStateAction.ts
448
+ var import_p_limit = __toESM(require("p-limit"), 1);
449
+ var DEFAULT_MAX_CONCURRENCY = 40;
450
+ var MapStateAction = class extends BaseStateAction {
451
+ constructor(stateDefinition) {
452
+ super(stateDefinition);
453
+ this.executionAbortFuncs = [];
454
+ }
455
+ processItem(stateMachine, item, input, context, index, options) {
456
+ const state = this.stateDefinition;
457
+ let paramValue;
458
+ context["Map"] = {
459
+ Item: {
460
+ Index: index,
461
+ Value: item
462
+ }
463
+ };
464
+ if (state.Parameters) {
465
+ paramValue = processPayloadTemplate(state.Parameters, input, context);
466
+ }
467
+ const execution = stateMachine.run(paramValue ?? item, options?.runOptions);
468
+ this.executionAbortFuncs.push(execution.abort);
469
+ return execution.result;
470
+ }
471
+ async execute(input, context, options) {
472
+ const state = this.stateDefinition;
473
+ let items = input;
474
+ if (state.ItemsPath) {
475
+ items = jsonPathQuery(state.ItemsPath, input, context);
476
+ }
477
+ if (!Array.isArray(items)) {
478
+ throw new StatesRuntimeError("Input of Map state must be an array or ItemsPath property must point to an array");
479
+ }
480
+ const iteratorStateMachine = new StateMachine(state.Iterator, options?.validationOptions);
481
+ const limit = (0, import_p_limit.default)(state.MaxConcurrency || DEFAULT_MAX_CONCURRENCY);
482
+ const processedItemsPromise = items.map(
483
+ (item, i) => limit(() => this.processItem(iteratorStateMachine, item, input, context, i, options))
484
+ );
485
+ try {
486
+ const result = await Promise.all(processedItemsPromise);
487
+ return this.buildExecutionResult(result);
488
+ } catch (error) {
489
+ this.executionAbortFuncs.forEach((abort) => abort());
490
+ if (error instanceof ExecutionError) {
491
+ throw error.getWrappedError;
492
+ }
493
+ throw error;
494
+ } finally {
495
+ delete context["Map"];
496
+ }
497
+ }
498
+ };
499
+
500
+ // src/stateMachine/stateActions/PassStateAction.ts
501
+ var PassStateAction = class extends BaseStateAction {
502
+ constructor(stateDefinition) {
503
+ super(stateDefinition);
504
+ }
505
+ async execute(input, context, options) {
506
+ if (this.stateDefinition.Result) {
507
+ return this.buildExecutionResult(this.stateDefinition.Result);
508
+ }
509
+ return this.buildExecutionResult(input);
510
+ }
511
+ };
512
+
513
+ // src/stateMachine/stateActions/SucceedStateAction.ts
514
+ var SucceedStateAction = class extends BaseStateAction {
515
+ constructor(stateDefinition) {
516
+ super(stateDefinition);
517
+ }
518
+ async execute(input, context, options) {
519
+ return { stateResult: input, nextState: "", isEndState: true };
520
+ }
521
+ };
522
+
523
+ // src/aws/LambdaClient.ts
524
+ var import_client_lambda = require("@aws-sdk/client-lambda");
525
+ var LambdaClient = class {
526
+ constructor(config) {
527
+ this.client = new import_client_lambda.LambdaClient(config ?? {});
528
+ }
529
+ async invokeFunction(funcNameOrArn, payload) {
530
+ const payloadBuffer = Buffer.from(JSON.stringify(payload));
531
+ const invokeCommand = new import_client_lambda.InvokeCommand({
532
+ FunctionName: funcNameOrArn,
533
+ Payload: payloadBuffer
534
+ });
535
+ const invocationResult = await this.client.send(invokeCommand);
536
+ let resultValue = null;
537
+ if (invocationResult.Payload) {
538
+ resultValue = Buffer.from(invocationResult.Payload).toString();
539
+ resultValue = JSON.parse(resultValue);
540
+ }
541
+ if (invocationResult.FunctionError) {
542
+ const errorResult = resultValue;
543
+ throw new FailStateError(errorResult.errorType, `Execution of Lambda function "${funcNameOrArn}" failed`);
544
+ }
545
+ return resultValue;
546
+ }
547
+ };
548
+
549
+ // src/stateMachine/stateActions/TaskStateAction.ts
550
+ var TaskStateAction = class extends BaseStateAction {
551
+ constructor(stateDefinition) {
552
+ super(stateDefinition);
553
+ }
554
+ async execute(input, context, options) {
555
+ const state = this.stateDefinition;
556
+ if (options?.overrideFn) {
557
+ const result2 = await options.overrideFn(input);
558
+ return this.buildExecutionResult(result2);
559
+ }
560
+ const lambdaClient = new LambdaClient();
561
+ const result = await lambdaClient.invokeFunction(state.Resource, input);
562
+ return this.buildExecutionResult(result);
563
+ }
564
+ };
565
+
566
+ // src/stateMachine/stateActions/WaitStateAction.ts
567
+ var WaitStateAction = class extends BaseStateAction {
568
+ constructor(stateDefinition) {
569
+ super(stateDefinition);
570
+ }
571
+ async execute(input, context, options) {
572
+ const state = this.stateDefinition;
573
+ if (options?.waitTimeOverrideOption !== void 0) {
574
+ await sleep(options.waitTimeOverrideOption, options.abortSignal);
575
+ return this.buildExecutionResult(input);
576
+ }
577
+ if (state.Seconds) {
578
+ await sleep(state.Seconds * 1e3, options?.abortSignal);
579
+ } else if (state.Timestamp) {
580
+ const dateTimestamp = new Date(state.Timestamp);
581
+ const currentTime = Date.now();
582
+ const timeDiff = dateTimestamp.getTime() - currentTime;
583
+ await sleep(timeDiff, options?.abortSignal);
584
+ } else if (state.SecondsPath) {
585
+ const seconds = jsonPathQuery(state.SecondsPath, input, context);
586
+ await sleep(seconds * 1e3, options?.abortSignal);
587
+ } else if (state.TimestampPath) {
588
+ const timestamp = jsonPathQuery(state.TimestampPath, input, context);
589
+ const dateTimestamp = new Date(timestamp);
590
+ const currentTime = Date.now();
591
+ const timeDiff = dateTimestamp.getTime() - currentTime;
592
+ await sleep(timeDiff, options?.abortSignal);
593
+ }
594
+ return this.buildExecutionResult(input);
595
+ }
596
+ };
597
+
598
+ // src/error/predefined/StatesTimeoutError.ts
599
+ var StatesTimeoutError = class extends RuntimeError {
600
+ constructor() {
601
+ super("States.Timeout");
602
+ this.name = "States.Timeout";
603
+ }
604
+ };
605
+
606
+ // src/stateMachine/StateExecutor.ts
607
+ var import_cloneDeep2 = __toESM(require("lodash/cloneDeep.js"), 1);
608
+ var DEFAULT_MAX_ATTEMPTS = 3;
609
+ var DEFAULT_INTERVAL_SECONDS = 1;
610
+ var DEFAULT_BACKOFF_RATE = 2;
611
+ var WILDCARD_ERROR = "States.ALL";
612
+ var TASK_STATE_WILDCARD_ERROR = "States.TaskFailed";
613
+ var StateExecutor = class {
614
+ constructor(stateName, stateDefinition) {
615
+ this.stateName = stateName;
616
+ this.stateDefinition = stateDefinition;
617
+ this.retrierAttempts = "Retry" in this.stateDefinition ? new Array(this.stateDefinition.Retry.length).fill(0) : [];
618
+ this.stateHandlers = {
619
+ Task: this.executeTaskState,
620
+ Map: this.executeMapState,
621
+ Pass: this.executePassState,
622
+ Wait: this.executeWaitState,
623
+ Choice: this.executeChoiceState,
624
+ Succeed: this.executeSucceedState,
625
+ Fail: this.executeFailState
626
+ };
627
+ }
628
+ /**
629
+ * Execute the current state.
630
+ */
631
+ async execute(input, context, options) {
632
+ const rawInput = (0, import_cloneDeep2.default)(input);
633
+ try {
634
+ const processedInput = this.processInput(input, context);
635
+ const {
636
+ stateResult: currResult,
637
+ nextState,
638
+ isEndState
639
+ } = await this.stateHandlers[this.stateDefinition.Type](
640
+ // @ts-expect-error Indexing `this.stateActions` by non-literal value produces a `never` type for the `this.stateDefinition` parameter of the handler being called
641
+ this.stateDefinition,
642
+ processedInput,
643
+ context,
644
+ this.stateName,
645
+ options
646
+ );
647
+ const processedResult = this.processResult(currResult, rawInput, context);
648
+ return { stateResult: processedResult, nextState, isEndState };
649
+ } catch (error) {
650
+ const { shouldRetry, waitTimeBeforeRetry } = this.shouldRetry(error);
651
+ if (shouldRetry && waitTimeBeforeRetry) {
652
+ await sleep(waitTimeBeforeRetry, options.abortSignal);
653
+ return this.execute(input, context, options);
654
+ }
655
+ const { nextState, errorOutput, resultPath } = this.catchError(error);
656
+ if (nextState && errorOutput) {
657
+ return { stateResult: processResultPath(resultPath, rawInput, errorOutput), nextState, isEndState: false };
658
+ }
659
+ throw error;
660
+ }
661
+ }
662
+ /**
663
+ * Process the current input according to the `InputPath` and `Parameters` fields.
664
+ */
665
+ processInput(input, context) {
666
+ let processedInput = input;
667
+ if ("InputPath" in this.stateDefinition) {
668
+ processedInput = processInputPath(this.stateDefinition.InputPath, processedInput, context);
669
+ }
670
+ if ("Parameters" in this.stateDefinition && this.stateDefinition.Type !== "Map") {
671
+ processedInput = processPayloadTemplate(this.stateDefinition.Parameters, processedInput, context);
672
+ }
673
+ return processedInput;
674
+ }
675
+ /**
676
+ * Process the current result according to the `ResultSelector`, `ResultPath` and `OutputPath` fields.
677
+ */
678
+ processResult(result, rawInput, context) {
679
+ let processedResult = result;
680
+ if ("ResultSelector" in this.stateDefinition) {
681
+ processedResult = processPayloadTemplate(this.stateDefinition.ResultSelector, processedResult, context);
682
+ }
683
+ if ("ResultPath" in this.stateDefinition) {
684
+ processedResult = processResultPath(this.stateDefinition.ResultPath, rawInput, processedResult);
685
+ }
686
+ if ("OutputPath" in this.stateDefinition) {
687
+ processedResult = processOutputPath(this.stateDefinition.OutputPath, processedResult, context);
688
+ }
689
+ return processedResult;
690
+ }
691
+ /**
692
+ * Decide whether this state should be retried, according to the `Retry` field.
693
+ */
694
+ shouldRetry(error) {
695
+ if (!("Retry" in this.stateDefinition)) {
696
+ return { shouldRetry: false };
697
+ }
698
+ for (let i = 0; i < this.stateDefinition.Retry.length; i++) {
699
+ const retrier = this.stateDefinition.Retry[i];
700
+ const maxAttempts = retrier.MaxAttempts ?? DEFAULT_MAX_ATTEMPTS;
701
+ const intervalSeconds = retrier.IntervalSeconds ?? DEFAULT_INTERVAL_SECONDS;
702
+ const backoffRate = retrier.BackoffRate ?? DEFAULT_BACKOFF_RATE;
703
+ const waitTimeBeforeRetry = intervalSeconds * Math.pow(backoffRate, this.retrierAttempts[i]) * 1e3;
704
+ const retryable = error.isRetryable ?? true;
705
+ for (const retrierError of retrier.ErrorEquals) {
706
+ const isErrorMatch = retrierError === error.name;
707
+ const isErrorWildcard = retrierError === WILDCARD_ERROR;
708
+ const isErrorTaskWildcard = retrierError === TASK_STATE_WILDCARD_ERROR && this.stateDefinition.Type === "Task" && !(error instanceof StatesTimeoutError);
709
+ const maybeShouldRetry = retryable && (isErrorMatch || isErrorWildcard || isErrorTaskWildcard);
710
+ if (maybeShouldRetry) {
711
+ if (this.retrierAttempts[i] >= maxAttempts)
712
+ return { shouldRetry: false };
713
+ this.retrierAttempts[i]++;
714
+ return { shouldRetry: true, waitTimeBeforeRetry };
715
+ }
716
+ }
717
+ }
718
+ return { shouldRetry: false };
719
+ }
720
+ /**
721
+ * Try to match the current error with a catcher, according to the `Catch` field.
722
+ */
723
+ catchError(error) {
724
+ if (!("Catch" in this.stateDefinition)) {
725
+ return { nextState: "" };
726
+ }
727
+ for (let i = 0; i < this.stateDefinition.Catch.length; i++) {
728
+ const catcher = this.stateDefinition.Catch[i];
729
+ const catchable = error.isCatchable ?? true;
730
+ for (const catcherError of catcher.ErrorEquals) {
731
+ const isErrorMatch = catcherError === error.name;
732
+ const isErrorWildcard = catcherError === WILDCARD_ERROR;
733
+ const isErrorTaskWildcard = catcherError === TASK_STATE_WILDCARD_ERROR && this.stateDefinition.Type === "Task" && !(error instanceof StatesTimeoutError);
734
+ const shouldCatch = catchable && (isErrorMatch || isErrorWildcard || isErrorTaskWildcard);
735
+ if (shouldCatch) {
736
+ const nextState = catcher.Next;
737
+ const errorOutput = {
738
+ Error: error.name,
739
+ Cause: error.message
740
+ };
741
+ const resultPath = catcher.ResultPath;
742
+ return { nextState, errorOutput, resultPath };
743
+ }
744
+ }
745
+ }
746
+ return { nextState: "" };
747
+ }
748
+ /**
749
+ * Handler for task states.
750
+ *
751
+ * Invokes the Lambda function specified in the `Resource` field
752
+ * and sets the current result of the state machine to the value returned by the Lambda.
753
+ */
754
+ async executeTaskState(stateDefinition, input, context, stateName, options) {
755
+ const overrideFn = options.runOptions?.overrides?.taskResourceLocalHandlers?.[stateName];
756
+ const taskStateAction = new TaskStateAction(stateDefinition);
757
+ const executionResult = await taskStateAction.execute(input, context, { overrideFn });
758
+ return executionResult;
759
+ }
760
+ /**
761
+ * Handler for map states.
762
+ *
763
+ * Iterates over the current input items or the items of an array specified
764
+ * by the `ItemsPath` field, and then processes each item by passing it
765
+ * as the input to the state machine specified in the `Iterator` field.
766
+ */
767
+ async executeMapState(stateDefinition, input, context, stateName, options) {
768
+ const mapStateAction = new MapStateAction(stateDefinition);
769
+ const executionResult = await mapStateAction.execute(input, context, {
770
+ validationOptions: options.validationOptions,
771
+ runOptions: options.runOptions
772
+ });
773
+ return executionResult;
774
+ }
775
+ /**
776
+ * Handler for pass states.
777
+ *
778
+ * If the `Result` field is specified, copies `Result` into the current result.
779
+ * Else, copies the current input into the current result.
780
+ */
781
+ async executePassState(stateDefinition, input, context, stateName, options) {
782
+ const passStateAction = new PassStateAction(stateDefinition);
783
+ const executionResult = await passStateAction.execute(input, context);
784
+ return executionResult;
785
+ }
786
+ /**
787
+ * Handler for wait states.
788
+ *
789
+ * Pauses the state machine execution for a certain amount of time
790
+ * based on one of the `Seconds`, `Timestamp`, `SecondsPath` or `TimestampPath` fields.
791
+ */
792
+ async executeWaitState(stateDefinition, input, context, stateName, options) {
793
+ const waitTimeOverrideOption = options.runOptions?.overrides?.waitTimeOverrides?.[stateName];
794
+ const abortSignal = options.abortSignal;
795
+ const waitStateAction = new WaitStateAction(stateDefinition);
796
+ const executionResult = await waitStateAction.execute(input, context, {
797
+ waitTimeOverrideOption,
798
+ abortSignal
799
+ });
800
+ return executionResult;
801
+ }
802
+ /**
803
+ * Handler for choice states.
804
+ *
805
+ * Evaluates each choice rule specified in the `Choices` field.
806
+ *
807
+ * If one of the rules matches, then the state machine transitions to the
808
+ * state specified in the `Next` field for that choice rule.
809
+ *
810
+ * If no rule matches but the `Default` field is specified,
811
+ * then the next state will be the state specified in said field.
812
+ *
813
+ * If no rule matches and the `Default` field is not specified, throws a
814
+ * States.NoChoiceMatched error.
815
+ */
816
+ async executeChoiceState(stateDefinition, input, context, stateName, options) {
817
+ const choiceStateAction = new ChoiceStateAction(stateDefinition);
818
+ const executionResult = await choiceStateAction.execute(input, context);
819
+ return executionResult;
820
+ }
821
+ /**
822
+ * Handler for succeed states.
823
+ *
824
+ * Ends the state machine execution successfully.
825
+ */
826
+ async executeSucceedState(stateDefinition, input, context, stateName, options) {
827
+ const succeedStateAction = new SucceedStateAction(stateDefinition);
828
+ const executionResult = await succeedStateAction.execute(input, context);
829
+ return executionResult;
830
+ }
831
+ /**
832
+ * Handler for fail states.
833
+ *
834
+ * Ends the state machine execution and marks it as a failure.
835
+ */
836
+ async executeFailState(stateDefinition, input, context, stateName, options) {
837
+ const failStateAction = new FailStateAction(stateDefinition);
838
+ const executionResult = await failStateAction.execute(input, context);
839
+ return executionResult;
840
+ }
841
+ };
842
+
843
+ // src/stateMachine/StateMachine.ts
844
+ var import_asl_validator = __toESM(require("asl-validator"), 1);
845
+ var import_cloneDeep3 = __toESM(require("lodash/cloneDeep.js"), 1);
846
+ var StateMachine = class {
847
+ /**
848
+ * Constructs a new state machine.
849
+ * @param definition The state machine definition defined using the Amazon States Language (https://states-language.net/spec.html).
850
+ * @param validationOptions Options to control whether to apply certain validations to the definition.
851
+ * These options also apply to state machines defined in the `Iterator` field of `Map` states.
852
+ */
853
+ constructor(definition, validationOptions) {
854
+ const { isValid, errorsText } = (0, import_asl_validator.default)(definition, {
855
+ checkArn: true,
856
+ checkPaths: true,
857
+ ...validationOptions
858
+ });
859
+ if (!isValid) {
860
+ throw new Error(`State machine definition is invalid, see error(s) below:
861
+ ${errorsText("\n")}`);
862
+ }
863
+ this.definition = definition;
864
+ this.validationOptions = validationOptions;
865
+ }
866
+ /**
867
+ * Executes the state machine, running through the states specified in the definition.
868
+ * If the execution fails, the result will throw an `ExecutionError` explaining why the
869
+ * execution failed.
870
+ *
871
+ * By default, if the execution is aborted, the result will throw an `ExecutionAbortedError`. This behavior can be changed by setting
872
+ * the `noThrowOnAbort` option to `true`, in which case the result will be `null`.
873
+ *
874
+ * @param input The input to pass to this state machine execution.
875
+ * @param options Miscellaneous options to control certain behaviors of the execution.
876
+ */
877
+ run(input, options) {
878
+ const abortController = new AbortController();
879
+ const settleOnAbort = new Promise((resolve, reject) => {
880
+ if (options?.noThrowOnAbort) {
881
+ abortController.signal.addEventListener("abort", () => resolve(null));
882
+ } else {
883
+ abortController.signal.addEventListener("abort", () => reject(new ExecutionAbortedError()));
884
+ }
885
+ });
886
+ const executionResult = this.execute(input, {
887
+ validationOptions: this.validationOptions,
888
+ runOptions: options,
889
+ abortSignal: abortController.signal
890
+ });
891
+ const result = Promise.race([executionResult, settleOnAbort]);
892
+ return {
893
+ abort: () => abortController.abort(),
894
+ result
895
+ };
896
+ }
897
+ /**
898
+ * Helper method that handles the execution of the machine states and the transitions between them.
899
+ */
900
+ async execute(input, options) {
901
+ let currState = this.definition.States[this.definition.StartAt];
902
+ let currStateName = this.definition.StartAt;
903
+ let currInput = (0, import_cloneDeep3.default)(input);
904
+ let currResult = null;
905
+ let nextState = "";
906
+ let isEndState = false;
907
+ let context = {};
908
+ try {
909
+ do {
910
+ const stateExecutor = new StateExecutor(currStateName, currState);
911
+ ({ stateResult: currResult, nextState, isEndState } = await stateExecutor.execute(currInput, context, options));
912
+ currInput = currResult;
913
+ currState = this.definition.States[nextState];
914
+ currStateName = nextState;
915
+ } while (!isEndState && !options.abortSignal.aborted);
916
+ } catch (error) {
917
+ throw new ExecutionError(error);
918
+ }
919
+ return currResult;
920
+ }
921
+ };
922
+ // Annotate the CommonJS export names for ESM import in node:
923
+ 0 && (module.exports = {
924
+ ExecutionAbortedError,
925
+ ExecutionError,
926
+ StateMachine
927
+ });