awaitly 1.35.0 → 2.0.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/dist/{duration.d.ts → di-BDlT7InM.d.cts} +15 -1
- package/dist/{duration.d.cts → di-BbFFfO8y.d.ts} +15 -1
- package/dist/errors-DtXvrCiO.d.cts +708 -0
- package/dist/errors-DtXvrCiO.d.ts +708 -0
- package/dist/index.cjs +4594 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1970 -141
- package/dist/index.d.ts +1970 -141
- package/dist/index.js +4398 -1
- package/dist/index.js.map +1 -1
- package/dist/result.cjs +641 -1
- package/dist/result.cjs.map +1 -1
- package/dist/result.d.cts +29 -4
- package/dist/result.d.ts +29 -4
- package/dist/result.js +561 -1
- package/dist/result.js.map +1 -1
- package/dist/testing.cjs +4202 -8
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +2 -6
- package/dist/testing.d.ts +2 -6
- package/dist/testing.js +4154 -8
- package/dist/testing.js.map +1 -1
- package/dist/{run-entry-DGs0tySr.d.cts → types-B8NfNRGX.d.ts} +1078 -1502
- package/dist/{run-entry-BOuNyVoO.d.ts → types-BZ2f4MRR.d.cts} +1078 -1502
- package/dist/workflow.cjs +7096 -6
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.d.cts +3346 -22
- package/dist/workflow.d.ts +3346 -22
- package/dist/workflow.js +6929 -6
- package/dist/workflow.js.map +1 -1
- package/package.json +3 -168
- package/dist/adapters.cjs +0 -7
- package/dist/adapters.cjs.map +0 -1
- package/dist/adapters.d.cts +0 -179
- package/dist/adapters.d.ts +0 -179
- package/dist/adapters.js +0 -7
- package/dist/adapters.js.map +0 -1
- package/dist/batch.cjs +0 -7
- package/dist/batch.cjs.map +0 -1
- package/dist/batch.d.cts +0 -200
- package/dist/batch.d.ts +0 -200
- package/dist/batch.js +0 -7
- package/dist/batch.js.map +0 -1
- package/dist/bind-deps.cjs +0 -2
- package/dist/bind-deps.cjs.map +0 -1
- package/dist/bind-deps.d.cts +0 -28
- package/dist/bind-deps.d.ts +0 -28
- package/dist/bind-deps.js +0 -2
- package/dist/bind-deps.js.map +0 -1
- package/dist/cache.cjs +0 -2
- package/dist/cache.cjs.map +0 -1
- package/dist/cache.d.cts +0 -269
- package/dist/cache.d.ts +0 -269
- package/dist/cache.js +0 -2
- package/dist/cache.js.map +0 -1
- package/dist/circuit-breaker.cjs +0 -7
- package/dist/circuit-breaker.cjs.map +0 -1
- package/dist/circuit-breaker.d.cts +0 -211
- package/dist/circuit-breaker.d.ts +0 -211
- package/dist/circuit-breaker.js +0 -7
- package/dist/circuit-breaker.js.map +0 -1
- package/dist/conditional.cjs +0 -2
- package/dist/conditional.cjs.map +0 -1
- package/dist/conditional.d.cts +0 -252
- package/dist/conditional.d.ts +0 -252
- package/dist/conditional.js +0 -2
- package/dist/conditional.js.map +0 -1
- package/dist/core.cjs +0 -7
- package/dist/core.cjs.map +0 -1
- package/dist/core.d.cts +0 -5
- package/dist/core.d.ts +0 -5
- package/dist/core.js +0 -7
- package/dist/core.js.map +0 -1
- package/dist/di-By77n4Fa.d.ts +0 -15
- package/dist/di-OJfsohf-.d.cts +0 -15
- package/dist/diagnostics.cjs +0 -8
- package/dist/diagnostics.cjs.map +0 -1
- package/dist/diagnostics.d.cts +0 -68
- package/dist/diagnostics.d.ts +0 -68
- package/dist/diagnostics.js +0 -8
- package/dist/diagnostics.js.map +0 -1
- package/dist/durable.cjs +0 -11
- package/dist/durable.cjs.map +0 -1
- package/dist/durable.d.cts +0 -9
- package/dist/durable.d.ts +0 -9
- package/dist/durable.js +0 -11
- package/dist/durable.js.map +0 -1
- package/dist/duration.cjs +0 -2
- package/dist/duration.cjs.map +0 -1
- package/dist/duration.js +0 -2
- package/dist/duration.js.map +0 -1
- package/dist/engine.cjs +0 -11
- package/dist/engine.cjs.map +0 -1
- package/dist/engine.d.cts +0 -115
- package/dist/engine.d.ts +0 -115
- package/dist/engine.js +0 -11
- package/dist/engine.js.map +0 -1
- package/dist/errors.cjs +0 -2
- package/dist/errors.cjs.map +0 -1
- package/dist/errors.d.cts +0 -361
- package/dist/errors.d.ts +0 -361
- package/dist/errors.js +0 -2
- package/dist/errors.js.map +0 -1
- package/dist/fetch.cjs +0 -7
- package/dist/fetch.cjs.map +0 -1
- package/dist/fetch.d.cts +0 -86
- package/dist/fetch.d.ts +0 -86
- package/dist/fetch.js +0 -7
- package/dist/fetch.js.map +0 -1
- package/dist/flow.cjs +0 -7
- package/dist/flow.cjs.map +0 -1
- package/dist/flow.d.cts +0 -163
- package/dist/flow.d.ts +0 -163
- package/dist/flow.js +0 -7
- package/dist/flow.js.map +0 -1
- package/dist/functional.cjs +0 -2
- package/dist/functional.cjs.map +0 -1
- package/dist/functional.d.cts +0 -444
- package/dist/functional.d.ts +0 -444
- package/dist/functional.js +0 -2
- package/dist/functional.js.map +0 -1
- package/dist/guards-4sV7mTqj.d.cts +0 -72
- package/dist/guards-BIX05ALH.d.ts +0 -72
- package/dist/hitl-DFn4Xa_l.d.cts +0 -468
- package/dist/hitl-DU5VpKq7.d.ts +0 -468
- package/dist/hitl.cjs +0 -7
- package/dist/hitl.cjs.map +0 -1
- package/dist/hitl.d.cts +0 -442
- package/dist/hitl.d.ts +0 -442
- package/dist/hitl.js +0 -7
- package/dist/hitl.js.map +0 -1
- package/dist/index-CnvBryQB.d.ts +0 -417
- package/dist/index-DEZEf8Fs.d.cts +0 -417
- package/dist/match-entry-DjI2bLpD.d.cts +0 -209
- package/dist/match-entry-DjI2bLpD.d.ts +0 -209
- package/dist/match.cjs +0 -2
- package/dist/match.cjs.map +0 -1
- package/dist/match.d.cts +0 -1
- package/dist/match.d.ts +0 -1
- package/dist/match.js +0 -2
- package/dist/match.js.map +0 -1
- package/dist/otel.cjs +0 -2
- package/dist/otel.cjs.map +0 -1
- package/dist/otel.d.cts +0 -188
- package/dist/otel.d.ts +0 -188
- package/dist/otel.js +0 -2
- package/dist/otel.js.map +0 -1
- package/dist/persistence-entry-B-8PjnSR.d.cts +0 -831
- package/dist/persistence-entry-D8zRkLiT.d.ts +0 -831
- package/dist/persistence.cjs +0 -2
- package/dist/persistence.cjs.map +0 -1
- package/dist/persistence.d.cts +0 -7
- package/dist/persistence.d.ts +0 -7
- package/dist/persistence.js +0 -2
- package/dist/persistence.js.map +0 -1
- package/dist/policies.cjs +0 -2
- package/dist/policies.cjs.map +0 -1
- package/dist/policies.d.cts +0 -379
- package/dist/policies.d.ts +0 -379
- package/dist/policies.js +0 -2
- package/dist/policies.js.map +0 -1
- package/dist/ratelimit.cjs +0 -7
- package/dist/ratelimit.cjs.map +0 -1
- package/dist/ratelimit.d.cts +0 -458
- package/dist/ratelimit.d.ts +0 -458
- package/dist/ratelimit.js +0 -7
- package/dist/ratelimit.js.map +0 -1
- package/dist/reliability.cjs +0 -11
- package/dist/reliability.cjs.map +0 -1
- package/dist/reliability.d.cts +0 -11
- package/dist/reliability.d.ts +0 -11
- package/dist/reliability.js +0 -11
- package/dist/reliability.js.map +0 -1
- package/dist/resolver.cjs +0 -7
- package/dist/resolver.cjs.map +0 -1
- package/dist/resolver.d.cts +0 -68
- package/dist/resolver.d.ts +0 -68
- package/dist/resolver.js +0 -7
- package/dist/resolver.js.map +0 -1
- package/dist/resource.cjs +0 -7
- package/dist/resource.cjs.map +0 -1
- package/dist/resource.d.cts +0 -174
- package/dist/resource.d.ts +0 -174
- package/dist/resource.js +0 -7
- package/dist/resource.js.map +0 -1
- package/dist/result/retry.cjs +0 -2
- package/dist/result/retry.cjs.map +0 -1
- package/dist/result/retry.d.cts +0 -70
- package/dist/result/retry.d.ts +0 -70
- package/dist/result/retry.js +0 -2
- package/dist/result/retry.js.map +0 -1
- package/dist/retry.cjs +0 -2
- package/dist/retry.cjs.map +0 -1
- package/dist/retry.d.cts +0 -388
- package/dist/retry.d.ts +0 -388
- package/dist/retry.js +0 -2
- package/dist/retry.js.map +0 -1
- package/dist/run.cjs +0 -7
- package/dist/run.cjs.map +0 -1
- package/dist/run.d.cts +0 -4
- package/dist/run.d.ts +0 -4
- package/dist/run.js +0 -7
- package/dist/run.js.map +0 -1
- package/dist/saga.cjs +0 -11
- package/dist/saga.cjs.map +0 -1
- package/dist/saga.d.cts +0 -164
- package/dist/saga.d.ts +0 -164
- package/dist/saga.js +0 -11
- package/dist/saga.js.map +0 -1
- package/dist/singleflight.cjs +0 -2
- package/dist/singleflight.cjs.map +0 -1
- package/dist/singleflight.d.cts +0 -145
- package/dist/singleflight.d.ts +0 -145
- package/dist/singleflight.js +0 -2
- package/dist/singleflight.js.map +0 -1
- package/dist/slugs.cjs +0 -2
- package/dist/slugs.cjs.map +0 -1
- package/dist/slugs.d.cts +0 -67
- package/dist/slugs.d.ts +0 -67
- package/dist/slugs.js +0 -2
- package/dist/slugs.js.map +0 -1
- package/dist/streaming.cjs +0 -9
- package/dist/streaming.cjs.map +0 -1
- package/dist/streaming.d.cts +0 -596
- package/dist/streaming.d.ts +0 -596
- package/dist/streaming.js +0 -9
- package/dist/streaming.js.map +0 -1
- package/dist/tagged-error.cjs +0 -2
- package/dist/tagged-error.cjs.map +0 -1
- package/dist/tagged-error.d.cts +0 -275
- package/dist/tagged-error.d.ts +0 -275
- package/dist/tagged-error.js +0 -2
- package/dist/tagged-error.js.map +0 -1
- package/dist/types-BziYHFkD.d.ts +0 -323
- package/dist/types-C5jLEUqY.d.cts +0 -323
- package/dist/webhook.cjs +0 -7
- package/dist/webhook.cjs.map +0 -1
- package/dist/webhook.d.cts +0 -499
- package/dist/webhook.d.ts +0 -499
- package/dist/webhook.js +0 -7
- package/dist/webhook.js.map +0 -1
package/dist/testing.js
CHANGED
|
@@ -1,13 +1,4159 @@
|
|
|
1
|
-
var It={"step-require-id":"step-require-id","step-no-immediate-execution":"step-no-immediate-execution","step-require-thunk-for-key":"step-require-thunk-for-key","step-no-bare-await":"step-no-bare-await","step-no-try-catch-wrap":"step-no-try-catch-wrap","step-stable-cache-keys":"step-stable-cache-keys","workflow-no-floating":"workflow-no-floating","workflow-options-position":"workflow-options-position","workflow-callback-shape":"workflow-callback-shape","workflow-no-callable-form":"workflow-no-callable-form","workflow-no-dynamic-import":"workflow-no-dynamic-import","result-no-floating":"result-no-floating","result-require-handling":"result-require-handling","result-no-double-wrap":"result-no-double-wrap","result-no-manual-propagation":"result-no-manual-propagation","result-no-direct-ok-err":"result-no-direct-ok-err","error-check-unexpected-first":"error-check-unexpected-first","error-access-cause":"error-access-cause","error-normalize":"error-normalize","error-no-throw-in-deps":"error-no-throw-in-deps","concurrency-no-promise-all":"concurrency-no-promise-all","concurrency-no-promise-race":"concurrency-no-promise-race","concurrency-no-promise-allsettled":"concurrency-no-promise-allsettled","runtime-step-timeout":"runtime-step-timeout","runtime-step-aborted":"runtime-step-aborted","runtime-retry-exhausted":"runtime-retry-exhausted","runtime-rate-limit":"runtime-rate-limit","runtime-circuit-open":"runtime-circuit-open","runtime-unexpected":"runtime-unexpected","runtime-resolver-not-found":"runtime-resolver-not-found","runtime-saga-compensation":"runtime-saga-compensation"};function rt(e){return`https://jagreehal.github.io/awaitly/rules/#${e}`}var mr=Object.keys(It);var We=class extends Error{_tag};function Te(e,t){return class extends We{_tag=e;constructor(n,m){let s=t?.message?t.message(n??{}):e;if(super(s),this.name=e,t?.slug!==void 0){if(!t.hint)throw new TypeError(`TaggedError: 'hint' is required when 'slug' is set (slug: "${t.slug}")`);Object.defineProperty(this,"code",{value:t.slug,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"hint",{value:t.hint,enumerable:!0,writable:!1,configurable:!1}),Object.defineProperty(this,"docsUrl",{value:rt(t.slug),enumerable:!0,writable:!1,configurable:!1})}if(Object.setPrototypeOf(this,new.target.prototype),n&&typeof n=="object"){let a;if(t?.slug!==void 0){let{_tag:K,name:I,message:O,stack:r,code:q,hint:L,docsUrl:de,...ne}=n;a=ne}else{let{_tag:K,name:I,message:O,stack:r,...q}=n;a=q}let w=Object.prototype.hasOwnProperty.call(a,"cause"),v=w?a.cause:void 0;w&&delete a.cause;let W=m?.cause!==void 0;if(w&&W)throw new TypeError("TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause");Object.assign(this,a),w&&(this.cause=v),W&&(this.cause=m?.cause)}else m?.cause!==void 0&&(this.cause=m.cause)}}}Object.defineProperty(Te,Symbol.hasInstance,{value:e=>e instanceof We});(s=>{function e(a){return a instanceof Error}s.isError=e;function t(a){return a instanceof We}s.isTaggedError=t;function n(a,w){let v=a._tag,W=w[v];return W(a)}s.match=n;function m(a,w,v){let W=a._tag,K=w[W];return K?K(a):v(a)}s.matchPartial=m})(Te||={});var nt=class extends Te("TimeoutError",{slug:"runtime-step-timeout",hint:"Increase the step's timeout option, or check why the upstream operation is slow.",message:t=>t.operation?`TimeoutError: ${t.operation} timed out after ${t.ms}ms`:`TimeoutError: Operation timed out after ${t.ms}ms`}){},ot=class extends Te("RetryExhaustedError",{slug:"runtime-retry-exhausted",hint:"All retry attempts failed. Inspect lastError and decide whether to surface it or compensate.",message:t=>t.operation?`RetryExhaustedError: ${t.operation} failed after ${t.attempts} attempts`:`RetryExhaustedError: Operation failed after ${t.attempts} attempts`}){},st=class extends Te("RateLimitError",{slug:"runtime-rate-limit",hint:"Wait retryAfterMs before retrying, or apply step.cache to deduplicate calls.",message:t=>t.limiterName?`RateLimitError: Rate limit exceeded for ${t.limiterName}${t.retryAfterMs?`, retry after ${t.retryAfterMs}ms`:""}`:`RateLimitError: Rate limit exceeded${t.retryAfterMs?`, retry after ${t.retryAfterMs}ms`:""}`}){},at=class extends Te("CircuitBreakerOpenError",{slug:"runtime-circuit-open",hint:"The circuit is open. Wait for it to half-open or fall back to a degraded path.",message:t=>`CircuitBreakerOpenError: Circuit ${t.circuitName} is ${t.state??"OPEN"}${t.retryAfterMs?`, retry after ${Math.ceil(t.retryAfterMs/1e3)}s`:""}`}){},it=class extends Te("ValidationError",{message:t=>`ValidationError: Invalid ${t.field} - ${t.reason}`}){},ut=class extends Te("NotFoundError",{message:t=>t.id?`NotFoundError: ${t.resource} with id ${t.id} not found`:`NotFoundError: ${t.resource} not found`}){},lt=class extends Te("UnauthorizedError",{message:t=>t.reason?`UnauthorizedError: ${t.reason}`:t.action&&t.resource?`UnauthorizedError: Not authorized to ${t.action} ${t.resource}`:"UnauthorizedError: Access denied"}){},ct=class extends Te("NetworkError",{message:t=>t.url?`NetworkError: ${t.reason} (${t.url})`:`NetworkError: ${t.reason}`}){},pt=class extends Te("CompensationError",{slug:"runtime-saga-compensation",hint:"A saga compensation step failed. Inspect compensationError and ensure compensation is idempotent.",message:t=>`CompensationError: Failed to compensate step ${t.step}`}){},he=class extends Te("UnexpectedError",{slug:"runtime-unexpected",hint:"An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",message:t=>`UnexpectedError: ${t.cause instanceof Error?t.cause.message:String(t.cause??"unknown")}`}){};function dt(e){return{ok:!0,value:e}}var Ut=e=>typeof e=="object"&&e!==null&&"ok"in e&&typeof e.ok=="boolean"&&(e.ok?"value"in e:"error"in e),Ne=(e,t)=>{let n={},m=new Map;for(let s of Object.keys(e)){let a=e[s];typeof a=="function"&&(n[s]=(...w)=>{let v=(m.get(s)??0)+1;m.set(s,v);let W=v===1?s:`${s}#${v}`;return t(W,async()=>{let K=await a(...w);return Ut(K)?K:dt(K)})})}return n};function Wt(e){let t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);if(!t)return;let n=parseFloat(t[1]),m=t[2].toLowerCase();return{_tag:"Duration",millis:n*({ms:1,s:1e3,m:6e4,h:36e5,d:864e5}[m]??1)}}function $e(e){return new he({cause:e})}function Z(e){return{ok:!0,value:e}}function j(e,t){let n=t?.cause;return{ok:!1,error:e,...n!==void 0?{cause:n}:{}}}var wt=e=>e.ok;var yt=e=>e instanceof he||typeof e=="object"&&e!==null&&"_tag"in e&&e._tag==="UnexpectedError";function Nt(e){if(e==null)return"unknown";if(typeof e=="string")return e.trim()||"unknown";if(typeof e=="object"){let t=e;if(typeof t._tag=="string"){let n=t._tag.trim();if(n)return n}if(typeof t.tag=="string"){let n=t.tag.trim();if(n)return n}if(typeof t.code=="string"){let n=t.code.trim();if(n)return n}else if(typeof t.code=="number")return String(t.code);if(e instanceof Error&&e.name){let n=e.name.trim();if(n)return n}}return"unknown"}function jt(e,t){if(!(!t||!e))return t[e]}function qe(e){let{intent:t,domain:n,owner:m,tags:s,stateChanges:a,emits:w,calls:v}=e;if(!t&&!n&&!m&&!s?.length&&!a?.length&&!w?.length&&!v?.length)return;let W={};return t&&(W.intent=t),n&&(W.domain=n),m&&(W.owner=m),s?.length&&(W.tags=s),a?.length&&(W.stateChanges=a),w?.length&&(W.emits=w),v?.length&&(W.calls=v),W}function xe(e,t,n,m,s){let a=Nt(e),w=jt(a,t),v={tag:a,origin:n};return w!==void 0&&(v.classification=w),m!==void 0&&(v.attempt=m),s!==void 0&&(v.cumulativeDurationMs=s),v}var Oe=Symbol.for("step_timeout_marker");function mt(e){return typeof e!="object"||e===null?!1:e.type==="STEP_TIMEOUT"?!0:Oe in e}function Kt(e){if(!(typeof e!="object"||e===null)){if(e.type==="STEP_TIMEOUT"){let t=e;return{timeoutMs:t.timeoutMs,stepName:t.stepName,stepKey:t.stepKey,attempt:t.attempt}}if(Oe in e)return e[Oe]}}var kt=Symbol("early-exit");function De(e,t){return{[kt]:!0,error:e,meta:t}}function ve(e){return typeof e=="object"&&e!==null&&e[kt]===!0}var gt=Symbol("mapper-exception");function Ae(e){return{[gt]:!0,thrown:e}}function Ft(e){return typeof e=="object"&&e!==null&&e[gt]===!0}function He(e,t){let{backoff:n,initialDelay:m,maxDelay:s,jitter:a}=t,w;switch(n){case"fixed":w=m;break;case"linear":w=m*e;break;case"exponential":w=m*Math.pow(2,e-1);break}if(w=Math.min(w,s),a){let v=w*.25*Math.random();w=w+v}return Math.floor(w)}function Je(e){return new Promise(t=>setTimeout(t,e))}var Et=Symbol("timeout"),Fe=Symbol("timeout-option");function $t(e){return typeof e=="object"&&e!==null&&e[Fe]===!0}async function Bt(e,t,n,m){let s=new AbortController,a=t.onTimeout??"error",w=()=>typeof a=="function"?a({name:n.name,key:n.key,ms:t.ms}):t.error??{type:"STEP_TIMEOUT",stepName:n.name,stepKey:n.key,timeoutMs:t.ms,attempt:n.attempt},v;m?.aborted&&s.abort(m.reason);let W;m&&!m.aborted&&(W=()=>s.abort(m.reason),m.addEventListener("abort",W,{once:!0}));let K=new Promise((O,r)=>{v=setTimeout(()=>{if(a!=="disconnect"&&s.abort(),a==="option"){r({[Fe]:!0,ms:t.ms});return}r({[Et]:!0,error:w()})},t.ms)}),I;t.signal?I=Promise.resolve(e(s.signal)):I=Promise.resolve(e());try{return await Promise.race([I,K])}catch(O){if(typeof O=="object"&&O!==null&&O[Fe]===!0)throw{[Fe]:!0,ms:t.ms};if(typeof O=="object"&&O!==null&&O[Et]===!0){a==="disconnect"&&I.catch(()=>{});let r=O.error;if(typeof r=="object"&&r!==null&&r.type!=="STEP_TIMEOUT"){let q={timeoutMs:t.ms,stepName:n.name,stepKey:n.key,attempt:n.attempt};Oe in r?r[Oe]=q:Object.defineProperty(r,Oe,{value:q,enumerable:!1,writable:!0,configurable:!1})}throw r}throw O}finally{clearTimeout(v),W&&m&&m.removeEventListener("abort",W)}}var Pe={backoff:"exponential",initialDelay:100,maxDelay:3e4,jitter:!0,shouldRetry:()=>!0,onRetry:()=>{}};async function je(e,t,n){if(typeof e!="function"){let y=e,oe=t;if(typeof oe!="function")throw new TypeError("[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))");return je(({step:ue})=>oe(Ne(y,ue),{step:ue}),n)}let m=e,s=t,{onError:a,onEvent:w,catchUnexpected:v,workflowId:W,workflowName:K,context:I,_workflowSignal:O}=s&&typeof s=="object"?s:{},r=W??crypto.randomUUID(),q=v??$e,L=[],de=0,ne=y=>y??`step_${++de}`,u=y=>{let oe=y.context!==void 0||I===void 0?y:{...y,context:I},me=K!==void 0&&oe.workflowName===void 0?{...oe,workflowName:K}:oe;if(me.type==="step_success"){let ue=me.stepId;for(let ce=L.length-1;ce>=0;ce--){let F=L[ce];if(F.type==="race"&&!F.winnerId){F.winnerId=ue;break}}}w?.(me,I)},Q=De,we=y=>ve(y),_=(y,oe)=>y,z=y=>typeof y=="function"?!1:!!(y&&typeof y=="object"&&"ok"in y||y&&typeof y=="object"&&"then"in y&&typeof y.then=="function");try{let oe=function(E){let S={};for(let[l,c]of Object.entries(E))if(typeof c=="function")S[l]=c;else if(c&&typeof c=="object"&&"fn"in c)S[l]=c.fn;else throw new TypeError(`step.all: operation "${l}" must be a function or { fn, errors? } object`);return S},me=function(E,S){let l=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let c=performance.now(),o=!1;L.push({scopeId:l,type:"parallel"});let i=()=>{if(o)return;o=!0;let T=L.findIndex(h=>h.scopeId===l);T!==-1&&L.splice(T,1),u({type:"scope_end",workflowId:r,scopeId:l,ts:Date.now(),durationMs:performance.now()-c})};u({type:"scope_start",workflowId:r,scopeId:l,scopeType:"parallel",name:E,ts:Date.now()});try{let T=await S();if(i(),!T.ok)throw a?.(T.error,E,I),Q(T.error,{origin:"result",resultCause:T.cause});return T.value}catch(T){throw i(),T}})()},ue=function(E,S){let l=Object.keys(E),c=S.name??`Parallel(${l.join(", ")})`,o=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let i=performance.now(),T=!1;L.push({scopeId:o,type:"parallel"});let h=()=>{if(T)return;T=!0;let P=L.findIndex(M=>M.scopeId===o);P!==-1&&L.splice(P,1),u({type:"scope_end",workflowId:r,scopeId:o,ts:Date.now(),durationMs:performance.now()-i})};u({type:"scope_start",workflowId:r,scopeId:o,scopeType:"parallel",name:c,ts:Date.now()});try{let P=await new Promise(N=>{if(l.length===0){N([]);return}let H=!1,ae=l.length,B=new Array(l.length);for(let G=0;G<l.length;G++){let V=l[G],Y=G;Promise.resolve(E[V]()).catch(C=>j({type:"PROMISE_REJECTED",cause:C},{cause:{type:"PROMISE_REJECTION",reason:C}})).then(C=>{if(!H){if(!C.ok){H=!0,N([{key:V,result:C}]);return}B[Y]={key:V,result:C},ae--,ae===0&&N(B)}})}});h();let M={};for(let{key:N,result:H}of P){if(!H.ok)throw a?.(H.error,N,I),Q(H.error,{origin:"result",resultCause:H.cause});M[N]=H.value}return M}catch(P){throw h(),P}})()};var ee=oe,pe=me,ye=ue;let y=(E,S,l)=>(async()=>{if(typeof E!="string"||E.length===0)throw new Error('[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))');let c=l??{},o=qe(c),i=E,T=c.key??E,h=c.key??E,{description:P,retry:M,timeout:N}=c,H=ne(T),ae=w,B=ae?performance.now():0,V=z(S)?()=>S:S,C={attempts:Math.max(1,M?.attempts??1),backoff:M?.backoff??Pe.backoff,initialDelay:M?.initialDelay??Pe.initialDelay,maxDelay:M?.maxDelay??Pe.maxDelay,jitter:M?.jitter??Pe.jitter,shouldRetry:M?.shouldRetry??Pe.shouldRetry,onRetry:M?.onRetry??Pe.onRetry};w&&u({type:"step_start",workflowId:r,stepId:H,stepKey:T,name:i,description:P,ts:Date.now(),...o&&{metadata:o}});let Re;for(let x=1;x<=C.attempts;x++){let g=ae?performance.now():0;try{let p;if(N?p=await Bt(V,N,{name:i,key:T,attempt:x},O):p=await V(),p.ok){let R=performance.now()-B;return u({type:"step_success",workflowId:r,stepId:H,stepKey:T,name:i,description:P,ts:Date.now(),durationMs:R,...o&&{metadata:o}}),h&&u({type:"step_complete",workflowId:r,stepKey:h,name:i,description:P,ts:Date.now(),durationMs:R,result:p,...o&&{metadata:o}}),p.value}if(Re=p,x<C.attempts&&C.shouldRetry(p.error,x)){let R=He(x,C);u({type:"step_retry",workflowId:r,stepId:H,stepKey:T,name:i,ts:Date.now(),attempt:x+1,maxAttempts:C.attempts,delayMs:R,error:p.error,...o&&{metadata:o},diagnostics:xe(p.error,c.errorMeta,"result",x,performance.now()-B)}),C.onRetry(p.error,x,R),await Je(R);continue}C.attempts>1&&u({type:"step_retries_exhausted",workflowId:r,stepId:H,stepKey:T,name:i,ts:Date.now(),durationMs:performance.now()-B,attempts:x,lastError:p.error,...o&&{metadata:o},diagnostics:xe(p.error,c.errorMeta,"result",x,performance.now()-B)});break}catch(p){let R=performance.now()-g;if($t(p)){let D=p.ms;u({type:"step_timeout",workflowId:r,stepId:H,stepKey:T,name:i,ts:Date.now(),timeoutMs:D,attempt:x,...o&&{metadata:o},diagnostics:xe(p,c.errorMeta,"timeout",x)}),u({type:"step_success",workflowId:r,stepId:H,stepKey:T,name:i,description:P,ts:Date.now(),durationMs:performance.now()-B,...o&&{metadata:o}}),h&&u({type:"step_complete",workflowId:r,stepKey:h,name:i,description:P,ts:Date.now(),durationMs:performance.now()-B,result:Z(void 0),...o&&{metadata:o}});return}if(we(p))throw u({type:"step_aborted",workflowId:r,stepId:H,stepKey:T,name:i,description:P,ts:Date.now(),durationMs:R,...o&&{metadata:o}}),p;if(mt(p)){let D=Kt(p),k=N?.ms??D?.timeoutMs??0;if(u({type:"step_timeout",workflowId:r,stepId:H,stepKey:T,name:i,ts:Date.now(),timeoutMs:k,attempt:x,...o&&{metadata:o},diagnostics:xe(p,c.errorMeta,"timeout",x)}),x<C.attempts&&C.shouldRetry(p,x)){let te=He(x,C);u({type:"step_retry",workflowId:r,stepId:H,stepKey:T,name:i,ts:Date.now(),attempt:x+1,maxAttempts:C.attempts,delayMs:te,error:p,...o&&{metadata:o},diagnostics:xe(p,c.errorMeta,"timeout",x,performance.now()-B)}),C.onRetry(p,x,te),await Je(te);continue}C.attempts>1&&u({type:"step_retries_exhausted",workflowId:r,stepId:H,stepKey:T,name:i,ts:Date.now(),durationMs:performance.now()-B,attempts:x,lastError:p,...o&&{metadata:o},diagnostics:xe(p,c.errorMeta,"timeout",x,performance.now()-B)});let $=performance.now()-B;throw u({type:"step_error",workflowId:r,stepId:H,stepKey:T,name:i,description:P,ts:Date.now(),durationMs:$,error:p,...o&&{metadata:o},diagnostics:xe(p,c.errorMeta,"timeout",x,$)}),h&&u({type:"step_complete",workflowId:r,stepKey:h,name:i,description:P,ts:Date.now(),durationMs:$,result:j(p,{cause:p}),meta:{origin:"throw",thrown:p},...o&&{metadata:o}}),a?.(p,i,I),Q(p,{origin:"throw",thrown:p})}if(x<C.attempts&&C.shouldRetry(p,x)){let D=He(x,C);u({type:"step_retry",workflowId:r,stepId:H,stepKey:T,name:i,ts:Date.now(),attempt:x+1,maxAttempts:C.attempts,delayMs:D,error:p,...o&&{metadata:o},diagnostics:xe(p,c.errorMeta,"throw",x,performance.now()-B)}),C.onRetry(p,x,D),await Je(D);continue}C.attempts>1&&!mt(p)&&u({type:"step_retries_exhausted",workflowId:r,stepId:H,stepKey:T,name:i,ts:Date.now(),durationMs:performance.now()-B,attempts:x,lastError:p,...o&&{metadata:o},diagnostics:xe(p,c.errorMeta,"throw",x,performance.now()-B)});let A=performance.now()-B,b;try{b=q(p)}catch(D){throw Ae(D)}throw u({type:"step_error",workflowId:r,stepId:H,stepKey:T,name:i,description:P,ts:Date.now(),durationMs:A,error:b,...o&&{metadata:o},diagnostics:xe(p,c.errorMeta,"throw",x,A)}),h&&u({type:"step_complete",workflowId:r,stepKey:h,name:i,description:P,ts:Date.now(),durationMs:A,result:j(b,{cause:p}),meta:{origin:"throw",thrown:p},...o&&{metadata:o}}),a?.(b,i,I),Q(b,{origin:"throw",thrown:p})}}let d=Re,f=performance.now()-B,X=_(d.error,{origin:"result",resultCause:d.cause});throw u({type:"step_error",workflowId:r,stepId:H,stepKey:T,name:i,description:P,ts:Date.now(),durationMs:f,error:X,...o&&{metadata:o},diagnostics:xe(d.error,c.errorMeta,"result",C.attempts,f)}),h&&u({type:"step_complete",workflowId:r,stepKey:h,name:i,description:P,ts:Date.now(),durationMs:f,result:d,meta:{origin:"result",resultCause:d.cause},...o&&{metadata:o}}),a?.(X,i,I),Q(X,{origin:"result",resultCause:d.cause})})();y.try=(E,S,l)=>{if(typeof E!="string"||E.length===0)throw new Error('[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })');let c="error"in l?()=>l.error:l.onError;if(l.retry||l.timeout)return y.retry(E,async()=>{try{return Z(await S())}catch(P){return j(c(P),{cause:P})}},{attempts:l.retry?.attempts??1,...l.retry??{},key:l.key,timeout:l.timeout});let o=l.key??E,i=E,T=E,h=w;return(async()=>{let P=h?performance.now():0;w&&u({type:"step_start",workflowId:r,stepId:T,stepKey:o,name:i,ts:Date.now()});try{let M=await S(),N=performance.now()-P;return u({type:"step_success",workflowId:r,stepId:T,stepKey:o,name:i,ts:Date.now(),durationMs:N}),o&&u({type:"step_complete",workflowId:r,stepKey:o,name:i,ts:Date.now(),durationMs:N,result:Z(M)}),M}catch(M){let N=c(M),H=performance.now()-P,ae=_(N,{origin:"throw",thrown:M});throw u({type:"step_error",workflowId:r,stepId:T,stepKey:o,name:i,ts:Date.now(),durationMs:H,error:ae}),o&&u({type:"step_complete",workflowId:r,stepKey:o,name:i,ts:Date.now(),durationMs:H,result:j(N,{cause:M}),meta:{origin:"throw",thrown:M}}),a?.(ae,i,I),Q(ae,{origin:"throw",thrown:M})}})()},y.fromResult=(E,S,l)=>{if(typeof E!="string"||E.length===0)throw new Error('[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })');let c=l.key??E,o=E,i=E,T="error"in l?()=>l.error:l.onError,h=w;return(async()=>{let P=h?performance.now():0;w&&u({type:"step_start",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now()});let M=await S();if(M.ok){let N=performance.now()-P;return u({type:"step_success",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:N}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:N,result:Z(M.value)}),M.value}else{let N=T(M.error),H=performance.now()-P,ae=_(N,{origin:"result",resultCause:M.error});throw u({type:"step_error",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:H,error:ae}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:H,result:j(N,{cause:M.error}),meta:{origin:"result",resultCause:M.error}}),a?.(ae,o,I),Q(ae,{origin:"result",resultCause:M.error})}})()},y.fromNullable=(E,S,l,c)=>{if(typeof E!="string"||E.length===0)throw new Error('[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))');return y(E,async()=>{let o=await S();return o!=null?Z(o):j(l())},c)},y.retry=(E,S,l)=>{if(typeof E!="string"||E.length===0)throw new Error('[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })');return y(E,S,{key:l.key??E,retry:{attempts:l.attempts,backoff:l.backoff,initialDelay:l.initialDelay,maxDelay:l.maxDelay,jitter:l.jitter,shouldRetry:l.shouldRetry,onRetry:l.onRetry},timeout:l.timeout})},y.withTimeout=(E,S,l)=>{if(typeof E!="string"||E.length===0)throw new Error('[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })');return y(E,S,{key:l.key??E,timeout:l})},y.sleep=(E,S,l)=>{if(typeof E!="string"||E.length===0)throw new Error('[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")');let c=typeof S=="string"?Wt(S):S;if(!c)throw new Error(`step.sleep: invalid duration '${S}'`);let o=c.millis,i=l?.signal;return y(E,async()=>{if(O?.aborted||i?.aborted){let T=new Error("Sleep aborted");throw T.name="AbortError",T}return new Promise((T,h)=>{let P={timeoutId:void 0},M=()=>{P.timeoutId&&clearTimeout(P.timeoutId);let N=new Error("Sleep aborted");N.name="AbortError",h(N)};O?.addEventListener("abort",M,{once:!0}),i?.addEventListener("abort",M,{once:!0}),P.timeoutId=setTimeout(()=>{O?.removeEventListener("abort",M),i?.removeEventListener("abort",M),T(Z(void 0))},o)})},{key:l?.key??E,description:l?.description})},y.all=((...E)=>{if(typeof E[0]!="string")throw new TypeError("step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })");let S=E[0],l=E[1];if(typeof l=="function")return me(S,l);if(l&&typeof l=="object"&&!Array.isArray(l)){let o=oe(l);return ue(o,{name:S})}throw new TypeError("step.all(name, ...): second argument must be a function (array form) or an object of operations (object form).")}),y.race=(E,S)=>{let l=`scope_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return(async()=>{let c=performance.now(),o=!1,i={scopeId:l,type:"race",winnerId:void 0};L.push(i);let T=()=>{if(o)return;o=!0;let h=L.findIndex(P=>P.scopeId===l);h!==-1&&L.splice(h,1),u({type:"scope_end",workflowId:r,scopeId:l,ts:Date.now(),durationMs:performance.now()-c,winnerId:i.winnerId})};u({type:"scope_start",workflowId:r,scopeId:l,scopeType:"race",name:E,ts:Date.now()});try{let h=await S();if(T(),!h.ok)throw a?.(h.error,E,I),Q(h.error,{origin:"result",resultCause:h.cause});return h.value}catch(h){throw T(),h}})()},y.if=(E,S,l)=>l(),y.label=y.if,y.branch=async(E,S)=>{let{condition:l,then:c,else:o}=S;if(l())return await c();if(o)return await o()},y.arm=(E,S)=>({fn:E,errors:S}),y.forEach=async(E,S,l)=>{let c=[],o=l.maxIterations,i=0,T="run"in l,h=Symbol.asyncIterator in S?S:(async function*(){yield*S})();for await(let P of h){if(o!==void 0&&i>=o)break;let M;T?M=await l.run(P,i):M=await l.item.handler(P,i,y),c.push(M),i++}return c},y.item=E=>({__forEachItemHandler:!0,handler:E}),y.dep=(E,S)=>S,y.workflow=(E,S,l)=>y(E,S,l),y.map=async(E,S,l,c)=>{let o=c?.concurrency??S.length;return y(E,()=>o>=S.length?ft(S.map((i,T)=>l(i,T))):(async()=>{let i=[];for(let T=0;T<S.length;T+=o){let h=S.slice(T,T+o),P=await ft(h.map((M,N)=>l(M,T+N)));if(!P.ok)return P;i.push(...P.value)}return Z(i)})(),{key:c?.key})},y.withFallback=(E,S,l)=>{if(typeof E!="string"||E.length===0)throw new Error('[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })');let c=l.key??E,o=E,i=ne(c),T=w;return(async()=>{let h=T?performance.now():0;w&&u({type:"step_start",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now()});let P;try{P=await S()}catch(B){if(we(B))throw u({type:"step_aborted",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:performance.now()-h}),B;let G;try{G=q(B)}catch(Y){throw Ae(Y)}if(l.on!==void 0&&l.on!==G){let Y=performance.now()-h;throw u({type:"step_error",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:Y,error:G}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:Y,result:j(G,{cause:B}),meta:{origin:"throw",thrown:B}}),a?.(G,o,I),Q(G,{origin:"throw",thrown:B})}let V;try{V=await l.fallback()}catch(Y){if(we(Y))throw u({type:"step_aborted",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:performance.now()-h}),Y;let C;try{C=q(Y)}catch(d){throw Ae(d)}let Re=performance.now()-h;throw u({type:"step_error",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:Re,error:C}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:Re,result:j(C,{cause:Y}),meta:{origin:"throw",thrown:Y}}),a?.(C,o,I),Q(C,{origin:"throw",thrown:Y})}if(V.ok){let Y=performance.now()-h;return u({type:"step_success",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:Y}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:Y,result:V,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(G)}}),V.value}else{let Y=performance.now()-h,C=_(V.error,{origin:"result",resultCause:V.cause});throw u({type:"step_error",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:Y,error:C}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:Y,result:V,meta:{origin:"result",resultCause:V.cause}}),a?.(C,o,I),Q(C,{origin:"result",resultCause:V.cause})}}if(P.ok){let B=performance.now()-h;return u({type:"step_success",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:B}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:B,result:P}),P.value}let M=P.error;if(l.on!==void 0&&l.on!==M){let B=performance.now()-h,G=_(M,{origin:"result",resultCause:P.cause});throw u({type:"step_error",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:B,error:G}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:B,result:P,meta:{origin:"result",resultCause:P.cause}}),a?.(G,o,I),Q(G,{origin:"result",resultCause:P.cause})}let N;try{N=await l.fallback()}catch(B){if(we(B))throw u({type:"step_aborted",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:performance.now()-h}),B;let G;try{G=q(B)}catch(Y){throw Ae(Y)}let V=performance.now()-h;throw u({type:"step_error",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:V,error:G}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:V,result:j(G,{cause:B}),meta:{origin:"throw",thrown:B}}),a?.(G,o,I),Q(G,{origin:"throw",thrown:B})}if(N.ok){let B=performance.now()-h;return u({type:"step_success",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:B}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:B,result:N,meta:{origin:"fallback",fallbackUsed:!0,fallbackReason:String(M)}}),N.value}let H=performance.now()-h,ae=_(N.error,{origin:"result",resultCause:N.cause});throw u({type:"step_error",workflowId:r,stepId:i,stepKey:c,name:o,ts:Date.now(),durationMs:H,error:ae}),c&&u({type:"step_complete",workflowId:r,stepKey:c,name:o,ts:Date.now(),durationMs:H,result:N,meta:{origin:"result",resultCause:N.cause}}),a?.(ae,o,I),Q(ae,{origin:"result",resultCause:N.cause})})()},y.withResource=(E,S)=>{if(typeof E!="string"||E.length===0)throw new Error('[awaitly] step.withResource() requires an explicit string ID as the first argument. Example: step.withResource("useDb", { acquire: () => connect(), use: (db) => query(db), release: (db) => db.close() })');let l=E,c=E,o=ne(l),i=w;return(async()=>{let T=i?performance.now():0;w&&u({type:"step_start",workflowId:r,stepId:o,stepKey:l,name:c,ts:Date.now()});let h;try{h=await S.acquire()}catch(V){if(we(V))throw u({type:"step_aborted",workflowId:r,stepId:o,stepKey:l,name:c,ts:Date.now(),durationMs:performance.now()-T}),V;let Y;try{Y=q(V)}catch(Re){throw Ae(Re)}let C=performance.now()-T;throw u({type:"step_error",workflowId:r,stepId:o,stepKey:l,name:c,ts:Date.now(),durationMs:C,error:Y}),l&&u({type:"step_complete",workflowId:r,stepKey:l,name:c,ts:Date.now(),durationMs:C,result:j(Y,{cause:V}),meta:{origin:"throw",thrown:V}}),a?.(Y,c,I),Q(Y,{origin:"throw",thrown:V})}if(!h.ok){let V=performance.now()-T,Y=_(h.error,{origin:"result",resultCause:h.cause});throw u({type:"step_error",workflowId:r,stepId:o,stepKey:l,name:c,ts:Date.now(),durationMs:V,error:Y}),l&&u({type:"step_complete",workflowId:r,stepKey:l,name:c,ts:Date.now(),durationMs:V,result:h,meta:{origin:"result",resultCause:h.cause}}),a?.(Y,c,I),Q(Y,{origin:"result",resultCause:h.cause})}let P=h.value,M,N,H=!1;try{M=await S.use(P)}catch(V){if(we(V)){try{await S.release(P)}catch(Y){console.warn(`[awaitly] step.withResource("${E}"): release threw after earlyExit:`,Y)}throw V}N=V,H=!0}try{await S.release(P)}catch(V){console.warn(`[awaitly] step.withResource("${E}"): release threw:`,V)}if(H){let V;try{V=q(N)}catch(C){throw Ae(C)}let Y=performance.now()-T;throw u({type:"step_error",workflowId:r,stepId:o,stepKey:l,name:c,ts:Date.now(),durationMs:Y,error:V}),l&&u({type:"step_complete",workflowId:r,stepKey:l,name:c,ts:Date.now(),durationMs:Y,result:j(V,{cause:N}),meta:{origin:"throw",thrown:N}}),a?.(V,c,I),Q(V,{origin:"throw",thrown:N})}let ae=M;if(ae.ok){let V=performance.now()-T;return u({type:"step_success",workflowId:r,stepId:o,stepKey:l,name:c,ts:Date.now(),durationMs:V}),l&&u({type:"step_complete",workflowId:r,stepKey:l,name:c,ts:Date.now(),durationMs:V,result:ae}),ae.value}let B=performance.now()-T,G=_(ae.error,{origin:"result",resultCause:ae.cause});throw u({type:"step_error",workflowId:r,stepId:o,stepKey:l,name:c,ts:Date.now(),durationMs:B,error:G}),l&&u({type:"step_complete",workflowId:r,stepKey:l,name:c,ts:Date.now(),durationMs:B,result:ae,meta:{origin:"result",resultCause:ae.cause}}),a?.(G,c,I),Q(G,{origin:"result",resultCause:ae.cause})})()};let F=await m({step:y});if(process.env.NODE_ENV!=="production"&&F!==null&&typeof F=="object"&&"ok"in F&&typeof F.ok=="boolean"){let E=F;(E.ok===!0&&"value"in E||E.ok===!1&&"error"in E)&&console.warn(`awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
|
|
1
|
+
// src/slugs.ts
|
|
2
|
+
var AWAITLY_SLUGS = {
|
|
3
|
+
// --- step-* ---
|
|
4
|
+
"step-require-id": "step-require-id",
|
|
5
|
+
"step-no-immediate-execution": "step-no-immediate-execution",
|
|
6
|
+
"step-require-thunk-for-key": "step-require-thunk-for-key",
|
|
7
|
+
"step-no-bare-await": "step-no-bare-await",
|
|
8
|
+
"step-no-try-catch-wrap": "step-no-try-catch-wrap",
|
|
9
|
+
"step-stable-cache-keys": "step-stable-cache-keys",
|
|
10
|
+
// --- workflow-* ---
|
|
11
|
+
"workflow-no-floating": "workflow-no-floating",
|
|
12
|
+
"workflow-options-position": "workflow-options-position",
|
|
13
|
+
"workflow-callback-shape": "workflow-callback-shape",
|
|
14
|
+
"workflow-no-callable-form": "workflow-no-callable-form",
|
|
15
|
+
"workflow-no-dynamic-import": "workflow-no-dynamic-import",
|
|
16
|
+
"workflow-prefer-step-if": "workflow-prefer-step-if",
|
|
17
|
+
"workflow-prefer-step-foreach": "workflow-prefer-step-foreach",
|
|
18
|
+
// --- result-* ---
|
|
19
|
+
"result-no-floating": "result-no-floating",
|
|
20
|
+
"result-require-handling": "result-require-handling",
|
|
21
|
+
"result-no-double-wrap": "result-no-double-wrap",
|
|
22
|
+
"result-no-manual-propagation": "result-no-manual-propagation",
|
|
23
|
+
"result-no-direct-ok-err": "result-no-direct-ok-err",
|
|
24
|
+
// --- error-* ---
|
|
25
|
+
"error-check-unexpected-first": "error-check-unexpected-first",
|
|
26
|
+
"error-access-cause": "error-access-cause",
|
|
27
|
+
"error-normalize": "error-normalize",
|
|
28
|
+
"error-no-throw-in-deps": "error-no-throw-in-deps",
|
|
29
|
+
// --- concurrency-* ---
|
|
30
|
+
"concurrency-no-promise-all": "concurrency-no-promise-all",
|
|
31
|
+
"concurrency-no-promise-race": "concurrency-no-promise-race",
|
|
32
|
+
"concurrency-no-promise-allsettled": "concurrency-no-promise-allsettled",
|
|
33
|
+
// --- runtime-* ---
|
|
34
|
+
"runtime-step-timeout": "runtime-step-timeout",
|
|
35
|
+
"runtime-step-aborted": "runtime-step-aborted",
|
|
36
|
+
"runtime-retry-exhausted": "runtime-retry-exhausted",
|
|
37
|
+
"runtime-rate-limit": "runtime-rate-limit",
|
|
38
|
+
"runtime-circuit-open": "runtime-circuit-open",
|
|
39
|
+
"runtime-unexpected": "runtime-unexpected",
|
|
40
|
+
"runtime-resolver-not-found": "runtime-resolver-not-found",
|
|
41
|
+
"runtime-saga-compensation": "runtime-saga-compensation"
|
|
42
|
+
};
|
|
43
|
+
function slugDocsUrl(slug) {
|
|
44
|
+
return `https://jagreehal.github.io/awaitly/rules/#${slug}`;
|
|
45
|
+
}
|
|
46
|
+
var ALL_SLUGS = Object.keys(
|
|
47
|
+
AWAITLY_SLUGS
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
// src/tagged-error.ts
|
|
51
|
+
var InternalTaggedErrorBase = class extends Error {
|
|
52
|
+
type;
|
|
53
|
+
/** @deprecated Use `type`. */
|
|
54
|
+
_tag;
|
|
55
|
+
};
|
|
56
|
+
function TaggedError(tag, options) {
|
|
57
|
+
return class extends InternalTaggedErrorBase {
|
|
58
|
+
type = tag;
|
|
59
|
+
/** @deprecated Use `type`. */
|
|
60
|
+
_tag = tag;
|
|
61
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
62
|
+
constructor(props, errorOptions) {
|
|
63
|
+
const message = options?.message ? options.message(props ?? {}) : tag;
|
|
64
|
+
super(message);
|
|
65
|
+
this.name = tag;
|
|
66
|
+
if (options?.slug !== void 0) {
|
|
67
|
+
if (!options.hint) {
|
|
68
|
+
throw new TypeError(
|
|
69
|
+
`TaggedError: 'hint' is required when 'slug' is set (slug: "${options.slug}")`
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
Object.defineProperty(this, "code", {
|
|
73
|
+
value: options.slug,
|
|
74
|
+
enumerable: true,
|
|
75
|
+
writable: false,
|
|
76
|
+
configurable: false
|
|
77
|
+
});
|
|
78
|
+
Object.defineProperty(this, "hint", {
|
|
79
|
+
value: options.hint,
|
|
80
|
+
enumerable: true,
|
|
81
|
+
writable: false,
|
|
82
|
+
configurable: false
|
|
83
|
+
});
|
|
84
|
+
Object.defineProperty(this, "docsUrl", {
|
|
85
|
+
value: slugDocsUrl(options.slug),
|
|
86
|
+
enumerable: true,
|
|
87
|
+
writable: false,
|
|
88
|
+
configurable: false
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
92
|
+
if (props && typeof props === "object") {
|
|
93
|
+
let safeProps;
|
|
94
|
+
if (options?.slug !== void 0) {
|
|
95
|
+
const {
|
|
96
|
+
_tag: _,
|
|
97
|
+
type: _t,
|
|
98
|
+
name: _n,
|
|
99
|
+
message: _m,
|
|
100
|
+
stack: _s,
|
|
101
|
+
code: _c,
|
|
102
|
+
hint: _h,
|
|
103
|
+
docsUrl: _d,
|
|
104
|
+
...rest
|
|
105
|
+
} = props;
|
|
106
|
+
safeProps = rest;
|
|
107
|
+
} else {
|
|
108
|
+
const {
|
|
109
|
+
_tag: _,
|
|
110
|
+
type: _t,
|
|
111
|
+
name: _n,
|
|
112
|
+
message: _m,
|
|
113
|
+
stack: _s,
|
|
114
|
+
...rest
|
|
115
|
+
} = props;
|
|
116
|
+
safeProps = rest;
|
|
117
|
+
}
|
|
118
|
+
const hasUserCause = Object.prototype.hasOwnProperty.call(
|
|
119
|
+
safeProps,
|
|
120
|
+
"cause"
|
|
121
|
+
);
|
|
122
|
+
const userCause = hasUserCause ? safeProps.cause : void 0;
|
|
123
|
+
if (hasUserCause) {
|
|
124
|
+
delete safeProps.cause;
|
|
125
|
+
}
|
|
126
|
+
const hasOptionsCause = errorOptions?.cause !== void 0;
|
|
127
|
+
if (hasUserCause && hasOptionsCause) {
|
|
128
|
+
throw new TypeError(
|
|
129
|
+
"TaggedError: cannot provide 'cause' in props when also setting ErrorOptions.cause"
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
Object.assign(this, safeProps);
|
|
133
|
+
if (hasUserCause) {
|
|
134
|
+
this.cause = userCause;
|
|
135
|
+
}
|
|
136
|
+
if (hasOptionsCause) {
|
|
137
|
+
this.cause = errorOptions?.cause;
|
|
138
|
+
}
|
|
139
|
+
} else if (errorOptions?.cause !== void 0) {
|
|
140
|
+
this.cause = errorOptions.cause;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
Object.defineProperty(TaggedError, Symbol.hasInstance, {
|
|
146
|
+
value: (instance) => instance instanceof InternalTaggedErrorBase
|
|
147
|
+
});
|
|
148
|
+
((TaggedError2) => {
|
|
149
|
+
function isError(value) {
|
|
150
|
+
return value instanceof Error;
|
|
151
|
+
}
|
|
152
|
+
TaggedError2.isError = isError;
|
|
153
|
+
function isTaggedError(value) {
|
|
154
|
+
return value instanceof InternalTaggedErrorBase;
|
|
155
|
+
}
|
|
156
|
+
TaggedError2.isTaggedError = isTaggedError;
|
|
157
|
+
function match(error, handlers) {
|
|
158
|
+
const tag = error._tag;
|
|
159
|
+
const handler = handlers[tag];
|
|
160
|
+
return handler(
|
|
161
|
+
error
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
TaggedError2.match = match;
|
|
165
|
+
function matchPartial(error, handlers, otherwise) {
|
|
166
|
+
const tag = error._tag;
|
|
167
|
+
const handler = handlers[tag];
|
|
168
|
+
if (handler) {
|
|
169
|
+
return handler(
|
|
170
|
+
error
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
return otherwise(error);
|
|
174
|
+
}
|
|
175
|
+
TaggedError2.matchPartial = matchPartial;
|
|
176
|
+
})(TaggedError || (TaggedError = {}));
|
|
177
|
+
|
|
178
|
+
// src/errors.ts
|
|
179
|
+
var UnexpectedError = class extends (/* @__PURE__ */ TaggedError("UnexpectedError", {
|
|
180
|
+
slug: "runtime-unexpected",
|
|
181
|
+
hint: "An unexpected exception escaped a step. Inspect cause; consider returning a typed Result instead of throwing.",
|
|
182
|
+
message: (p) => `UnexpectedError: ${p.cause instanceof Error ? p.cause.message : String(p.cause ?? "unknown")}`
|
|
183
|
+
})) {
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
// src/result/index.ts
|
|
187
|
+
function ok(value) {
|
|
188
|
+
return { ok: true, value };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// src/core/bound-steps.ts
|
|
192
|
+
var isDepResultShaped = (value) => typeof value === "object" && value !== null && "ok" in value && typeof value.ok === "boolean" && (value.ok ? "value" in value : "error" in value);
|
|
193
|
+
var bindSteps = (deps, step) => {
|
|
194
|
+
const steps = {};
|
|
195
|
+
const invocationCounts = /* @__PURE__ */ new Map();
|
|
196
|
+
for (const key of Object.keys(deps)) {
|
|
197
|
+
const dep = deps[key];
|
|
198
|
+
if (typeof dep !== "function") continue;
|
|
199
|
+
steps[key] = (...args) => {
|
|
200
|
+
const count = (invocationCounts.get(key) ?? 0) + 1;
|
|
201
|
+
invocationCounts.set(key, count);
|
|
202
|
+
const stepKey = count === 1 ? key : `${key}#${count}`;
|
|
203
|
+
return step(stepKey, async () => {
|
|
204
|
+
const value = await dep(...args);
|
|
205
|
+
return isDepResultShaped(value) ? value : ok(value);
|
|
206
|
+
});
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
return steps;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
// src/duration.ts
|
|
213
|
+
function millis(ms) {
|
|
214
|
+
return { _tag: "Duration", millis: ms };
|
|
215
|
+
}
|
|
216
|
+
function seconds(s) {
|
|
217
|
+
return { _tag: "Duration", millis: s * 1e3 };
|
|
218
|
+
}
|
|
219
|
+
function minutes(m) {
|
|
220
|
+
return { _tag: "Duration", millis: m * 60 * 1e3 };
|
|
221
|
+
}
|
|
222
|
+
function hours(h) {
|
|
223
|
+
return { _tag: "Duration", millis: h * 60 * 60 * 1e3 };
|
|
224
|
+
}
|
|
225
|
+
function days(d) {
|
|
226
|
+
return { _tag: "Duration", millis: d * 24 * 60 * 60 * 1e3 };
|
|
227
|
+
}
|
|
228
|
+
function toMillis(duration) {
|
|
229
|
+
return duration.millis;
|
|
230
|
+
}
|
|
231
|
+
function parse(input) {
|
|
232
|
+
const match = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
|
|
233
|
+
if (!match) return void 0;
|
|
234
|
+
const value = parseFloat(match[1]);
|
|
235
|
+
const unit = match[2].toLowerCase();
|
|
236
|
+
switch (unit) {
|
|
237
|
+
case "ms":
|
|
238
|
+
return millis(value);
|
|
239
|
+
case "s":
|
|
240
|
+
return seconds(value);
|
|
241
|
+
case "m":
|
|
242
|
+
return minutes(value);
|
|
243
|
+
case "h":
|
|
244
|
+
return hours(value);
|
|
245
|
+
case "d":
|
|
246
|
+
return days(value);
|
|
247
|
+
default:
|
|
248
|
+
return void 0;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// src/core/index.ts
|
|
253
|
+
function parseDurationString(input) {
|
|
254
|
+
const match = input.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i);
|
|
255
|
+
if (!match) return void 0;
|
|
256
|
+
const value = parseFloat(match[1]);
|
|
257
|
+
const unit = match[2].toLowerCase();
|
|
258
|
+
const multipliers = { ms: 1, s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
|
|
259
|
+
return { _tag: "Duration", millis: value * (multipliers[unit] ?? 1) };
|
|
260
|
+
}
|
|
261
|
+
function defaultCatchUnexpected(cause) {
|
|
262
|
+
return new UnexpectedError({ cause });
|
|
263
|
+
}
|
|
264
|
+
function ok2(value) {
|
|
265
|
+
return { ok: true, value };
|
|
266
|
+
}
|
|
267
|
+
function err(error, options) {
|
|
268
|
+
const cause = options?.cause;
|
|
269
|
+
return { ok: false, error, ...cause !== void 0 ? { cause } : {} };
|
|
270
|
+
}
|
|
271
|
+
var isOk = (r) => r.ok;
|
|
272
|
+
var isUnexpectedError = (e) => e instanceof UnexpectedError || typeof e === "object" && e !== null && "_tag" in e && e._tag === "UnexpectedError";
|
|
273
|
+
function extractErrorTag(error) {
|
|
274
|
+
if (error == null) return "unknown";
|
|
275
|
+
if (typeof error === "string") return error.trim() || "unknown";
|
|
276
|
+
if (typeof error === "object") {
|
|
277
|
+
const tagged = error;
|
|
278
|
+
if (typeof tagged._tag === "string") {
|
|
279
|
+
const trimmed = tagged._tag.trim();
|
|
280
|
+
if (trimmed) return trimmed;
|
|
281
|
+
}
|
|
282
|
+
if (typeof tagged.tag === "string") {
|
|
283
|
+
const trimmed = tagged.tag.trim();
|
|
284
|
+
if (trimmed) return trimmed;
|
|
285
|
+
}
|
|
286
|
+
if (typeof tagged.code === "string") {
|
|
287
|
+
const trimmed = tagged.code.trim();
|
|
288
|
+
if (trimmed) return trimmed;
|
|
289
|
+
} else if (typeof tagged.code === "number") {
|
|
290
|
+
return String(tagged.code);
|
|
291
|
+
}
|
|
292
|
+
if (error instanceof Error && error.name) {
|
|
293
|
+
const trimmed = error.name.trim();
|
|
294
|
+
if (trimmed) return trimmed;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return "unknown";
|
|
298
|
+
}
|
|
299
|
+
function lookupErrorClassification(tag, errorMeta) {
|
|
300
|
+
if (!errorMeta || !tag) return void 0;
|
|
301
|
+
return errorMeta[tag];
|
|
302
|
+
}
|
|
303
|
+
function extractStepMetadata(options) {
|
|
304
|
+
const { intent, domain, owner, tags, stateChanges, emits, calls } = options;
|
|
305
|
+
if (!intent && !domain && !owner && !tags?.length && !stateChanges?.length && !emits?.length && !calls?.length) {
|
|
306
|
+
return void 0;
|
|
307
|
+
}
|
|
308
|
+
const metadata = {};
|
|
309
|
+
if (intent) metadata.intent = intent;
|
|
310
|
+
if (domain) metadata.domain = domain;
|
|
311
|
+
if (owner) metadata.owner = owner;
|
|
312
|
+
if (tags?.length) metadata.tags = tags;
|
|
313
|
+
if (stateChanges?.length) metadata.stateChanges = stateChanges;
|
|
314
|
+
if (emits?.length) metadata.emits = emits;
|
|
315
|
+
if (calls?.length) metadata.calls = calls;
|
|
316
|
+
return metadata;
|
|
317
|
+
}
|
|
318
|
+
function buildStepErrorPayload(error, errorMeta, origin, attempt, cumulativeDurationMs) {
|
|
319
|
+
const tag = extractErrorTag(error);
|
|
320
|
+
const classification = lookupErrorClassification(tag, errorMeta);
|
|
321
|
+
const diagnostics = { tag, origin };
|
|
322
|
+
if (classification !== void 0) diagnostics.classification = classification;
|
|
323
|
+
if (attempt !== void 0) diagnostics.attempt = attempt;
|
|
324
|
+
if (cumulativeDurationMs !== void 0) diagnostics.cumulativeDurationMs = cumulativeDurationMs;
|
|
325
|
+
return diagnostics;
|
|
326
|
+
}
|
|
327
|
+
var STEP_TIMEOUT_MARKER = /* @__PURE__ */ Symbol.for("step_timeout_marker");
|
|
328
|
+
function isStepTimeoutError(e) {
|
|
329
|
+
if (typeof e !== "object" || e === null) {
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
332
|
+
if (e.type === "STEP_TIMEOUT") {
|
|
333
|
+
return true;
|
|
334
|
+
}
|
|
335
|
+
return STEP_TIMEOUT_MARKER in e;
|
|
336
|
+
}
|
|
337
|
+
function getStepTimeoutMeta(e) {
|
|
338
|
+
if (typeof e !== "object" || e === null) {
|
|
339
|
+
return void 0;
|
|
340
|
+
}
|
|
341
|
+
if (e.type === "STEP_TIMEOUT") {
|
|
342
|
+
const err2 = e;
|
|
343
|
+
return {
|
|
344
|
+
timeoutMs: err2.timeoutMs,
|
|
345
|
+
stepName: err2.stepName,
|
|
346
|
+
stepKey: err2.stepKey,
|
|
347
|
+
attempt: err2.attempt
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
if (STEP_TIMEOUT_MARKER in e) {
|
|
351
|
+
return e[STEP_TIMEOUT_MARKER];
|
|
352
|
+
}
|
|
353
|
+
return void 0;
|
|
354
|
+
}
|
|
355
|
+
var EARLY_EXIT_SYMBOL = /* @__PURE__ */ Symbol("early-exit");
|
|
356
|
+
function createEarlyExit(error, meta) {
|
|
357
|
+
return {
|
|
358
|
+
[EARLY_EXIT_SYMBOL]: true,
|
|
359
|
+
error,
|
|
360
|
+
meta
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
function isEarlyExit(e) {
|
|
364
|
+
return typeof e === "object" && e !== null && e[EARLY_EXIT_SYMBOL] === true;
|
|
365
|
+
}
|
|
366
|
+
var MAPPER_EXCEPTION_SYMBOL = /* @__PURE__ */ Symbol("mapper-exception");
|
|
367
|
+
function createMapperException(thrown) {
|
|
368
|
+
return { [MAPPER_EXCEPTION_SYMBOL]: true, thrown };
|
|
369
|
+
}
|
|
370
|
+
function isMapperException(e) {
|
|
371
|
+
return typeof e === "object" && e !== null && e[MAPPER_EXCEPTION_SYMBOL] === true;
|
|
372
|
+
}
|
|
373
|
+
function calculateRetryDelay(attempt, options) {
|
|
374
|
+
const { backoff, initialDelay, maxDelay, jitter } = options;
|
|
375
|
+
let delay;
|
|
376
|
+
switch (backoff) {
|
|
377
|
+
case "fixed":
|
|
378
|
+
delay = initialDelay;
|
|
379
|
+
break;
|
|
380
|
+
case "linear":
|
|
381
|
+
delay = initialDelay * attempt;
|
|
382
|
+
break;
|
|
383
|
+
case "exponential":
|
|
384
|
+
delay = initialDelay * Math.pow(2, attempt - 1);
|
|
385
|
+
break;
|
|
386
|
+
}
|
|
387
|
+
delay = Math.min(delay, maxDelay);
|
|
388
|
+
if (jitter) {
|
|
389
|
+
const jitterAmount = delay * 0.25 * Math.random();
|
|
390
|
+
delay = delay + jitterAmount;
|
|
391
|
+
}
|
|
392
|
+
return Math.floor(delay);
|
|
393
|
+
}
|
|
394
|
+
function sleep(ms) {
|
|
395
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
396
|
+
}
|
|
397
|
+
var TIMEOUT_SYMBOL = /* @__PURE__ */ Symbol("timeout");
|
|
398
|
+
var TIMEOUT_OPTION_SYMBOL = /* @__PURE__ */ Symbol("timeout-option");
|
|
399
|
+
function isTimeoutOptionMarker(value) {
|
|
400
|
+
return typeof value === "object" && value !== null && value[TIMEOUT_OPTION_SYMBOL] === true;
|
|
401
|
+
}
|
|
402
|
+
async function executeWithTimeout(operation, options, stepInfo, externalSignal) {
|
|
403
|
+
const controller = new AbortController();
|
|
404
|
+
const behavior = options.onTimeout ?? "error";
|
|
405
|
+
const createTimeoutError = () => {
|
|
406
|
+
if (typeof behavior === "function") {
|
|
407
|
+
return behavior({
|
|
408
|
+
name: stepInfo.name,
|
|
409
|
+
key: stepInfo.key,
|
|
410
|
+
ms: options.ms
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
return options.error ?? {
|
|
414
|
+
type: "STEP_TIMEOUT",
|
|
415
|
+
stepName: stepInfo.name,
|
|
416
|
+
stepKey: stepInfo.key,
|
|
417
|
+
timeoutMs: options.ms,
|
|
418
|
+
attempt: stepInfo.attempt
|
|
419
|
+
};
|
|
420
|
+
};
|
|
421
|
+
let timeoutId;
|
|
422
|
+
if (externalSignal?.aborted) {
|
|
423
|
+
controller.abort(externalSignal.reason);
|
|
424
|
+
}
|
|
425
|
+
let externalAbortHandler;
|
|
426
|
+
if (externalSignal && !externalSignal.aborted) {
|
|
427
|
+
externalAbortHandler = () => controller.abort(externalSignal.reason);
|
|
428
|
+
externalSignal.addEventListener("abort", externalAbortHandler, { once: true });
|
|
429
|
+
}
|
|
430
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
431
|
+
timeoutId = setTimeout(() => {
|
|
432
|
+
if (behavior !== "disconnect") {
|
|
433
|
+
controller.abort();
|
|
434
|
+
}
|
|
435
|
+
if (behavior === "option") {
|
|
436
|
+
reject({ [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms });
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
reject({ [TIMEOUT_SYMBOL]: true, error: createTimeoutError() });
|
|
440
|
+
}, options.ms);
|
|
441
|
+
});
|
|
442
|
+
let operationPromise;
|
|
443
|
+
if (options.signal) {
|
|
444
|
+
operationPromise = Promise.resolve(
|
|
445
|
+
operation(controller.signal)
|
|
446
|
+
);
|
|
447
|
+
} else {
|
|
448
|
+
operationPromise = Promise.resolve(operation());
|
|
449
|
+
}
|
|
450
|
+
try {
|
|
451
|
+
const result = await Promise.race([operationPromise, timeoutPromise]);
|
|
452
|
+
return result;
|
|
453
|
+
} catch (error) {
|
|
454
|
+
if (typeof error === "object" && error !== null && error[TIMEOUT_OPTION_SYMBOL] === true) {
|
|
455
|
+
throw { [TIMEOUT_OPTION_SYMBOL]: true, ms: options.ms };
|
|
456
|
+
}
|
|
457
|
+
if (typeof error === "object" && error !== null && error[TIMEOUT_SYMBOL] === true) {
|
|
458
|
+
if (behavior === "disconnect") {
|
|
459
|
+
operationPromise.catch(() => {
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
const errorToThrow = error.error;
|
|
463
|
+
if (typeof errorToThrow === "object" && errorToThrow !== null && errorToThrow.type !== "STEP_TIMEOUT") {
|
|
464
|
+
const meta = {
|
|
465
|
+
timeoutMs: options.ms,
|
|
466
|
+
stepName: stepInfo.name,
|
|
467
|
+
stepKey: stepInfo.key,
|
|
468
|
+
attempt: stepInfo.attempt
|
|
469
|
+
};
|
|
470
|
+
if (STEP_TIMEOUT_MARKER in errorToThrow) {
|
|
471
|
+
errorToThrow[STEP_TIMEOUT_MARKER] = meta;
|
|
472
|
+
} else {
|
|
473
|
+
Object.defineProperty(errorToThrow, STEP_TIMEOUT_MARKER, {
|
|
474
|
+
value: meta,
|
|
475
|
+
enumerable: false,
|
|
476
|
+
writable: true,
|
|
477
|
+
configurable: false
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
throw errorToThrow;
|
|
482
|
+
}
|
|
483
|
+
throw error;
|
|
484
|
+
} finally {
|
|
485
|
+
clearTimeout(timeoutId);
|
|
486
|
+
if (externalAbortHandler && externalSignal) {
|
|
487
|
+
externalSignal.removeEventListener("abort", externalAbortHandler);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
var DEFAULT_RETRY_CONFIG = {
|
|
492
|
+
backoff: "exponential",
|
|
493
|
+
initialDelay: 100,
|
|
494
|
+
maxDelay: 3e4,
|
|
495
|
+
jitter: true,
|
|
496
|
+
shouldRetry: () => true,
|
|
497
|
+
onRetry: () => {
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
async function runFn(fnOrDeps, optionsOrFn, maybeOptions) {
|
|
501
|
+
if (typeof fnOrDeps !== "function") {
|
|
502
|
+
const deps = fnOrDeps;
|
|
503
|
+
const boundFn = optionsOrFn;
|
|
504
|
+
if (typeof boundFn !== "function") {
|
|
505
|
+
throw new TypeError(
|
|
506
|
+
"[awaitly] run(deps, fn) requires a callback as the second argument. Example: run({ getUser }, async (s) => s.getUser(id))"
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
const classicRun = runFn;
|
|
510
|
+
return classicRun(
|
|
511
|
+
({ step }) => boundFn(bindSteps(deps, step), { step }),
|
|
512
|
+
maybeOptions
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
const fn = fnOrDeps;
|
|
516
|
+
const options = optionsOrFn;
|
|
517
|
+
const {
|
|
518
|
+
onError,
|
|
519
|
+
onEvent,
|
|
520
|
+
catchUnexpected,
|
|
521
|
+
workflowId: providedWorkflowId,
|
|
522
|
+
workflowName,
|
|
523
|
+
context,
|
|
524
|
+
graph,
|
|
525
|
+
_workflowSignal
|
|
526
|
+
} = options && typeof options === "object" ? options : {};
|
|
527
|
+
const workflowId = providedWorkflowId ?? crypto.randomUUID();
|
|
528
|
+
const declaredIds = graph ? new Set(
|
|
529
|
+
Array.isArray(graph) ? graph : graph.states.map((state) => state.semanticId ?? state.id)
|
|
530
|
+
) : void 0;
|
|
531
|
+
const declaredPatterns = declaredIds ? [...declaredIds].filter((id) => id.includes("{")).map(
|
|
532
|
+
(id) => new RegExp(
|
|
533
|
+
`^${id.replaceAll(/[.*+?^$()[\]\\|]/g, String.raw`\$&`).replaceAll(/\{[^}]*\}/g, ".+")}$`
|
|
534
|
+
)
|
|
535
|
+
) : void 0;
|
|
536
|
+
const assertDeclared = (id, kind) => {
|
|
537
|
+
if (!declaredIds || declaredIds.has(id)) return;
|
|
538
|
+
if (declaredPatterns?.some((re) => re.test(id))) return;
|
|
539
|
+
throw new Error(
|
|
540
|
+
`[awaitly] ${kind} id "${id}" is not in the declared workflow graph. Declared ids: ${[...declaredIds].join(", ")}. Either add it to the graph or remove the graph option.`
|
|
541
|
+
);
|
|
542
|
+
};
|
|
543
|
+
const effectiveCatchUnexpected = catchUnexpected ?? defaultCatchUnexpected;
|
|
544
|
+
const activeScopeStack = [];
|
|
545
|
+
let stepIdCounter = 0;
|
|
546
|
+
const generateStepId = (stepKey) => {
|
|
547
|
+
return stepKey ?? `step_${++stepIdCounter}`;
|
|
548
|
+
};
|
|
549
|
+
const emitEvent = (event) => {
|
|
550
|
+
const eventWithContext = event.context !== void 0 || context === void 0 ? event : { ...event, context };
|
|
551
|
+
const eventWithName = workflowName !== void 0 && eventWithContext.workflowName === void 0 ? { ...eventWithContext, workflowName } : eventWithContext;
|
|
552
|
+
if (eventWithName.type === "step_success") {
|
|
553
|
+
const stepId = eventWithName.stepId;
|
|
554
|
+
for (let i = activeScopeStack.length - 1; i >= 0; i--) {
|
|
555
|
+
const scope = activeScopeStack[i];
|
|
556
|
+
if (scope.type === "race" && !scope.winnerId) {
|
|
557
|
+
scope.winnerId = stepId;
|
|
558
|
+
break;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
onEvent?.(eventWithName, context);
|
|
563
|
+
};
|
|
564
|
+
const earlyExit = createEarlyExit;
|
|
565
|
+
const isEarlyExitE = (e) => isEarlyExit(e);
|
|
566
|
+
const wrapForStep = (error, _meta) => {
|
|
567
|
+
return error;
|
|
568
|
+
};
|
|
569
|
+
const isResultLike = (value) => {
|
|
570
|
+
if (typeof value === "function") return false;
|
|
571
|
+
if (value && typeof value === "object" && "ok" in value) return true;
|
|
572
|
+
if (value && typeof value === "object" && "then" in value && typeof value.then === "function") return true;
|
|
573
|
+
return false;
|
|
574
|
+
};
|
|
575
|
+
try {
|
|
576
|
+
let normalizeParallelOperations2 = function(rawOperations) {
|
|
577
|
+
const out = {};
|
|
578
|
+
for (const [key, value2] of Object.entries(rawOperations)) {
|
|
579
|
+
if (typeof value2 === "function") {
|
|
580
|
+
out[key] = value2;
|
|
581
|
+
} else if (value2 && typeof value2 === "object" && "fn" in value2) {
|
|
582
|
+
out[key] = value2.fn;
|
|
583
|
+
} else {
|
|
584
|
+
throw new TypeError(`step.all: operation "${key}" must be a function or { fn, errors? } object`);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
return out;
|
|
588
|
+
}, executeParallelArray2 = function(name, operation) {
|
|
589
|
+
const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
590
|
+
return (async () => {
|
|
591
|
+
const startTime = performance.now();
|
|
592
|
+
let scopeEnded = false;
|
|
593
|
+
activeScopeStack.push({ scopeId, type: "parallel" });
|
|
594
|
+
const emitScopeEnd = () => {
|
|
595
|
+
if (scopeEnded) return;
|
|
596
|
+
scopeEnded = true;
|
|
597
|
+
const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
|
|
598
|
+
if (idx !== -1) activeScopeStack.splice(idx, 1);
|
|
599
|
+
emitEvent({
|
|
600
|
+
type: "scope_end",
|
|
601
|
+
workflowId,
|
|
602
|
+
scopeId,
|
|
603
|
+
ts: Date.now(),
|
|
604
|
+
durationMs: performance.now() - startTime
|
|
605
|
+
});
|
|
606
|
+
};
|
|
607
|
+
emitEvent({
|
|
608
|
+
type: "scope_start",
|
|
609
|
+
workflowId,
|
|
610
|
+
scopeId,
|
|
611
|
+
scopeType: "parallel",
|
|
612
|
+
name,
|
|
613
|
+
ts: Date.now()
|
|
614
|
+
});
|
|
615
|
+
try {
|
|
616
|
+
const result = await operation();
|
|
617
|
+
emitScopeEnd();
|
|
618
|
+
if (!result.ok) {
|
|
619
|
+
onError?.(result.error, name, context);
|
|
620
|
+
throw earlyExit(result.error, {
|
|
621
|
+
origin: "result",
|
|
622
|
+
resultCause: result.cause
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
return result.value;
|
|
626
|
+
} catch (error) {
|
|
627
|
+
emitScopeEnd();
|
|
628
|
+
throw error;
|
|
629
|
+
}
|
|
630
|
+
})();
|
|
631
|
+
}, executeParallelNamed2 = function(operations, options2) {
|
|
632
|
+
const keys = Object.keys(operations);
|
|
633
|
+
const name = options2.name ?? `Parallel(${keys.join(", ")})`;
|
|
634
|
+
const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
635
|
+
return (async () => {
|
|
636
|
+
const startTime = performance.now();
|
|
637
|
+
let scopeEnded = false;
|
|
638
|
+
activeScopeStack.push({ scopeId, type: "parallel" });
|
|
639
|
+
const emitScopeEnd = () => {
|
|
640
|
+
if (scopeEnded) return;
|
|
641
|
+
scopeEnded = true;
|
|
642
|
+
const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
|
|
643
|
+
if (idx !== -1) activeScopeStack.splice(idx, 1);
|
|
644
|
+
emitEvent({
|
|
645
|
+
type: "scope_end",
|
|
646
|
+
workflowId,
|
|
647
|
+
scopeId,
|
|
648
|
+
ts: Date.now(),
|
|
649
|
+
durationMs: performance.now() - startTime
|
|
650
|
+
});
|
|
651
|
+
};
|
|
652
|
+
emitEvent({
|
|
653
|
+
type: "scope_start",
|
|
654
|
+
workflowId,
|
|
655
|
+
scopeId,
|
|
656
|
+
scopeType: "parallel",
|
|
657
|
+
name,
|
|
658
|
+
ts: Date.now()
|
|
659
|
+
});
|
|
660
|
+
try {
|
|
661
|
+
const results = await new Promise((resolve) => {
|
|
662
|
+
if (keys.length === 0) {
|
|
663
|
+
resolve([]);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
let settled = false;
|
|
667
|
+
let pendingCount = keys.length;
|
|
668
|
+
const resultArray = new Array(keys.length);
|
|
669
|
+
for (let i = 0; i < keys.length; i++) {
|
|
670
|
+
const key = keys[i];
|
|
671
|
+
const index = i;
|
|
672
|
+
Promise.resolve(operations[key]()).catch((reason) => err(
|
|
673
|
+
{ type: "PROMISE_REJECTED", cause: reason },
|
|
674
|
+
{ cause: { type: "PROMISE_REJECTION", reason } }
|
|
675
|
+
)).then((result) => {
|
|
676
|
+
if (settled) return;
|
|
677
|
+
if (!result.ok) {
|
|
678
|
+
settled = true;
|
|
679
|
+
resolve([{ key, result }]);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
resultArray[index] = { key, result };
|
|
683
|
+
pendingCount--;
|
|
684
|
+
if (pendingCount === 0) {
|
|
685
|
+
resolve(resultArray);
|
|
686
|
+
}
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
});
|
|
690
|
+
emitScopeEnd();
|
|
691
|
+
const output = {};
|
|
692
|
+
for (const { key, result } of results) {
|
|
693
|
+
if (!result.ok) {
|
|
694
|
+
onError?.(result.error, key, context);
|
|
695
|
+
throw earlyExit(result.error, {
|
|
696
|
+
origin: "result",
|
|
697
|
+
resultCause: result.cause
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
output[key] = result.value;
|
|
701
|
+
}
|
|
702
|
+
return output;
|
|
703
|
+
} catch (error) {
|
|
704
|
+
emitScopeEnd();
|
|
705
|
+
throw error;
|
|
706
|
+
}
|
|
707
|
+
})();
|
|
708
|
+
};
|
|
709
|
+
var normalizeParallelOperations = normalizeParallelOperations2, executeParallelArray = executeParallelArray2, executeParallelNamed = executeParallelNamed2;
|
|
710
|
+
const stepFn = (id, operationOrResult, stepOptions) => {
|
|
711
|
+
return (async () => {
|
|
712
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
713
|
+
throw new Error(
|
|
714
|
+
'[awaitly] step() requires an explicit string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))'
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
assertDeclared(id, "step");
|
|
718
|
+
const parsedOptions = stepOptions ?? {};
|
|
719
|
+
const stepMetadata = extractStepMetadata(parsedOptions);
|
|
720
|
+
const stepName = id;
|
|
721
|
+
const stepKey = parsedOptions.key ?? id;
|
|
722
|
+
const explicitKey = parsedOptions.key ?? id;
|
|
723
|
+
const { description: stepDescription, retry: retryConfig, timeout: timeoutConfig } = parsedOptions;
|
|
724
|
+
const stepId = generateStepId(stepKey);
|
|
725
|
+
const hasEventListeners = onEvent;
|
|
726
|
+
const overallStartTime = hasEventListeners ? performance.now() : 0;
|
|
727
|
+
const isDirectResult = isResultLike(operationOrResult);
|
|
728
|
+
const operation = isDirectResult ? () => operationOrResult : operationOrResult;
|
|
729
|
+
const maxAttempts = Math.max(1, retryConfig?.attempts ?? 1);
|
|
730
|
+
const effectiveRetry = {
|
|
731
|
+
attempts: maxAttempts,
|
|
732
|
+
backoff: retryConfig?.backoff ?? DEFAULT_RETRY_CONFIG.backoff,
|
|
733
|
+
initialDelay: retryConfig?.initialDelay ?? DEFAULT_RETRY_CONFIG.initialDelay,
|
|
734
|
+
maxDelay: retryConfig?.maxDelay ?? DEFAULT_RETRY_CONFIG.maxDelay,
|
|
735
|
+
jitter: retryConfig?.jitter ?? DEFAULT_RETRY_CONFIG.jitter,
|
|
736
|
+
shouldRetry: retryConfig?.shouldRetry ?? DEFAULT_RETRY_CONFIG.shouldRetry,
|
|
737
|
+
onRetry: retryConfig?.onRetry ?? DEFAULT_RETRY_CONFIG.onRetry
|
|
738
|
+
};
|
|
739
|
+
if (onEvent) {
|
|
740
|
+
emitEvent({
|
|
741
|
+
type: "step_start",
|
|
742
|
+
workflowId,
|
|
743
|
+
stepId,
|
|
744
|
+
stepKey,
|
|
745
|
+
name: stepName,
|
|
746
|
+
description: stepDescription,
|
|
747
|
+
ts: Date.now(),
|
|
748
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
let lastResult;
|
|
752
|
+
for (let attempt = 1; attempt <= effectiveRetry.attempts; attempt++) {
|
|
753
|
+
const attemptStartTime = hasEventListeners ? performance.now() : 0;
|
|
754
|
+
try {
|
|
755
|
+
let result;
|
|
756
|
+
if (timeoutConfig) {
|
|
757
|
+
result = await executeWithTimeout(
|
|
758
|
+
operation,
|
|
759
|
+
timeoutConfig,
|
|
760
|
+
{ name: stepName, key: stepKey, attempt },
|
|
761
|
+
_workflowSignal
|
|
762
|
+
);
|
|
763
|
+
} else {
|
|
764
|
+
result = await operation();
|
|
765
|
+
}
|
|
766
|
+
if (result.ok) {
|
|
767
|
+
const durationMs = performance.now() - overallStartTime;
|
|
768
|
+
emitEvent({
|
|
769
|
+
type: "step_success",
|
|
770
|
+
workflowId,
|
|
771
|
+
stepId,
|
|
772
|
+
stepKey,
|
|
773
|
+
name: stepName,
|
|
774
|
+
description: stepDescription,
|
|
775
|
+
ts: Date.now(),
|
|
776
|
+
durationMs,
|
|
777
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
778
|
+
});
|
|
779
|
+
if (explicitKey) {
|
|
780
|
+
emitEvent({
|
|
781
|
+
type: "step_complete",
|
|
782
|
+
workflowId,
|
|
783
|
+
stepKey: explicitKey,
|
|
784
|
+
name: stepName,
|
|
785
|
+
description: stepDescription,
|
|
786
|
+
ts: Date.now(),
|
|
787
|
+
durationMs,
|
|
788
|
+
result,
|
|
789
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
return result.value;
|
|
793
|
+
}
|
|
794
|
+
lastResult = result;
|
|
795
|
+
if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(result.error, attempt)) {
|
|
796
|
+
const delay = calculateRetryDelay(attempt, effectiveRetry);
|
|
797
|
+
emitEvent({
|
|
798
|
+
type: "step_retry",
|
|
799
|
+
workflowId,
|
|
800
|
+
stepId,
|
|
801
|
+
stepKey,
|
|
802
|
+
name: stepName,
|
|
803
|
+
ts: Date.now(),
|
|
804
|
+
attempt: attempt + 1,
|
|
805
|
+
maxAttempts: effectiveRetry.attempts,
|
|
806
|
+
delayMs: delay,
|
|
807
|
+
error: result.error,
|
|
808
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
809
|
+
diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
|
|
810
|
+
});
|
|
811
|
+
effectiveRetry.onRetry(result.error, attempt, delay);
|
|
812
|
+
await sleep(delay);
|
|
813
|
+
continue;
|
|
814
|
+
}
|
|
815
|
+
if (effectiveRetry.attempts > 1) {
|
|
816
|
+
emitEvent({
|
|
817
|
+
type: "step_retries_exhausted",
|
|
818
|
+
workflowId,
|
|
819
|
+
stepId,
|
|
820
|
+
stepKey,
|
|
821
|
+
name: stepName,
|
|
822
|
+
ts: Date.now(),
|
|
823
|
+
durationMs: performance.now() - overallStartTime,
|
|
824
|
+
attempts: attempt,
|
|
825
|
+
lastError: result.error,
|
|
826
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
827
|
+
diagnostics: buildStepErrorPayload(result.error, parsedOptions.errorMeta, "result", attempt, performance.now() - overallStartTime)
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
break;
|
|
831
|
+
} catch (thrown) {
|
|
832
|
+
const durationMs = performance.now() - attemptStartTime;
|
|
833
|
+
if (isTimeoutOptionMarker(thrown)) {
|
|
834
|
+
const timeoutMs = thrown.ms;
|
|
835
|
+
emitEvent({
|
|
836
|
+
type: "step_timeout",
|
|
837
|
+
workflowId,
|
|
838
|
+
stepId,
|
|
839
|
+
stepKey,
|
|
840
|
+
name: stepName,
|
|
841
|
+
ts: Date.now(),
|
|
842
|
+
timeoutMs,
|
|
843
|
+
attempt,
|
|
844
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
845
|
+
diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
|
|
846
|
+
});
|
|
847
|
+
emitEvent({
|
|
848
|
+
type: "step_success",
|
|
849
|
+
workflowId,
|
|
850
|
+
stepId,
|
|
851
|
+
stepKey,
|
|
852
|
+
name: stepName,
|
|
853
|
+
description: stepDescription,
|
|
854
|
+
ts: Date.now(),
|
|
855
|
+
durationMs: performance.now() - overallStartTime,
|
|
856
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
857
|
+
});
|
|
858
|
+
if (explicitKey) {
|
|
859
|
+
emitEvent({
|
|
860
|
+
type: "step_complete",
|
|
861
|
+
workflowId,
|
|
862
|
+
stepKey: explicitKey,
|
|
863
|
+
name: stepName,
|
|
864
|
+
description: stepDescription,
|
|
865
|
+
ts: Date.now(),
|
|
866
|
+
durationMs: performance.now() - overallStartTime,
|
|
867
|
+
result: ok2(void 0),
|
|
868
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
return void 0;
|
|
872
|
+
}
|
|
873
|
+
if (isEarlyExitE(thrown)) {
|
|
874
|
+
emitEvent({
|
|
875
|
+
type: "step_aborted",
|
|
876
|
+
workflowId,
|
|
877
|
+
stepId,
|
|
878
|
+
stepKey,
|
|
879
|
+
name: stepName,
|
|
880
|
+
description: stepDescription,
|
|
881
|
+
ts: Date.now(),
|
|
882
|
+
durationMs,
|
|
883
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
884
|
+
});
|
|
885
|
+
throw thrown;
|
|
886
|
+
}
|
|
887
|
+
if (isStepTimeoutError(thrown)) {
|
|
888
|
+
const timeoutMeta = getStepTimeoutMeta(thrown);
|
|
889
|
+
const timeoutMs = timeoutConfig?.ms ?? timeoutMeta?.timeoutMs ?? 0;
|
|
890
|
+
emitEvent({
|
|
891
|
+
type: "step_timeout",
|
|
892
|
+
workflowId,
|
|
893
|
+
stepId,
|
|
894
|
+
stepKey,
|
|
895
|
+
name: stepName,
|
|
896
|
+
ts: Date.now(),
|
|
897
|
+
timeoutMs,
|
|
898
|
+
attempt,
|
|
899
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
900
|
+
diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt)
|
|
901
|
+
});
|
|
902
|
+
if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
|
|
903
|
+
const delay = calculateRetryDelay(attempt, effectiveRetry);
|
|
904
|
+
emitEvent({
|
|
905
|
+
type: "step_retry",
|
|
906
|
+
workflowId,
|
|
907
|
+
stepId,
|
|
908
|
+
stepKey,
|
|
909
|
+
name: stepName,
|
|
910
|
+
ts: Date.now(),
|
|
911
|
+
attempt: attempt + 1,
|
|
912
|
+
maxAttempts: effectiveRetry.attempts,
|
|
913
|
+
delayMs: delay,
|
|
914
|
+
error: thrown,
|
|
915
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
916
|
+
diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
|
|
917
|
+
});
|
|
918
|
+
effectiveRetry.onRetry(thrown, attempt, delay);
|
|
919
|
+
await sleep(delay);
|
|
920
|
+
continue;
|
|
921
|
+
}
|
|
922
|
+
if (effectiveRetry.attempts > 1) {
|
|
923
|
+
emitEvent({
|
|
924
|
+
type: "step_retries_exhausted",
|
|
925
|
+
workflowId,
|
|
926
|
+
stepId,
|
|
927
|
+
stepKey,
|
|
928
|
+
name: stepName,
|
|
929
|
+
ts: Date.now(),
|
|
930
|
+
durationMs: performance.now() - overallStartTime,
|
|
931
|
+
attempts: attempt,
|
|
932
|
+
lastError: thrown,
|
|
933
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
934
|
+
diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, performance.now() - overallStartTime)
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
const totalDurationMs3 = performance.now() - overallStartTime;
|
|
938
|
+
emitEvent({
|
|
939
|
+
type: "step_error",
|
|
940
|
+
workflowId,
|
|
941
|
+
stepId,
|
|
942
|
+
stepKey,
|
|
943
|
+
name: stepName,
|
|
944
|
+
description: stepDescription,
|
|
945
|
+
ts: Date.now(),
|
|
946
|
+
durationMs: totalDurationMs3,
|
|
947
|
+
error: thrown,
|
|
948
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
949
|
+
diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "timeout", attempt, totalDurationMs3)
|
|
950
|
+
});
|
|
951
|
+
if (explicitKey) {
|
|
952
|
+
emitEvent({
|
|
953
|
+
type: "step_complete",
|
|
954
|
+
workflowId,
|
|
955
|
+
stepKey: explicitKey,
|
|
956
|
+
name: stepName,
|
|
957
|
+
description: stepDescription,
|
|
958
|
+
ts: Date.now(),
|
|
959
|
+
durationMs: totalDurationMs3,
|
|
960
|
+
result: err(thrown, { cause: thrown }),
|
|
961
|
+
meta: { origin: "throw", thrown },
|
|
962
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
onError?.(thrown, stepName, context);
|
|
966
|
+
throw earlyExit(thrown, { origin: "throw", thrown });
|
|
967
|
+
}
|
|
968
|
+
if (attempt < effectiveRetry.attempts && effectiveRetry.shouldRetry(thrown, attempt)) {
|
|
969
|
+
const delay = calculateRetryDelay(attempt, effectiveRetry);
|
|
970
|
+
emitEvent({
|
|
971
|
+
type: "step_retry",
|
|
972
|
+
workflowId,
|
|
973
|
+
stepId,
|
|
974
|
+
stepKey,
|
|
975
|
+
name: stepName,
|
|
976
|
+
ts: Date.now(),
|
|
977
|
+
attempt: attempt + 1,
|
|
978
|
+
maxAttempts: effectiveRetry.attempts,
|
|
979
|
+
delayMs: delay,
|
|
980
|
+
error: thrown,
|
|
981
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
982
|
+
diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
|
|
983
|
+
});
|
|
984
|
+
effectiveRetry.onRetry(thrown, attempt, delay);
|
|
985
|
+
await sleep(delay);
|
|
986
|
+
continue;
|
|
987
|
+
}
|
|
988
|
+
if (effectiveRetry.attempts > 1 && !isStepTimeoutError(thrown)) {
|
|
989
|
+
emitEvent({
|
|
990
|
+
type: "step_retries_exhausted",
|
|
991
|
+
workflowId,
|
|
992
|
+
stepId,
|
|
993
|
+
stepKey,
|
|
994
|
+
name: stepName,
|
|
995
|
+
ts: Date.now(),
|
|
996
|
+
durationMs: performance.now() - overallStartTime,
|
|
997
|
+
attempts: attempt,
|
|
998
|
+
lastError: thrown,
|
|
999
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
1000
|
+
diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, performance.now() - overallStartTime)
|
|
1001
|
+
});
|
|
1002
|
+
}
|
|
1003
|
+
const totalDurationMs2 = performance.now() - overallStartTime;
|
|
1004
|
+
let mappedError;
|
|
1005
|
+
try {
|
|
1006
|
+
mappedError = effectiveCatchUnexpected(thrown);
|
|
1007
|
+
} catch (mapperError) {
|
|
1008
|
+
throw createMapperException(mapperError);
|
|
1009
|
+
}
|
|
1010
|
+
emitEvent({
|
|
1011
|
+
type: "step_error",
|
|
1012
|
+
workflowId,
|
|
1013
|
+
stepId,
|
|
1014
|
+
stepKey,
|
|
1015
|
+
name: stepName,
|
|
1016
|
+
description: stepDescription,
|
|
1017
|
+
ts: Date.now(),
|
|
1018
|
+
durationMs: totalDurationMs2,
|
|
1019
|
+
error: mappedError,
|
|
1020
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
1021
|
+
diagnostics: buildStepErrorPayload(thrown, parsedOptions.errorMeta, "throw", attempt, totalDurationMs2)
|
|
1022
|
+
});
|
|
1023
|
+
if (explicitKey) {
|
|
1024
|
+
emitEvent({
|
|
1025
|
+
type: "step_complete",
|
|
1026
|
+
workflowId,
|
|
1027
|
+
stepKey: explicitKey,
|
|
1028
|
+
name: stepName,
|
|
1029
|
+
description: stepDescription,
|
|
1030
|
+
ts: Date.now(),
|
|
1031
|
+
durationMs: totalDurationMs2,
|
|
1032
|
+
result: err(mappedError, { cause: thrown }),
|
|
1033
|
+
meta: { origin: "throw", thrown },
|
|
1034
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
onError?.(mappedError, stepName, context);
|
|
1038
|
+
throw earlyExit(mappedError, { origin: "throw", thrown });
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
const errorResult = lastResult;
|
|
1042
|
+
const totalDurationMs = performance.now() - overallStartTime;
|
|
1043
|
+
const wrappedError = wrapForStep(errorResult.error, {
|
|
1044
|
+
origin: "result",
|
|
1045
|
+
resultCause: errorResult.cause
|
|
1046
|
+
});
|
|
1047
|
+
emitEvent({
|
|
1048
|
+
type: "step_error",
|
|
1049
|
+
workflowId,
|
|
1050
|
+
stepId,
|
|
1051
|
+
stepKey,
|
|
1052
|
+
name: stepName,
|
|
1053
|
+
description: stepDescription,
|
|
1054
|
+
ts: Date.now(),
|
|
1055
|
+
durationMs: totalDurationMs,
|
|
1056
|
+
error: wrappedError,
|
|
1057
|
+
...stepMetadata && { metadata: stepMetadata },
|
|
1058
|
+
diagnostics: buildStepErrorPayload(errorResult.error, parsedOptions.errorMeta, "result", effectiveRetry.attempts, totalDurationMs)
|
|
1059
|
+
});
|
|
1060
|
+
if (explicitKey) {
|
|
1061
|
+
emitEvent({
|
|
1062
|
+
type: "step_complete",
|
|
1063
|
+
workflowId,
|
|
1064
|
+
stepKey: explicitKey,
|
|
1065
|
+
name: stepName,
|
|
1066
|
+
description: stepDescription,
|
|
1067
|
+
ts: Date.now(),
|
|
1068
|
+
durationMs: totalDurationMs,
|
|
1069
|
+
result: errorResult,
|
|
1070
|
+
meta: { origin: "result", resultCause: errorResult.cause },
|
|
1071
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
onError?.(wrappedError, stepName, context);
|
|
1075
|
+
throw earlyExit(wrappedError, {
|
|
1076
|
+
origin: "result",
|
|
1077
|
+
resultCause: errorResult.cause
|
|
1078
|
+
});
|
|
1079
|
+
})();
|
|
1080
|
+
};
|
|
1081
|
+
stepFn.try = (id, operation, opts) => {
|
|
1082
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
1083
|
+
throw new Error(
|
|
1084
|
+
'[awaitly] step.try() requires an explicit string ID as the first argument. Example: step.try("parse", () => JSON.parse(str), { error: "PARSE_ERROR" })'
|
|
1085
|
+
);
|
|
1086
|
+
}
|
|
1087
|
+
assertDeclared(id, "step");
|
|
1088
|
+
const mapToError = "error" in opts ? () => opts.error : opts.onError;
|
|
1089
|
+
if (opts.retry || opts.timeout) {
|
|
1090
|
+
return stepFn.retry(
|
|
1091
|
+
id,
|
|
1092
|
+
async () => {
|
|
1093
|
+
try {
|
|
1094
|
+
return ok2(await operation());
|
|
1095
|
+
} catch (cause) {
|
|
1096
|
+
return err(mapToError(cause), { cause });
|
|
1097
|
+
}
|
|
1098
|
+
},
|
|
1099
|
+
{
|
|
1100
|
+
attempts: opts.retry?.attempts ?? 1,
|
|
1101
|
+
...opts.retry ?? {},
|
|
1102
|
+
key: opts.key,
|
|
1103
|
+
timeout: opts.timeout
|
|
1104
|
+
}
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
const stepKey = opts.key ?? id;
|
|
1108
|
+
const stepName = id;
|
|
1109
|
+
const stepId = id;
|
|
1110
|
+
const hasEventListeners = onEvent;
|
|
1111
|
+
return (async () => {
|
|
1112
|
+
const startTime = hasEventListeners ? performance.now() : 0;
|
|
1113
|
+
if (onEvent) {
|
|
1114
|
+
emitEvent({
|
|
1115
|
+
type: "step_start",
|
|
1116
|
+
workflowId,
|
|
1117
|
+
stepId,
|
|
1118
|
+
stepKey,
|
|
1119
|
+
name: stepName,
|
|
1120
|
+
ts: Date.now()
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
try {
|
|
1124
|
+
const value2 = await operation();
|
|
1125
|
+
const durationMs = performance.now() - startTime;
|
|
1126
|
+
emitEvent({
|
|
1127
|
+
type: "step_success",
|
|
1128
|
+
workflowId,
|
|
1129
|
+
stepId,
|
|
1130
|
+
stepKey,
|
|
1131
|
+
name: stepName,
|
|
1132
|
+
ts: Date.now(),
|
|
1133
|
+
durationMs
|
|
1134
|
+
});
|
|
1135
|
+
if (stepKey) {
|
|
1136
|
+
emitEvent({
|
|
1137
|
+
type: "step_complete",
|
|
1138
|
+
workflowId,
|
|
1139
|
+
stepKey,
|
|
1140
|
+
name: stepName,
|
|
1141
|
+
ts: Date.now(),
|
|
1142
|
+
durationMs,
|
|
1143
|
+
result: ok2(value2)
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
return value2;
|
|
1147
|
+
} catch (error) {
|
|
1148
|
+
const mapped = mapToError(error);
|
|
1149
|
+
const durationMs = performance.now() - startTime;
|
|
1150
|
+
const wrappedError = wrapForStep(mapped, { origin: "throw", thrown: error });
|
|
1151
|
+
emitEvent({
|
|
1152
|
+
type: "step_error",
|
|
1153
|
+
workflowId,
|
|
1154
|
+
stepId,
|
|
1155
|
+
stepKey,
|
|
1156
|
+
name: stepName,
|
|
1157
|
+
ts: Date.now(),
|
|
1158
|
+
durationMs,
|
|
1159
|
+
error: wrappedError
|
|
1160
|
+
});
|
|
1161
|
+
if (stepKey) {
|
|
1162
|
+
emitEvent({
|
|
1163
|
+
type: "step_complete",
|
|
1164
|
+
workflowId,
|
|
1165
|
+
stepKey,
|
|
1166
|
+
name: stepName,
|
|
1167
|
+
ts: Date.now(),
|
|
1168
|
+
durationMs,
|
|
1169
|
+
result: err(mapped, { cause: error }),
|
|
1170
|
+
meta: { origin: "throw", thrown: error }
|
|
1171
|
+
});
|
|
1172
|
+
}
|
|
1173
|
+
onError?.(wrappedError, stepName, context);
|
|
1174
|
+
throw earlyExit(wrappedError, { origin: "throw", thrown: error });
|
|
1175
|
+
}
|
|
1176
|
+
})();
|
|
1177
|
+
};
|
|
1178
|
+
stepFn.fromResult = (id, operation, opts) => {
|
|
1179
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
1180
|
+
throw new Error(
|
|
1181
|
+
'[awaitly] step.fromResult() requires an explicit string ID as the first argument. Example: step.fromResult("callProvider", () => callProvider(input), { onError: (e) => ({ type: "FAILED" }) })'
|
|
1182
|
+
);
|
|
1183
|
+
}
|
|
1184
|
+
assertDeclared(id, "step");
|
|
1185
|
+
const stepKey = opts.key ?? id;
|
|
1186
|
+
const stepName = id;
|
|
1187
|
+
const stepId = id;
|
|
1188
|
+
const mapToError = "error" in opts ? () => opts.error : opts.onError;
|
|
1189
|
+
const hasEventListeners = onEvent;
|
|
1190
|
+
return (async () => {
|
|
1191
|
+
const startTime = hasEventListeners ? performance.now() : 0;
|
|
1192
|
+
if (onEvent) {
|
|
1193
|
+
emitEvent({
|
|
1194
|
+
type: "step_start",
|
|
1195
|
+
workflowId,
|
|
1196
|
+
stepId,
|
|
1197
|
+
stepKey,
|
|
1198
|
+
name: stepName,
|
|
1199
|
+
ts: Date.now()
|
|
1200
|
+
});
|
|
1201
|
+
}
|
|
1202
|
+
const result = await operation();
|
|
1203
|
+
if (result.ok) {
|
|
1204
|
+
const durationMs = performance.now() - startTime;
|
|
1205
|
+
emitEvent({
|
|
1206
|
+
type: "step_success",
|
|
1207
|
+
workflowId,
|
|
1208
|
+
stepId,
|
|
1209
|
+
stepKey,
|
|
1210
|
+
name: stepName,
|
|
1211
|
+
ts: Date.now(),
|
|
1212
|
+
durationMs
|
|
1213
|
+
});
|
|
1214
|
+
if (stepKey) {
|
|
1215
|
+
emitEvent({
|
|
1216
|
+
type: "step_complete",
|
|
1217
|
+
workflowId,
|
|
1218
|
+
stepKey,
|
|
1219
|
+
name: stepName,
|
|
1220
|
+
ts: Date.now(),
|
|
1221
|
+
durationMs,
|
|
1222
|
+
result: ok2(result.value)
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
return result.value;
|
|
1226
|
+
} else {
|
|
1227
|
+
const mapped = mapToError(result.error);
|
|
1228
|
+
const durationMs = performance.now() - startTime;
|
|
1229
|
+
const wrappedError = wrapForStep(mapped, {
|
|
1230
|
+
origin: "result",
|
|
1231
|
+
resultCause: result.error
|
|
1232
|
+
});
|
|
1233
|
+
emitEvent({
|
|
1234
|
+
type: "step_error",
|
|
1235
|
+
workflowId,
|
|
1236
|
+
stepId,
|
|
1237
|
+
stepKey,
|
|
1238
|
+
name: stepName,
|
|
1239
|
+
ts: Date.now(),
|
|
1240
|
+
durationMs,
|
|
1241
|
+
error: wrappedError
|
|
1242
|
+
});
|
|
1243
|
+
if (stepKey) {
|
|
1244
|
+
emitEvent({
|
|
1245
|
+
type: "step_complete",
|
|
1246
|
+
workflowId,
|
|
1247
|
+
stepKey,
|
|
1248
|
+
name: stepName,
|
|
1249
|
+
ts: Date.now(),
|
|
1250
|
+
durationMs,
|
|
1251
|
+
result: err(mapped, { cause: result.error }),
|
|
1252
|
+
meta: { origin: "result", resultCause: result.error }
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
onError?.(wrappedError, stepName, context);
|
|
1256
|
+
throw earlyExit(wrappedError, {
|
|
1257
|
+
origin: "result",
|
|
1258
|
+
resultCause: result.error
|
|
1259
|
+
});
|
|
1260
|
+
}
|
|
1261
|
+
})();
|
|
1262
|
+
};
|
|
1263
|
+
stepFn.fromNullable = (id, operation, onNull, options2) => {
|
|
1264
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
1265
|
+
throw new Error(
|
|
1266
|
+
'[awaitly] step.fromNullable() requires an explicit string ID as the first argument. Example: step.fromNullable("getUser", () => db.find(id), () => ({ type: "NOT_FOUND" }))'
|
|
1267
|
+
);
|
|
1268
|
+
}
|
|
1269
|
+
return stepFn(
|
|
1270
|
+
id,
|
|
1271
|
+
async () => {
|
|
1272
|
+
const value2 = await operation();
|
|
1273
|
+
return value2 != null ? ok2(value2) : err(onNull());
|
|
1274
|
+
},
|
|
1275
|
+
options2
|
|
1276
|
+
);
|
|
1277
|
+
};
|
|
1278
|
+
stepFn.retry = (id, operation, options2) => {
|
|
1279
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
1280
|
+
throw new Error(
|
|
1281
|
+
'[awaitly] step.retry() requires an explicit string ID as the first argument. Example: step.retry("fetchData", () => fetchData(), { attempts: 3 })'
|
|
1282
|
+
);
|
|
1283
|
+
}
|
|
1284
|
+
return stepFn(id, operation, {
|
|
1285
|
+
key: options2.key ?? id,
|
|
1286
|
+
retry: {
|
|
1287
|
+
attempts: options2.attempts,
|
|
1288
|
+
backoff: options2.backoff,
|
|
1289
|
+
initialDelay: options2.initialDelay,
|
|
1290
|
+
maxDelay: options2.maxDelay,
|
|
1291
|
+
jitter: options2.jitter,
|
|
1292
|
+
shouldRetry: options2.shouldRetry,
|
|
1293
|
+
onRetry: options2.onRetry
|
|
1294
|
+
},
|
|
1295
|
+
timeout: options2.timeout
|
|
1296
|
+
});
|
|
1297
|
+
};
|
|
1298
|
+
stepFn.withTimeout = (id, operation, options2) => {
|
|
1299
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
1300
|
+
throw new Error(
|
|
1301
|
+
'[awaitly] step.withTimeout() requires an explicit string ID as the first argument. Example: step.withTimeout("slowOp", () => slowOp(), { ms: 5000 })'
|
|
1302
|
+
);
|
|
1303
|
+
}
|
|
1304
|
+
return stepFn(
|
|
1305
|
+
id,
|
|
1306
|
+
operation,
|
|
1307
|
+
{
|
|
1308
|
+
key: options2.key ?? id,
|
|
1309
|
+
timeout: options2
|
|
1310
|
+
}
|
|
1311
|
+
);
|
|
1312
|
+
};
|
|
1313
|
+
stepFn.sleep = (id, duration, options2) => {
|
|
1314
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
1315
|
+
throw new Error(
|
|
1316
|
+
'[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")'
|
|
1317
|
+
);
|
|
1318
|
+
}
|
|
1319
|
+
const d = typeof duration === "string" ? parseDurationString(duration) : duration;
|
|
1320
|
+
if (!d) {
|
|
1321
|
+
throw new Error(`step.sleep: invalid duration '${duration}'`);
|
|
1322
|
+
}
|
|
1323
|
+
const ms = d.millis;
|
|
1324
|
+
const userSignal = options2?.signal;
|
|
1325
|
+
return stepFn(
|
|
1326
|
+
id,
|
|
1327
|
+
async () => {
|
|
1328
|
+
if (_workflowSignal?.aborted || userSignal?.aborted) {
|
|
1329
|
+
const e = new Error("Sleep aborted");
|
|
1330
|
+
e.name = "AbortError";
|
|
1331
|
+
throw e;
|
|
1332
|
+
}
|
|
1333
|
+
return new Promise((resolve, reject) => {
|
|
1334
|
+
const state = { timeoutId: void 0 };
|
|
1335
|
+
const onAbort = () => {
|
|
1336
|
+
if (state.timeoutId) clearTimeout(state.timeoutId);
|
|
1337
|
+
const e = new Error("Sleep aborted");
|
|
1338
|
+
e.name = "AbortError";
|
|
1339
|
+
reject(e);
|
|
1340
|
+
};
|
|
1341
|
+
_workflowSignal?.addEventListener("abort", onAbort, { once: true });
|
|
1342
|
+
userSignal?.addEventListener("abort", onAbort, { once: true });
|
|
1343
|
+
state.timeoutId = setTimeout(() => {
|
|
1344
|
+
_workflowSignal?.removeEventListener("abort", onAbort);
|
|
1345
|
+
userSignal?.removeEventListener("abort", onAbort);
|
|
1346
|
+
resolve(ok2(void 0));
|
|
1347
|
+
}, ms);
|
|
1348
|
+
});
|
|
1349
|
+
},
|
|
1350
|
+
{
|
|
1351
|
+
key: options2?.key ?? id,
|
|
1352
|
+
description: options2?.description
|
|
1353
|
+
}
|
|
1354
|
+
);
|
|
1355
|
+
};
|
|
1356
|
+
stepFn.all = ((...args) => {
|
|
1357
|
+
if (typeof args[0] !== "string") {
|
|
1358
|
+
throw new TypeError(
|
|
1359
|
+
"step.all(name, ...): first argument must be a string (step name). Example: step.all('Fetch data', { user: () => fetchUser(), posts: () => fetchPosts() })"
|
|
1360
|
+
);
|
|
1361
|
+
}
|
|
1362
|
+
const name = args[0];
|
|
1363
|
+
const second = args[1];
|
|
1364
|
+
if (typeof second === "function") {
|
|
1365
|
+
return executeParallelArray2(name, second);
|
|
1366
|
+
}
|
|
1367
|
+
if (second && typeof second === "object" && !Array.isArray(second)) {
|
|
1368
|
+
const rawOperations = second;
|
|
1369
|
+
const normalizedOperations = normalizeParallelOperations2(rawOperations);
|
|
1370
|
+
return executeParallelNamed2(normalizedOperations, { name });
|
|
1371
|
+
}
|
|
1372
|
+
throw new TypeError(
|
|
1373
|
+
"step.all(name, ...): second argument must be a function (array form) or an object of operations (object form)."
|
|
1374
|
+
);
|
|
1375
|
+
});
|
|
1376
|
+
stepFn.race = (name, operation) => {
|
|
1377
|
+
const scopeId = `scope_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
|
1378
|
+
return (async () => {
|
|
1379
|
+
const startTime = performance.now();
|
|
1380
|
+
let scopeEnded = false;
|
|
1381
|
+
const scopeEntry = { scopeId, type: "race", winnerId: void 0 };
|
|
1382
|
+
activeScopeStack.push(scopeEntry);
|
|
1383
|
+
const emitScopeEnd = () => {
|
|
1384
|
+
if (scopeEnded) return;
|
|
1385
|
+
scopeEnded = true;
|
|
1386
|
+
const idx = activeScopeStack.findIndex((s) => s.scopeId === scopeId);
|
|
1387
|
+
if (idx !== -1) activeScopeStack.splice(idx, 1);
|
|
1388
|
+
emitEvent({
|
|
1389
|
+
type: "scope_end",
|
|
1390
|
+
workflowId,
|
|
1391
|
+
scopeId,
|
|
1392
|
+
ts: Date.now(),
|
|
1393
|
+
durationMs: performance.now() - startTime,
|
|
1394
|
+
winnerId: scopeEntry.winnerId
|
|
1395
|
+
});
|
|
1396
|
+
};
|
|
1397
|
+
emitEvent({
|
|
1398
|
+
type: "scope_start",
|
|
1399
|
+
workflowId,
|
|
1400
|
+
scopeId,
|
|
1401
|
+
scopeType: "race",
|
|
1402
|
+
name,
|
|
1403
|
+
ts: Date.now()
|
|
1404
|
+
});
|
|
1405
|
+
try {
|
|
1406
|
+
const result = await operation();
|
|
1407
|
+
emitScopeEnd();
|
|
1408
|
+
if (!result.ok) {
|
|
1409
|
+
onError?.(result.error, name, context);
|
|
1410
|
+
throw earlyExit(result.error, {
|
|
1411
|
+
origin: "result",
|
|
1412
|
+
resultCause: result.cause
|
|
1413
|
+
});
|
|
1414
|
+
}
|
|
1415
|
+
return result.value;
|
|
1416
|
+
} catch (error) {
|
|
1417
|
+
emitScopeEnd();
|
|
1418
|
+
throw error;
|
|
1419
|
+
}
|
|
1420
|
+
})();
|
|
1421
|
+
};
|
|
1422
|
+
stepFn.if = (id, conditionLabel, condition) => {
|
|
1423
|
+
assertDeclared(id, "decision");
|
|
1424
|
+
const value2 = condition();
|
|
1425
|
+
emitEvent({
|
|
1426
|
+
type: "decision",
|
|
1427
|
+
workflowId,
|
|
1428
|
+
decisionId: id,
|
|
1429
|
+
label: conditionLabel,
|
|
1430
|
+
branch: value2 ? "then" : "else",
|
|
1431
|
+
value: value2,
|
|
1432
|
+
ts: Date.now()
|
|
1433
|
+
});
|
|
1434
|
+
return value2;
|
|
1435
|
+
};
|
|
1436
|
+
stepFn.label = stepFn.if;
|
|
1437
|
+
stepFn.branch = async (id, options2) => {
|
|
1438
|
+
const { condition, then: thenFn, else: elseFn } = options2;
|
|
1439
|
+
assertDeclared(id, "decision");
|
|
1440
|
+
const conditionResult = condition();
|
|
1441
|
+
const branch = conditionResult ? "then" : "else";
|
|
1442
|
+
const startTime = performance.now();
|
|
1443
|
+
emitEvent({
|
|
1444
|
+
type: "decision",
|
|
1445
|
+
workflowId,
|
|
1446
|
+
decisionId: id,
|
|
1447
|
+
label: options2.conditionLabel,
|
|
1448
|
+
branch,
|
|
1449
|
+
value: conditionResult,
|
|
1450
|
+
phase: "start",
|
|
1451
|
+
ts: Date.now()
|
|
1452
|
+
});
|
|
1453
|
+
const emitEnd = () => {
|
|
1454
|
+
emitEvent({
|
|
1455
|
+
type: "decision",
|
|
1456
|
+
workflowId,
|
|
1457
|
+
decisionId: id,
|
|
1458
|
+
label: options2.conditionLabel,
|
|
1459
|
+
branch,
|
|
1460
|
+
value: conditionResult,
|
|
1461
|
+
phase: "end",
|
|
1462
|
+
durationMs: performance.now() - startTime,
|
|
1463
|
+
ts: Date.now()
|
|
1464
|
+
});
|
|
1465
|
+
};
|
|
1466
|
+
try {
|
|
1467
|
+
if (conditionResult) {
|
|
1468
|
+
return await thenFn();
|
|
1469
|
+
} else if (elseFn) {
|
|
1470
|
+
return await elseFn();
|
|
1471
|
+
}
|
|
1472
|
+
return void 0;
|
|
1473
|
+
} finally {
|
|
1474
|
+
emitEnd();
|
|
1475
|
+
}
|
|
1476
|
+
};
|
|
1477
|
+
stepFn.arm = (fn2, errors) => {
|
|
1478
|
+
return { fn: fn2, errors };
|
|
1479
|
+
};
|
|
1480
|
+
stepFn.forEach = async (_id, items, options2) => {
|
|
1481
|
+
const results = [];
|
|
1482
|
+
const maxIterations = options2.maxIterations;
|
|
1483
|
+
let index = 0;
|
|
1484
|
+
const isRunForm = "run" in options2;
|
|
1485
|
+
const asyncItems = Symbol.asyncIterator in items ? items : (async function* () {
|
|
1486
|
+
yield* items;
|
|
1487
|
+
})();
|
|
1488
|
+
for await (const item of asyncItems) {
|
|
1489
|
+
if (maxIterations !== void 0 && index >= maxIterations) {
|
|
1490
|
+
break;
|
|
1491
|
+
}
|
|
1492
|
+
let result;
|
|
1493
|
+
if (isRunForm) {
|
|
1494
|
+
const runOptions = options2;
|
|
1495
|
+
result = await runOptions.run(item, index);
|
|
1496
|
+
} else {
|
|
1497
|
+
const itemOptions = options2;
|
|
1498
|
+
result = await itemOptions.item.handler(item, index, stepFn);
|
|
1499
|
+
}
|
|
1500
|
+
results.push(result);
|
|
1501
|
+
index++;
|
|
1502
|
+
}
|
|
1503
|
+
return results;
|
|
1504
|
+
};
|
|
1505
|
+
stepFn.item = (handler) => {
|
|
1506
|
+
return {
|
|
1507
|
+
__forEachItemHandler: true,
|
|
1508
|
+
handler
|
|
1509
|
+
};
|
|
1510
|
+
};
|
|
1511
|
+
stepFn.dep = (_name, fn2) => {
|
|
1512
|
+
return fn2;
|
|
1513
|
+
};
|
|
1514
|
+
stepFn.workflow = (id, getter, options2) => {
|
|
1515
|
+
return stepFn(id, getter, options2);
|
|
1516
|
+
};
|
|
1517
|
+
stepFn.map = async (id, items, mapper, options2) => {
|
|
1518
|
+
const concurrency = options2?.concurrency ?? items.length;
|
|
1519
|
+
return stepFn(
|
|
1520
|
+
id,
|
|
1521
|
+
() => {
|
|
1522
|
+
if (concurrency >= items.length) {
|
|
1523
|
+
return allAsync(items.map((item, index) => mapper(item, index)));
|
|
1524
|
+
} else {
|
|
1525
|
+
return (async () => {
|
|
1526
|
+
const results = [];
|
|
1527
|
+
for (let i = 0; i < items.length; i += concurrency) {
|
|
1528
|
+
const batch = items.slice(i, i + concurrency);
|
|
1529
|
+
const batchResult = await allAsync(
|
|
1530
|
+
batch.map((item, batchIndex) => mapper(item, i + batchIndex))
|
|
1531
|
+
);
|
|
1532
|
+
if (!batchResult.ok) {
|
|
1533
|
+
return batchResult;
|
|
1534
|
+
}
|
|
1535
|
+
results.push(...batchResult.value);
|
|
1536
|
+
}
|
|
1537
|
+
return ok2(results);
|
|
1538
|
+
})();
|
|
1539
|
+
}
|
|
1540
|
+
},
|
|
1541
|
+
{ key: options2?.key }
|
|
1542
|
+
);
|
|
1543
|
+
};
|
|
1544
|
+
stepFn.withFallback = (id, operation, options2) => {
|
|
1545
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
1546
|
+
throw new Error(
|
|
1547
|
+
'[awaitly] step.withFallback() requires an explicit string ID as the first argument. Example: step.withFallback("getUser", () => fetchUser(id), { fallback: () => fetchFromCache(id) })'
|
|
1548
|
+
);
|
|
1549
|
+
}
|
|
1550
|
+
assertDeclared(id, "step");
|
|
1551
|
+
const stepKey = options2.key ?? id;
|
|
1552
|
+
const stepName = id;
|
|
1553
|
+
const stepId = generateStepId(stepKey);
|
|
1554
|
+
const hasEventListeners = onEvent;
|
|
1555
|
+
return (async () => {
|
|
1556
|
+
const startTime = hasEventListeners ? performance.now() : 0;
|
|
1557
|
+
if (onEvent) {
|
|
1558
|
+
emitEvent({
|
|
1559
|
+
type: "step_start",
|
|
1560
|
+
workflowId,
|
|
1561
|
+
stepId,
|
|
1562
|
+
stepKey,
|
|
1563
|
+
name: stepName,
|
|
1564
|
+
ts: Date.now()
|
|
1565
|
+
});
|
|
1566
|
+
}
|
|
1567
|
+
let primaryResult;
|
|
1568
|
+
try {
|
|
1569
|
+
primaryResult = await operation();
|
|
1570
|
+
} catch (thrown) {
|
|
1571
|
+
if (isEarlyExitE(thrown)) {
|
|
1572
|
+
emitEvent({
|
|
1573
|
+
type: "step_aborted",
|
|
1574
|
+
workflowId,
|
|
1575
|
+
stepId,
|
|
1576
|
+
stepKey,
|
|
1577
|
+
name: stepName,
|
|
1578
|
+
ts: Date.now(),
|
|
1579
|
+
durationMs: performance.now() - startTime
|
|
1580
|
+
});
|
|
1581
|
+
throw thrown;
|
|
1582
|
+
}
|
|
1583
|
+
let mappedError;
|
|
1584
|
+
try {
|
|
1585
|
+
mappedError = effectiveCatchUnexpected(thrown);
|
|
1586
|
+
} catch (mapperError) {
|
|
1587
|
+
throw createMapperException(mapperError);
|
|
1588
|
+
}
|
|
1589
|
+
if (options2.on !== void 0 && options2.on !== mappedError) {
|
|
1590
|
+
const durationMs2 = performance.now() - startTime;
|
|
1591
|
+
emitEvent({
|
|
1592
|
+
type: "step_error",
|
|
1593
|
+
workflowId,
|
|
1594
|
+
stepId,
|
|
1595
|
+
stepKey,
|
|
1596
|
+
name: stepName,
|
|
1597
|
+
ts: Date.now(),
|
|
1598
|
+
durationMs: durationMs2,
|
|
1599
|
+
error: mappedError
|
|
1600
|
+
});
|
|
1601
|
+
if (stepKey) {
|
|
1602
|
+
emitEvent({
|
|
1603
|
+
type: "step_complete",
|
|
1604
|
+
workflowId,
|
|
1605
|
+
stepKey,
|
|
1606
|
+
name: stepName,
|
|
1607
|
+
ts: Date.now(),
|
|
1608
|
+
durationMs: durationMs2,
|
|
1609
|
+
result: err(mappedError, { cause: thrown }),
|
|
1610
|
+
meta: { origin: "throw", thrown }
|
|
1611
|
+
});
|
|
1612
|
+
}
|
|
1613
|
+
onError?.(mappedError, stepName, context);
|
|
1614
|
+
throw earlyExit(mappedError, { origin: "throw", thrown });
|
|
1615
|
+
}
|
|
1616
|
+
let fallbackResultFromThrow;
|
|
1617
|
+
try {
|
|
1618
|
+
fallbackResultFromThrow = await options2.fallback();
|
|
1619
|
+
} catch (fallbackThrown) {
|
|
1620
|
+
if (isEarlyExitE(fallbackThrown)) {
|
|
1621
|
+
emitEvent({
|
|
1622
|
+
type: "step_aborted",
|
|
1623
|
+
workflowId,
|
|
1624
|
+
stepId,
|
|
1625
|
+
stepKey,
|
|
1626
|
+
name: stepName,
|
|
1627
|
+
ts: Date.now(),
|
|
1628
|
+
durationMs: performance.now() - startTime
|
|
1629
|
+
});
|
|
1630
|
+
throw fallbackThrown;
|
|
1631
|
+
}
|
|
1632
|
+
let fallbackMappedError;
|
|
1633
|
+
try {
|
|
1634
|
+
fallbackMappedError = effectiveCatchUnexpected(fallbackThrown);
|
|
1635
|
+
} catch (mapperError) {
|
|
1636
|
+
throw createMapperException(mapperError);
|
|
1637
|
+
}
|
|
1638
|
+
const durationMs2 = performance.now() - startTime;
|
|
1639
|
+
emitEvent({
|
|
1640
|
+
type: "step_error",
|
|
1641
|
+
workflowId,
|
|
1642
|
+
stepId,
|
|
1643
|
+
stepKey,
|
|
1644
|
+
name: stepName,
|
|
1645
|
+
ts: Date.now(),
|
|
1646
|
+
durationMs: durationMs2,
|
|
1647
|
+
error: fallbackMappedError
|
|
1648
|
+
});
|
|
1649
|
+
if (stepKey) {
|
|
1650
|
+
emitEvent({
|
|
1651
|
+
type: "step_complete",
|
|
1652
|
+
workflowId,
|
|
1653
|
+
stepKey,
|
|
1654
|
+
name: stepName,
|
|
1655
|
+
ts: Date.now(),
|
|
1656
|
+
durationMs: durationMs2,
|
|
1657
|
+
result: err(fallbackMappedError, { cause: fallbackThrown }),
|
|
1658
|
+
meta: { origin: "throw", thrown: fallbackThrown }
|
|
1659
|
+
});
|
|
1660
|
+
}
|
|
1661
|
+
onError?.(fallbackMappedError, stepName, context);
|
|
1662
|
+
throw earlyExit(fallbackMappedError, { origin: "throw", thrown: fallbackThrown });
|
|
1663
|
+
}
|
|
1664
|
+
if (fallbackResultFromThrow.ok) {
|
|
1665
|
+
const durationMs2 = performance.now() - startTime;
|
|
1666
|
+
emitEvent({
|
|
1667
|
+
type: "step_success",
|
|
1668
|
+
workflowId,
|
|
1669
|
+
stepId,
|
|
1670
|
+
stepKey,
|
|
1671
|
+
name: stepName,
|
|
1672
|
+
ts: Date.now(),
|
|
1673
|
+
durationMs: durationMs2
|
|
1674
|
+
});
|
|
1675
|
+
if (stepKey) {
|
|
1676
|
+
emitEvent({
|
|
1677
|
+
type: "step_complete",
|
|
1678
|
+
workflowId,
|
|
1679
|
+
stepKey,
|
|
1680
|
+
name: stepName,
|
|
1681
|
+
ts: Date.now(),
|
|
1682
|
+
durationMs: durationMs2,
|
|
1683
|
+
result: fallbackResultFromThrow,
|
|
1684
|
+
meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(mappedError) }
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
return fallbackResultFromThrow.value;
|
|
1688
|
+
} else {
|
|
1689
|
+
const durationMs2 = performance.now() - startTime;
|
|
1690
|
+
const wrappedError2 = wrapForStep(fallbackResultFromThrow.error, {
|
|
1691
|
+
origin: "result",
|
|
1692
|
+
resultCause: fallbackResultFromThrow.cause
|
|
1693
|
+
});
|
|
1694
|
+
emitEvent({
|
|
1695
|
+
type: "step_error",
|
|
1696
|
+
workflowId,
|
|
1697
|
+
stepId,
|
|
1698
|
+
stepKey,
|
|
1699
|
+
name: stepName,
|
|
1700
|
+
ts: Date.now(),
|
|
1701
|
+
durationMs: durationMs2,
|
|
1702
|
+
error: wrappedError2
|
|
1703
|
+
});
|
|
1704
|
+
if (stepKey) {
|
|
1705
|
+
emitEvent({
|
|
1706
|
+
type: "step_complete",
|
|
1707
|
+
workflowId,
|
|
1708
|
+
stepKey,
|
|
1709
|
+
name: stepName,
|
|
1710
|
+
ts: Date.now(),
|
|
1711
|
+
durationMs: durationMs2,
|
|
1712
|
+
result: fallbackResultFromThrow,
|
|
1713
|
+
meta: { origin: "result", resultCause: fallbackResultFromThrow.cause }
|
|
1714
|
+
});
|
|
1715
|
+
}
|
|
1716
|
+
onError?.(wrappedError2, stepName, context);
|
|
1717
|
+
throw earlyExit(wrappedError2, {
|
|
1718
|
+
origin: "result",
|
|
1719
|
+
resultCause: fallbackResultFromThrow.cause
|
|
1720
|
+
});
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
if (primaryResult.ok) {
|
|
1724
|
+
const durationMs2 = performance.now() - startTime;
|
|
1725
|
+
emitEvent({
|
|
1726
|
+
type: "step_success",
|
|
1727
|
+
workflowId,
|
|
1728
|
+
stepId,
|
|
1729
|
+
stepKey,
|
|
1730
|
+
name: stepName,
|
|
1731
|
+
ts: Date.now(),
|
|
1732
|
+
durationMs: durationMs2
|
|
1733
|
+
});
|
|
1734
|
+
if (stepKey) {
|
|
1735
|
+
emitEvent({
|
|
1736
|
+
type: "step_complete",
|
|
1737
|
+
workflowId,
|
|
1738
|
+
stepKey,
|
|
1739
|
+
name: stepName,
|
|
1740
|
+
ts: Date.now(),
|
|
1741
|
+
durationMs: durationMs2,
|
|
1742
|
+
result: primaryResult
|
|
1743
|
+
});
|
|
1744
|
+
}
|
|
1745
|
+
return primaryResult.value;
|
|
1746
|
+
}
|
|
1747
|
+
const primaryError = primaryResult.error;
|
|
1748
|
+
if (options2.on !== void 0 && options2.on !== primaryError) {
|
|
1749
|
+
const durationMs2 = performance.now() - startTime;
|
|
1750
|
+
const wrappedError2 = wrapForStep(primaryError, {
|
|
1751
|
+
origin: "result",
|
|
1752
|
+
resultCause: primaryResult.cause
|
|
1753
|
+
});
|
|
1754
|
+
emitEvent({
|
|
1755
|
+
type: "step_error",
|
|
1756
|
+
workflowId,
|
|
1757
|
+
stepId,
|
|
1758
|
+
stepKey,
|
|
1759
|
+
name: stepName,
|
|
1760
|
+
ts: Date.now(),
|
|
1761
|
+
durationMs: durationMs2,
|
|
1762
|
+
error: wrappedError2
|
|
1763
|
+
});
|
|
1764
|
+
if (stepKey) {
|
|
1765
|
+
emitEvent({
|
|
1766
|
+
type: "step_complete",
|
|
1767
|
+
workflowId,
|
|
1768
|
+
stepKey,
|
|
1769
|
+
name: stepName,
|
|
1770
|
+
ts: Date.now(),
|
|
1771
|
+
durationMs: durationMs2,
|
|
1772
|
+
result: primaryResult,
|
|
1773
|
+
meta: { origin: "result", resultCause: primaryResult.cause }
|
|
1774
|
+
});
|
|
1775
|
+
}
|
|
1776
|
+
onError?.(wrappedError2, stepName, context);
|
|
1777
|
+
throw earlyExit(wrappedError2, {
|
|
1778
|
+
origin: "result",
|
|
1779
|
+
resultCause: primaryResult.cause
|
|
1780
|
+
});
|
|
1781
|
+
}
|
|
1782
|
+
let fallbackResult;
|
|
1783
|
+
try {
|
|
1784
|
+
fallbackResult = await options2.fallback();
|
|
1785
|
+
} catch (thrown) {
|
|
1786
|
+
if (isEarlyExitE(thrown)) {
|
|
1787
|
+
emitEvent({
|
|
1788
|
+
type: "step_aborted",
|
|
1789
|
+
workflowId,
|
|
1790
|
+
stepId,
|
|
1791
|
+
stepKey,
|
|
1792
|
+
name: stepName,
|
|
1793
|
+
ts: Date.now(),
|
|
1794
|
+
durationMs: performance.now() - startTime
|
|
1795
|
+
});
|
|
1796
|
+
throw thrown;
|
|
1797
|
+
}
|
|
1798
|
+
let mappedError;
|
|
1799
|
+
try {
|
|
1800
|
+
mappedError = effectiveCatchUnexpected(thrown);
|
|
1801
|
+
} catch (mapperError) {
|
|
1802
|
+
throw createMapperException(mapperError);
|
|
1803
|
+
}
|
|
1804
|
+
const durationMs2 = performance.now() - startTime;
|
|
1805
|
+
emitEvent({
|
|
1806
|
+
type: "step_error",
|
|
1807
|
+
workflowId,
|
|
1808
|
+
stepId,
|
|
1809
|
+
stepKey,
|
|
1810
|
+
name: stepName,
|
|
1811
|
+
ts: Date.now(),
|
|
1812
|
+
durationMs: durationMs2,
|
|
1813
|
+
error: mappedError
|
|
1814
|
+
});
|
|
1815
|
+
if (stepKey) {
|
|
1816
|
+
emitEvent({
|
|
1817
|
+
type: "step_complete",
|
|
1818
|
+
workflowId,
|
|
1819
|
+
stepKey,
|
|
1820
|
+
name: stepName,
|
|
1821
|
+
ts: Date.now(),
|
|
1822
|
+
durationMs: durationMs2,
|
|
1823
|
+
result: err(mappedError, { cause: thrown }),
|
|
1824
|
+
meta: { origin: "throw", thrown }
|
|
1825
|
+
});
|
|
1826
|
+
}
|
|
1827
|
+
onError?.(mappedError, stepName, context);
|
|
1828
|
+
throw earlyExit(mappedError, { origin: "throw", thrown });
|
|
1829
|
+
}
|
|
1830
|
+
if (fallbackResult.ok) {
|
|
1831
|
+
const durationMs2 = performance.now() - startTime;
|
|
1832
|
+
emitEvent({
|
|
1833
|
+
type: "step_success",
|
|
1834
|
+
workflowId,
|
|
1835
|
+
stepId,
|
|
1836
|
+
stepKey,
|
|
1837
|
+
name: stepName,
|
|
1838
|
+
ts: Date.now(),
|
|
1839
|
+
durationMs: durationMs2
|
|
1840
|
+
});
|
|
1841
|
+
if (stepKey) {
|
|
1842
|
+
emitEvent({
|
|
1843
|
+
type: "step_complete",
|
|
1844
|
+
workflowId,
|
|
1845
|
+
stepKey,
|
|
1846
|
+
name: stepName,
|
|
1847
|
+
ts: Date.now(),
|
|
1848
|
+
durationMs: durationMs2,
|
|
1849
|
+
result: fallbackResult,
|
|
1850
|
+
meta: { origin: "fallback", fallbackUsed: true, fallbackReason: String(primaryError) }
|
|
1851
|
+
});
|
|
1852
|
+
}
|
|
1853
|
+
return fallbackResult.value;
|
|
1854
|
+
}
|
|
1855
|
+
const durationMs = performance.now() - startTime;
|
|
1856
|
+
const wrappedError = wrapForStep(fallbackResult.error, {
|
|
1857
|
+
origin: "result",
|
|
1858
|
+
resultCause: fallbackResult.cause
|
|
1859
|
+
});
|
|
1860
|
+
emitEvent({
|
|
1861
|
+
type: "step_error",
|
|
1862
|
+
workflowId,
|
|
1863
|
+
stepId,
|
|
1864
|
+
stepKey,
|
|
1865
|
+
name: stepName,
|
|
1866
|
+
ts: Date.now(),
|
|
1867
|
+
durationMs,
|
|
1868
|
+
error: wrappedError
|
|
1869
|
+
});
|
|
1870
|
+
if (stepKey) {
|
|
1871
|
+
emitEvent({
|
|
1872
|
+
type: "step_complete",
|
|
1873
|
+
workflowId,
|
|
1874
|
+
stepKey,
|
|
1875
|
+
name: stepName,
|
|
1876
|
+
ts: Date.now(),
|
|
1877
|
+
durationMs,
|
|
1878
|
+
result: fallbackResult,
|
|
1879
|
+
meta: { origin: "result", resultCause: fallbackResult.cause }
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
onError?.(wrappedError, stepName, context);
|
|
1883
|
+
throw earlyExit(wrappedError, {
|
|
1884
|
+
origin: "result",
|
|
1885
|
+
resultCause: fallbackResult.cause
|
|
1886
|
+
});
|
|
1887
|
+
})();
|
|
1888
|
+
};
|
|
1889
|
+
stepFn.withResource = (id, options2) => {
|
|
1890
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
1891
|
+
throw new Error(
|
|
1892
|
+
'[awaitly] step.withResource() requires an explicit string ID as the first argument. Example: step.withResource("useDb", { acquire: () => connect(), use: (db) => query(db), release: (db) => db.close() })'
|
|
1893
|
+
);
|
|
1894
|
+
}
|
|
1895
|
+
assertDeclared(id, "step");
|
|
1896
|
+
const stepKey = id;
|
|
1897
|
+
const stepName = id;
|
|
1898
|
+
const stepId = generateStepId(stepKey);
|
|
1899
|
+
const hasEventListeners = onEvent;
|
|
1900
|
+
return (async () => {
|
|
1901
|
+
const startTime = hasEventListeners ? performance.now() : 0;
|
|
1902
|
+
if (onEvent) {
|
|
1903
|
+
emitEvent({
|
|
1904
|
+
type: "step_start",
|
|
1905
|
+
workflowId,
|
|
1906
|
+
stepId,
|
|
1907
|
+
stepKey,
|
|
1908
|
+
name: stepName,
|
|
1909
|
+
ts: Date.now()
|
|
1910
|
+
});
|
|
1911
|
+
}
|
|
1912
|
+
let acquireResult;
|
|
1913
|
+
try {
|
|
1914
|
+
acquireResult = await options2.acquire();
|
|
1915
|
+
} catch (thrown) {
|
|
1916
|
+
if (isEarlyExitE(thrown)) {
|
|
1917
|
+
emitEvent({
|
|
1918
|
+
type: "step_aborted",
|
|
1919
|
+
workflowId,
|
|
1920
|
+
stepId,
|
|
1921
|
+
stepKey,
|
|
1922
|
+
name: stepName,
|
|
1923
|
+
ts: Date.now(),
|
|
1924
|
+
durationMs: performance.now() - startTime
|
|
1925
|
+
});
|
|
1926
|
+
throw thrown;
|
|
1927
|
+
}
|
|
1928
|
+
let mappedError;
|
|
1929
|
+
try {
|
|
1930
|
+
mappedError = effectiveCatchUnexpected(thrown);
|
|
1931
|
+
} catch (mapperError) {
|
|
1932
|
+
throw createMapperException(mapperError);
|
|
1933
|
+
}
|
|
1934
|
+
const durationMs2 = performance.now() - startTime;
|
|
1935
|
+
emitEvent({
|
|
1936
|
+
type: "step_error",
|
|
1937
|
+
workflowId,
|
|
1938
|
+
stepId,
|
|
1939
|
+
stepKey,
|
|
1940
|
+
name: stepName,
|
|
1941
|
+
ts: Date.now(),
|
|
1942
|
+
durationMs: durationMs2,
|
|
1943
|
+
error: mappedError
|
|
1944
|
+
});
|
|
1945
|
+
if (stepKey) {
|
|
1946
|
+
emitEvent({
|
|
1947
|
+
type: "step_complete",
|
|
1948
|
+
workflowId,
|
|
1949
|
+
stepKey,
|
|
1950
|
+
name: stepName,
|
|
1951
|
+
ts: Date.now(),
|
|
1952
|
+
durationMs: durationMs2,
|
|
1953
|
+
result: err(mappedError, { cause: thrown }),
|
|
1954
|
+
meta: { origin: "throw", thrown }
|
|
1955
|
+
});
|
|
1956
|
+
}
|
|
1957
|
+
onError?.(mappedError, stepName, context);
|
|
1958
|
+
throw earlyExit(mappedError, { origin: "throw", thrown });
|
|
1959
|
+
}
|
|
1960
|
+
if (!acquireResult.ok) {
|
|
1961
|
+
const durationMs2 = performance.now() - startTime;
|
|
1962
|
+
const wrappedError2 = wrapForStep(acquireResult.error, {
|
|
1963
|
+
origin: "result",
|
|
1964
|
+
resultCause: acquireResult.cause
|
|
1965
|
+
});
|
|
1966
|
+
emitEvent({
|
|
1967
|
+
type: "step_error",
|
|
1968
|
+
workflowId,
|
|
1969
|
+
stepId,
|
|
1970
|
+
stepKey,
|
|
1971
|
+
name: stepName,
|
|
1972
|
+
ts: Date.now(),
|
|
1973
|
+
durationMs: durationMs2,
|
|
1974
|
+
error: wrappedError2
|
|
1975
|
+
});
|
|
1976
|
+
if (stepKey) {
|
|
1977
|
+
emitEvent({
|
|
1978
|
+
type: "step_complete",
|
|
1979
|
+
workflowId,
|
|
1980
|
+
stepKey,
|
|
1981
|
+
name: stepName,
|
|
1982
|
+
ts: Date.now(),
|
|
1983
|
+
durationMs: durationMs2,
|
|
1984
|
+
result: acquireResult,
|
|
1985
|
+
meta: { origin: "result", resultCause: acquireResult.cause }
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
onError?.(wrappedError2, stepName, context);
|
|
1989
|
+
throw earlyExit(wrappedError2, {
|
|
1990
|
+
origin: "result",
|
|
1991
|
+
resultCause: acquireResult.cause
|
|
1992
|
+
});
|
|
1993
|
+
}
|
|
1994
|
+
const resource = acquireResult.value;
|
|
1995
|
+
let useResult;
|
|
1996
|
+
let useThrown;
|
|
1997
|
+
let useThrewNonResult = false;
|
|
1998
|
+
try {
|
|
1999
|
+
useResult = await options2.use(resource);
|
|
2000
|
+
} catch (thrown) {
|
|
2001
|
+
if (isEarlyExitE(thrown)) {
|
|
2002
|
+
try {
|
|
2003
|
+
await options2.release(resource);
|
|
2004
|
+
} catch (releaseErr) {
|
|
2005
|
+
console.warn(
|
|
2006
|
+
`[awaitly] step.withResource("${id}"): release threw after earlyExit:`,
|
|
2007
|
+
releaseErr
|
|
2008
|
+
);
|
|
2009
|
+
}
|
|
2010
|
+
throw thrown;
|
|
2011
|
+
}
|
|
2012
|
+
useThrown = thrown;
|
|
2013
|
+
useThrewNonResult = true;
|
|
2014
|
+
}
|
|
2015
|
+
try {
|
|
2016
|
+
await options2.release(resource);
|
|
2017
|
+
} catch (releaseErr) {
|
|
2018
|
+
console.warn(
|
|
2019
|
+
`[awaitly] step.withResource("${id}"): release threw:`,
|
|
2020
|
+
releaseErr
|
|
2021
|
+
);
|
|
2022
|
+
}
|
|
2023
|
+
if (useThrewNonResult) {
|
|
2024
|
+
let mappedError;
|
|
2025
|
+
try {
|
|
2026
|
+
mappedError = effectiveCatchUnexpected(useThrown);
|
|
2027
|
+
} catch (mapperError) {
|
|
2028
|
+
throw createMapperException(mapperError);
|
|
2029
|
+
}
|
|
2030
|
+
const durationMs2 = performance.now() - startTime;
|
|
2031
|
+
emitEvent({
|
|
2032
|
+
type: "step_error",
|
|
2033
|
+
workflowId,
|
|
2034
|
+
stepId,
|
|
2035
|
+
stepKey,
|
|
2036
|
+
name: stepName,
|
|
2037
|
+
ts: Date.now(),
|
|
2038
|
+
durationMs: durationMs2,
|
|
2039
|
+
error: mappedError
|
|
2040
|
+
});
|
|
2041
|
+
if (stepKey) {
|
|
2042
|
+
emitEvent({
|
|
2043
|
+
type: "step_complete",
|
|
2044
|
+
workflowId,
|
|
2045
|
+
stepKey,
|
|
2046
|
+
name: stepName,
|
|
2047
|
+
ts: Date.now(),
|
|
2048
|
+
durationMs: durationMs2,
|
|
2049
|
+
result: err(mappedError, { cause: useThrown }),
|
|
2050
|
+
meta: { origin: "throw", thrown: useThrown }
|
|
2051
|
+
});
|
|
2052
|
+
}
|
|
2053
|
+
onError?.(mappedError, stepName, context);
|
|
2054
|
+
throw earlyExit(mappedError, { origin: "throw", thrown: useThrown });
|
|
2055
|
+
}
|
|
2056
|
+
const result = useResult;
|
|
2057
|
+
if (result.ok) {
|
|
2058
|
+
const durationMs2 = performance.now() - startTime;
|
|
2059
|
+
emitEvent({
|
|
2060
|
+
type: "step_success",
|
|
2061
|
+
workflowId,
|
|
2062
|
+
stepId,
|
|
2063
|
+
stepKey,
|
|
2064
|
+
name: stepName,
|
|
2065
|
+
ts: Date.now(),
|
|
2066
|
+
durationMs: durationMs2
|
|
2067
|
+
});
|
|
2068
|
+
if (stepKey) {
|
|
2069
|
+
emitEvent({
|
|
2070
|
+
type: "step_complete",
|
|
2071
|
+
workflowId,
|
|
2072
|
+
stepKey,
|
|
2073
|
+
name: stepName,
|
|
2074
|
+
ts: Date.now(),
|
|
2075
|
+
durationMs: durationMs2,
|
|
2076
|
+
result
|
|
2077
|
+
});
|
|
2078
|
+
}
|
|
2079
|
+
return result.value;
|
|
2080
|
+
}
|
|
2081
|
+
const durationMs = performance.now() - startTime;
|
|
2082
|
+
const wrappedError = wrapForStep(result.error, {
|
|
2083
|
+
origin: "result",
|
|
2084
|
+
resultCause: result.cause
|
|
2085
|
+
});
|
|
2086
|
+
emitEvent({
|
|
2087
|
+
type: "step_error",
|
|
2088
|
+
workflowId,
|
|
2089
|
+
stepId,
|
|
2090
|
+
stepKey,
|
|
2091
|
+
name: stepName,
|
|
2092
|
+
ts: Date.now(),
|
|
2093
|
+
durationMs,
|
|
2094
|
+
error: wrappedError
|
|
2095
|
+
});
|
|
2096
|
+
if (stepKey) {
|
|
2097
|
+
emitEvent({
|
|
2098
|
+
type: "step_complete",
|
|
2099
|
+
workflowId,
|
|
2100
|
+
stepKey,
|
|
2101
|
+
name: stepName,
|
|
2102
|
+
ts: Date.now(),
|
|
2103
|
+
durationMs,
|
|
2104
|
+
result,
|
|
2105
|
+
meta: { origin: "result", resultCause: result.cause }
|
|
2106
|
+
});
|
|
2107
|
+
}
|
|
2108
|
+
onError?.(wrappedError, stepName, context);
|
|
2109
|
+
throw earlyExit(wrappedError, {
|
|
2110
|
+
origin: "result",
|
|
2111
|
+
resultCause: result.cause
|
|
2112
|
+
});
|
|
2113
|
+
})();
|
|
2114
|
+
};
|
|
2115
|
+
const step = stepFn;
|
|
2116
|
+
const value = await fn({ step });
|
|
2117
|
+
if (process.env.NODE_ENV !== "production" && value !== null && typeof value === "object" && "ok" in value && typeof value.ok === "boolean") {
|
|
2118
|
+
const maybeResult = value;
|
|
2119
|
+
if (maybeResult.ok === true && "value" in maybeResult || maybeResult.ok === false && "error" in maybeResult) {
|
|
2120
|
+
console.warn(
|
|
2121
|
+
`awaitly: Workflow executor returned a Result-like object. Return raw values, not ok() or err().
|
|
2
2122
|
|
|
3
2123
|
Incorrect: return ok({ data });
|
|
4
2124
|
Correct: return { data };
|
|
5
2125
|
|
|
6
|
-
See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
const restored = parseState(json); // Load this`),typeof d.steps=="object"&&d.steps!==null&&(d.steps=new Map(Object.entries(d.steps))));for(let[f,X]of d.steps){let{result:x,meta:g}=X;if(x.ok)i.set(f,x);else{let p=g??{origin:"result",resultCause:x.cause};i.set(f,be(x.error,p,x.cause))}}}let h=O?.snapshot??s?.snapshot,P=s?.serialization;if(h&&!pe){i||(i=new Map);let d=h,f=P?.decode;for(let[X,x]of Object.entries(d.steps))if(Object.prototype.hasOwnProperty.call(d.steps,X))try{if(x.ok){let g=f?f(x.value):x.value;i.set(X,Z(g))}else{let g=f?f(x.error):x.error,p=Ye(x.cause),R=x.meta?.origin==="throw"?{origin:"throw",thrown:p}:{origin:"result",resultCause:p};i.set(X,be(g,R,p))}}catch(g){throw new Be(`Failed to decode step "${X}": ${g instanceof Error?g.message:String(g)}`,X,g instanceof Error?g:void 0)}}let M=!1,N,H,ae=()=>{M=!0,N=typeof u?.reason=="string"?u.reason:u?.reason instanceof Error?u.reason.message:void 0};u&&!u.aborted&&u.addEventListener("abort",ae,{once:!0});let B=()=>{if(M||u?.aborted)throw{type:"WORKFLOW_CANCELLED",reason:N??(typeof u?.reason=="string"?u.reason:u?.reason instanceof Error?u.reason.message:void 0),lastStepKey:H}},G=async(d,f,X)=>{if(!ee)return;let x=performance.now();try{await ee(d,f,r,ne);let g=performance.now()-x;F({type:"hook_after_step",workflowId:r,stepKey:d,ts:Date.now(),durationMs:g})}catch(g){let p=performance.now()-x;throw F({type:"hook_after_step_error",workflowId:r,stepKey:d,ts:Date.now(),durationMs:p,error:g}),g}},V=d=>{let f=async(g,p,R)=>{if(typeof g!="string")throw new Error('[awaitly] step() requires a string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))');let A=g,b=R??{},D=A,k=Object.prototype.hasOwnProperty.call(b,"key")?b.key:A,{ttl:$,out:te}=b;B();let se=qe(b);if(k&&i&&i.has(k)){F({type:"step_cache_hit",workflowId:r,stepKey:k,name:D,ts:Date.now(),...se&&{metadata:se}});let U=i.get(k);if(U.ok)return H=k,te&&(y[te]=U.value),U.value;let J=Ke(U.cause);throw De(U.error,J)}k&&i&&F({type:"step_cache_miss",workflowId:r,stepKey:k,name:D,ts:Date.now(),...se&&{metadata:se}});try{let U=await d(A,p,b);return te&&(y[te]=U),b.compensate&&L.push({stepName:D,value:U,compensate:b.compensate}),k&&(H=k,i&&i.set(k,Z(U),$?{ttl:$}:void 0),await G(k,Z(U))),U}catch(U){if(k&&ve(U)){let J=U,Ee=J.meta.origin==="result"?J.meta.resultCause:J.meta.origin==="throw"?J.meta.thrown:void 0,re=be(J.error,J.meta,Ee);i&&i.set(k,re,$?{ttl:$}:void 0),await G(k,re,J.meta)}throw U}};f.try=async(g,p,R)=>{let{ttl:A}=R,b=R.key??g,D=g;if(i&&i.has(b)){F({type:"step_cache_hit",workflowId:r,stepKey:b,name:D,ts:Date.now()});let k=i.get(b);if(k.ok)return k.value;let $=Ke(k.cause);throw De(k.error,$)}i&&F({type:"step_cache_miss",workflowId:r,stepKey:b,name:D,ts:Date.now()});try{let k=await d.try(g,p,{...R,key:b});return R.compensate&&L.push({stepName:D,value:k,compensate:R.compensate}),i&&i.set(b,Z(k),A?{ttl:A}:void 0),await G(b,Z(k)),k}catch(k){if(ve(k)){let $=k,te=$.meta.origin==="result"?$.meta.resultCause:$.meta.origin==="throw"?$.meta.thrown:void 0,se=be($.error,$.meta,te);i&&i.set(b,se,A?{ttl:A}:void 0),await G(b,se,$.meta)}throw k}},f.fromResult=async(g,p,R)=>{let{ttl:A}=R,b=R.key??g,D=g;if(i&&i.has(b)){F({type:"step_cache_hit",workflowId:r,stepKey:b,name:D,ts:Date.now()});let k=i.get(b);if(k.ok)return k.value;let $=Ke(k.cause);throw De(k.error,$)}i&&F({type:"step_cache_miss",workflowId:r,stepKey:b,name:D,ts:Date.now()});try{let k=await d.fromResult(g,p,{...R,key:b});return i&&i.set(b,Z(k),A?{ttl:A}:void 0),await G(b,Z(k)),k}catch(k){if(ve(k)){let $=k,te=$.meta.origin==="result"?$.meta.resultCause:$.meta.origin==="throw"?$.meta.thrown:void 0,se=be($.error,$.meta,te);i&&i.set(b,se,A?{ttl:A}:void 0),await G(b,se,$.meta)}throw k}},f.race=d.race,f.withFallback=async(g,p,R)=>{let A=R.key??g,b=g;if(i&&i.has(A)){F({type:"step_cache_hit",workflowId:r,stepKey:A,name:b,ts:Date.now()});let D=i.get(A);if(D.ok)return D.value;let k=Ke(D.cause);throw De(D.error,k)}i&&F({type:"step_cache_miss",workflowId:r,stepKey:A,name:b,ts:Date.now()});try{let D=await d.withFallback(g,p,R);return i&&i.set(A,Z(D)),await G(A,Z(D)),D}catch(D){if(ve(D)){let k=D,$=k.meta.origin==="result"?k.meta.resultCause:k.meta.origin==="throw"?k.meta.thrown:void 0,te=be(k.error,k.meta,$);i&&i.set(A,te),await G(A,te,k.meta)}throw D}},f.withResource=async(g,p)=>{let R=g;try{let A=await d.withResource(g,p);return await G(R,Z(A)),A}catch(A){if(ve(A)){let b=A,D=b.meta.origin==="result"?b.meta.resultCause:b.meta.origin==="throw"?b.meta.thrown:void 0,k=be(b.error,b.meta,D);await G(R,k,b.meta)}throw A}},f.retry=(g,p,R)=>{let A={key:R.key,retry:{attempts:R.attempts,backoff:R.backoff,initialDelay:R.initialDelay,maxDelay:R.maxDelay,jitter:R.jitter,shouldRetry:R.shouldRetry,onRetry:R.onRetry},timeout:R.timeout,ttl:R.ttl};return f(g,p,A)},f.withTimeout=(g,p,R)=>{let A={key:R.key,timeout:R,ttl:R.ttl};return f(g,p,A)},f.sleep=(g,p,R)=>{if(typeof g!="string"||g.length===0)throw new Error('[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")');let A=typeof p=="string"?ht(p):p;if(!A)throw new Error(`step.sleep: invalid duration '${p}'`);let b=St(A),D=R?.signal;return f(g,async()=>{if(u?.aborted||D?.aborted){let $=new Error("Sleep aborted");throw $.name="AbortError",$}return new Promise(($,te)=>{let se={timeoutId:void 0},U=()=>{se.timeoutId&&clearTimeout(se.timeoutId);let J=new Error("Sleep aborted");J.name="AbortError",te(J)};u?.addEventListener("abort",U,{once:!0}),D?.addEventListener("abort",U,{once:!0}),se.timeoutId=setTimeout(()=>{u?.removeEventListener("abort",U),D?.removeEventListener("abort",U),$(Z(void 0))},b)})},{key:R?.key,ttl:R?.ttl,description:R?.description})};let X=new Map,x=new Map;return f.getWritable=g=>{let p=g?.namespace??"default",R=g?.highWaterMark??16;if(!T)throw new Error("streamStore is required to use getWritable(). Pass a streamStore to createWorkflow options.");let A=`${r}:${p}`,b=X.get(A);if(b&&!b.closed&&!b.aborted)return b.writer;let D=xt({highWaterMark:R,onStateChange:J=>{F({type:"stream_backpressure",workflowId:r,namespace:p,bufferedCount:D.bufferedCount,state:J,ts:Date.now()})}}),k=0,$=!0,te=!1,se=!1;F({type:"stream_created",workflowId:r,namespace:p,ts:Date.now()});let U={async write(J){if(se)return j(Ve("closed","Stream is closed"));if(te)return j(Ve("aborted","Stream was aborted"));D.state==="paused"&&await D.waitForDrain();let Ee={value:J,position:k,ts:Date.now()},re=await T.append(r,p,Ee);return re.ok?(F({type:"stream_write",workflowId:r,namespace:p,position:k,ts:Date.now()}),k++,D.increment(),Z(void 0)):(F({type:"stream_error",workflowId:r,namespace:p,error:re.error,position:k,ts:Date.now()}),j(Ve("store_error",re.error.message,re.error)))},async close(){if(se)return j(Xe("already_closed","Stream is already closed"));let J=await T.closeStream(r,p);return J.ok?(se=!0,$=!1,F({type:"stream_close",workflowId:r,namespace:p,finalPosition:k,ts:Date.now()}),X.delete(A),Z(void 0)):j(Xe("store_error",J.error.message,J.error))},abort(J){te=!0,$=!1,se=!0,F({type:"stream_error",workflowId:r,namespace:p,error:J,position:k,ts:Date.now()}),X.delete(A)},get writable(){return $},get position(){return k},get namespace(){return p}};return X.set(A,{writer:U,backpressure:D,aborted:te,closed:se}),U},f.getReadable=g=>{let p=g?.namespace??"default",R=g?.startIndex??0,A=g?.pollInterval??10,b=g?.pollTimeout??3e4;if(!T)throw new Error("streamStore is required to use getReadable(). Pass a streamStore to createWorkflow options.");let D=`${r}:${p}:${R}`,k=x.get(D);if(k&&!k.closed)return k.reader;let $=()=>{let Se=`${r}:${p}`,le=X.get(Se);le&&le.backpressure.decrement()},te=R,se=!0,U=!1,J=[],Ee=0,re={async read(){if(U)return j(Ge("closed","Reader is closed"));if(Ee<J.length){let ge=J[Ee++];return te=ge.position+1,$(),F({type:"stream_read",workflowId:r,namespace:p,position:ge.position,ts:Date.now()}),Z(ge.value)}let Se=`${r}:${p}`,le=Date.now(),ke=X.has(Se),ie=await T.getMetadata(r,p),fe=ie.ok&&ie.value!==void 0;for(;Date.now()-le<b;){let ge=await T.read(r,p,te,100);if(!ge.ok)return j(Ge("store_error",ge.error.message,ge.error));let Me=ge.value;if(Me.length>0){J=Me,Ee=1;let Ue=Me[0];return te=Ue.position+1,$(),F({type:"stream_read",workflowId:r,namespace:p,position:Ue.position,ts:Date.now()}),Z(Ue.value)}let Ie=X.has(Se),Ce=await T.getMetadata(r,p),tt=Ce.ok&&Ce.value!==void 0;if(Ie&&(ke=!0),tt&&(fe=!0),Ce.ok&&Ce.value?.closed)return se=!1,j(Le(te));if(ke&&!Ie&&!tt)return se=!1,j(Le(te));fe&&!Ie&&Ce.ok&&Ce.value?.closed,await new Promise(Ue=>setTimeout(Ue,A))}return se=!1,j(Le(te))},close(){U=!0,se=!1,J=[],x.delete(D)},get readable(){return se},get position(){return te},get namespace(){return p}};return x.set(D,{reader:re,position:te,closed:U}),re},f.streamForEach=async(g,p,R)=>{let A=R?.checkpointInterval??1,b=R?.concurrency??1,D=[],k=0,$=-1,te=U=>typeof U=="object"&&U!==null&&"read"in U&&typeof U.read=="function",se=async(U,J,Ee,re)=>{let le=A>0&&J%A===0?`stream-foreach:${re}:pos-${Ee}`:void 0,ke=le??`stream-item-${Ee}`,ie=await f(ke,()=>p(U,J),{key:le});return{index:J,position:Ee,result:ie}};if(te(g))if(b<=1){let U=g.position,J=await g.read();for(;J.ok;){let Ee=J.value,{result:re}=await se(Ee,k,U,g.namespace);D.push(re),$=U,k++,U=g.position,J=await g.read()}}else{let U=new Map,J=0,Ee=0,re=new Array(b).fill(null),Se=async()=>{for(let ge=0;ge<re.length;ge++)if(re[ge]===null)return ge;let ie=re.filter(ge=>ge!==null),fe=await Promise.race(ie);return U.set(fe.index,{position:fe.position,result:fe.result}),re[fe.slotIndex]=null,fe.slotIndex},le=g.position,ke=await g.read();for(;ke.ok;){let ie=await Se(),fe=J,ge=le,Me=ke.value,Ie=ie;re[ie]=se(Me,fe,ge,g.namespace).then(Ce=>({slotIndex:Ie,...Ce})),Ee++,J++,le=g.position,ke=await g.read()}for(let ie=0;ie<re.length;ie++)if(re[ie]!==null){let fe=await re[ie];U.set(fe.index,{position:fe.position,result:fe.result})}for(let ie=0;ie<Ee;ie++){let fe=U.get(ie);fe&&(D.push(fe.result),$=fe.position,k++)}}else if(b<=1){let U=0;for await(let J of g){let{result:Ee}=await se(J,U,U,"async-iterable");D.push(Ee),$=U,k++,U++}}else{let U=new Map,J=0,Ee=0,re=new Array(b).fill(null),Se=async()=>{for(let ie=0;ie<re.length;ie++)if(re[ie]===null)return ie;let le=re.filter(ie=>ie!==null),ke=await Promise.race(le);return U.set(ke.index,ke.result),re[ke.slotIndex]=null,ke.slotIndex};for await(let le of g){let ke=await Se(),ie=J,fe=ke;re[ke]=se(le,ie,ie,"async-iterable").then(ge=>({slotIndex:fe,...ge})),Ee++,J++}for(let le=0;le<re.length;le++)if(re[le]!==null){let ke=await re[le];U.set(ke.index,ke.result)}for(let le=0;le<Ee;le++)U.has(le)&&(D.push(U.get(le)),$=le,k++)}return{results:D,processedCount:k,lastPosition:$}},f.if=d.if,f.label=d.label,f.branch=d.branch,f.arm=d.arm,f.forEach=d.forEach,f.item=d.item,f.dep=d.dep,f.workflow=(g,p,R)=>f(g,p,R),f.all=(g,p,R)=>{let A=R!==void 0&&Object.prototype.hasOwnProperty.call(R,"key")?R:{...R,key:void 0};return f(g,async()=>Z(await d.all(g,p)),A)},f.map=(g,p,R,A)=>{let b=A!==void 0&&Object.prototype.hasOwnProperty.call(A,"key")?A:{...A,key:void 0};return f(g,async()=>Z(await d.map(g,p,R,A)),b)},f},Y=({step:d})=>{let f=V(d);return I({step:f,steps:Ne(q??{},f),deps:q,ctx:ce})},C;try{C=await je(Y,{onError:we,onEvent:Q,catchUnexpected:ye,workflowId:r,workflowName:e,context:ne,_workflowSignal:u})}finally{u&&u.removeEventListener("abort",ae)}if(!C.ok&&L.length>0){let d=[];for(let f=L.length-1;f>=0;f--){let X=L[f];try{await X.compensate(X.value)}catch(x){d.push({stepName:X.stepName,error:x})}}if(d.length>0){let f={type:"SAGA_COMPENSATION_ERROR",originalError:C.error,compensationErrors:d};C=j(f,{cause:C.cause})}}let Re=performance.now()-o;if(!C.ok){let d;if(ze(C.cause)&&(d=C.cause),!d&&M&&yt(C.error)){let f=C.cause;f!=null&&typeof f=="object"&&"name"in f&&f.name==="AbortError"&&(d={type:"WORKFLOW_CANCELLED",reason:N??(typeof u?.reason=="string"?u.reason:u?.reason instanceof Error?u.reason.message:void 0),lastStepKey:H})}if(d)return F({type:"workflow_cancelled",workflowId:r,ts:Date.now(),durationMs:Re,reason:d.reason,lastStepKey:d.lastStepKey}),d&&!ze(C.cause)?j(C.error,{cause:d}):C}if(C.ok&&M){let d=N??(typeof u?.reason=="string"?u.reason:u?.reason instanceof Error?u.reason.message:void 0);F({type:"workflow_cancelled",workflowId:r,ts:Date.now(),durationMs:Re,reason:d,lastStepKey:H});let f={type:"WORKFLOW_CANCELLED",reason:d,lastStepKey:H};return j(ye(f),{cause:f})}return C.ok?F({type:"workflow_success",workflowId:r,ts:Date.now(),durationMs:Re}):F({type:"workflow_error",workflowId:r,ts:Date.now(),durationMs:Re,error:C.error}),C}function w(K,I,O){let r,q,L;return typeof K=="string"?(r=K,q=I,L=O):(q=K,L=I),a(r,q,L)}async function v(K,I,O){let r,q,L;typeof K=="string"?(r=K,q=I,L=O):(q=K,L=I);let de=Rt(),ne=L?.onEvent,Q={...L,onEvent:(z,ee)=>{de.handleEvent(z);try{ne?.(z,ee)}catch{}}},we,_;try{we=await a(r,q,Q)}catch(z){let ee=s?.catchUnexpected??$e;we=j(ee(z),{cause:z})}finally{_=de.getResumeState()}return{result:we,resumeState:_}}let W={withDeps:K=>Ze(W,K),run:w,runWithState:v};return W}async function bt(e,t,n){let m=[],s={},a=[],w=O=>{if(m.push(O),O.type==="step_complete"&&O.stepKey){let r={output:O.result.ok?O.result.value:void 0,durationMs:O.durationMs,result:O.result};s[O.stepKey]=r,a.push(O.stepKey)}},v=Qe("test-workflow",e),W=performance.now(),K=await v.run(t,{onEvent:w,signal:n?.signal}),I=performance.now()-W;return{result:K,steps:s,events:m,durationMs:I,stepOrder:a}}function et(e){return typeof e=="object"&&e!==null&&"__earlyExit"in e&&e.__earlyExit===!0}function vt(e,t={}){let{recordInvocations:n=!0,clock:m=Date.now}=t,s=[],a=new Map,w=0,v=[];function W(_){s=[..._],w=0,a.clear()}function K(_,z){a.set(_,z)}function I(_){if(_&&a.has(_))return a.get(_);if(w<s.length)return s[w++]}function O(){let _=async(z,ee,pe)=>{let ye,y,oe;typeof z=="string"?(ye=z,y=ee,oe=pe??{}):(y=z,typeof ee=="string"?(ye=ee,oe={}):(oe=ee??{},ye=oe.key??"step"));let me=m(),ue={name:ye,key:oe.key,order:v.length,timestamp:me};n&&v.push(ue);let ce=I(ye);if(ce)switch(ue.durationMs=m()-me,ce.type){case"ok":return ue.result=Z(ce.value),ce.value;case"err":throw ue.result=j(ce.error),{__earlyExit:!0,error:ce.error};case"throw":throw ce.error}let F=typeof y=="function"?await y():await y;if(ue.durationMs=m()-me,ue.result=F,!F.ok)throw{__earlyExit:!0,error:F.error};return F.value};return _.try=async(z,ee,pe)=>{let ye,y,oe;typeof z=="string"?(ye=z,y=ee,oe=pe):(y=z,oe=ee,ye=oe.key??"step");let me=m(),ue={name:ye,key:"key"in oe?oe.key:void 0,order:v.length,timestamp:me};n&&v.push(ue);let ce=I(ye);if(ce)switch(ue.durationMs=m()-me,ce.type){case"ok":return ue.result=Z(ce.value),ce.value;case"err":throw ue.result=j(ce.error),{__earlyExit:!0,error:ce.error};case"throw":throw ce.error}try{let F=await y();return ue.durationMs=m()-me,ue.result=Z(F),F}catch(F){ue.durationMs=m()-me;let E="error"in oe?oe.error:oe.onError(F);throw ue.result=j(E),{__earlyExit:!0,error:E}}},_}async function r(_){let z=O();try{let ee=await _({step:z,deps:e});return Z(ee)}catch(ee){return et(ee)?j(ee.error):j(new he({cause:ee}))}}async function q(_,z){let ee=O();try{let pe=await z({step:ee,deps:e,input:_});return Z(pe)}catch(pe){return et(pe)?j(pe.error):j(new he({cause:pe}))}}function L(){return[...v]}function de(_){let z=v.map(pe=>pe.name??pe.key??"unnamed").filter(pe=>pe!=="unnamed"),ee=JSON.stringify(z)===JSON.stringify(_);return{passed:ee,message:ee?`Steps invoked in order: ${_.join(", ")}`:`Expected steps [${_.join(", ")}] but got [${z.join(", ")}]`,expected:_,actual:z}}function ne(_){let z=v.some(ee=>ee.name===_||ee.key===_);return{passed:z,message:z?`Step "${_}" was invoked`:`Step "${_}" was NOT invoked`,expected:_,actual:z}}function u(_){let z=v.some(ee=>ee.name===_||ee.key===_);return{passed:!z,message:z?`Step "${_}" was invoked but should not have been`:`Step "${_}" was correctly NOT invoked`,expected:"not called",actual:z?"called":"not called"}}function Q(_,z){let ee=_.ok===z.ok&&(_.ok?JSON.stringify(_.value)===JSON.stringify(z.value):JSON.stringify(_.error)===JSON.stringify(z.error));return{passed:ee,message:ee?"Result matches expected":"Result does not match expected",expected:z,actual:_}}function we(){s=[],a.clear(),w=0,v=[]}return{script:W,scriptStep:K,run:r,runWithInput:q,getInvocations:L,assertSteps:de,assertStepCalled:ne,assertStepNotCalled:u,assertResult:Q,reset:we}}function Qt(){let e,t=[],n=[],m=((...s)=>{if(n.push(s),t.length>0)return Promise.resolve(t.shift());if(e)return Promise.resolve(e);throw new Error("Mock function called without configured return value")});return m.returns=s=>(e=s,m),m.returnsOnce=s=>(t.push(s),m),m.getCalls=()=>[...n],m.getCallCount=()=>n.length,m.reset=()=>{e=void 0,t.length=0,n.length=0},m}function er(e,t,n){let m=e.reduce((s,a)=>s+(a.durationMs??0),0);return{invocations:e.map(s=>({...s,timestamp:0})),result:t,events:n?.map(s=>({...s,ts:0})),durationMs:m}}function tr(e,t){let n=[];e.invocations.length!==t.invocations.length&&n.push(`Invocation count: ${e.invocations.length} vs ${t.invocations.length}`);let m=Math.max(e.invocations.length,t.invocations.length);for(let s=0;s<m;s++){let a=e.invocations[s],w=t.invocations[s];if(!a){n.push(`Step ${s}: missing in first snapshot`);continue}if(!w){n.push(`Step ${s}: missing in second snapshot`);continue}a.name!==w.name&&n.push(`Step ${s} name: "${a.name}" vs "${w.name}"`),a.key!==w.key&&n.push(`Step ${s} key: "${a.key}" vs "${w.key}"`),a.result?.ok!==w.result?.ok&&n.push(`Step ${s} result: ${a.result?.ok?"ok":"err"} vs ${w.result?.ok?"ok":"err"}`)}return e.result.ok!==t.result.ok&&n.push(`Final result: ${e.result.ok?"ok":"err"} vs ${t.result.ok?"ok":"err"}`),{equal:n.length===0,differences:n}}function rr(e=0){let t=e;return{now:()=>t,advance:n=>{t+=n},set:n=>{t=n},reset:()=>{t=e}}}function nr(e){return{type:"ok",value:e}}function or(e){return{type:"err",error:e}}function sr(e){return{type:"throw",error:e}}function ar(e,t={}){let{clock:n=Date.now}=t,m=vt(e,t),s=[],a=[];async function w(q){s=[],a=[];let L={step:async(ne,u)=>{try{let Q=await m.run(async({step:we})=>we("saga-step",ne));if(!Q.ok)throw await de(),{__earlyExit:!0,error:Q.error};return u?.compensate&&a.push({value:Q.value,compensate:u.compensate}),Q.value}catch(Q){throw a.length>0&&await de(),Q}}};async function de(){let ne=[...a].reverse();a=[];for(let{name:u,value:Q,compensate:we}of ne)try{await we(Q),s.push({stepName:u,order:s.length,value:Q,timestamp:n()})}catch(_){console.error(`Compensation failed for step "${u}":`,_)}}try{let ne=await q({saga:L,deps:e});return Z(ne)}catch(ne){return et(ne)?j(ne.error):(await de(),j(new he({cause:ne})))}}function v(){return[...s]}function W(q){let L=s.map(ne=>ne.stepName),de=JSON.stringify(L)===JSON.stringify(q);return{passed:de,message:de?`Compensations ran in order: ${q.join(" \u2192 ")}`:`Expected compensations [${q.join(" \u2192 ")}] but got [${L.join(" \u2192 ")}]`,expected:q,actual:L}}function K(q){let L=s.some(de=>de.stepName===q);return{passed:L,message:L?`Step "${q}" was compensated`:`Step "${q}" was NOT compensated`,expected:q,actual:L}}function I(q){let L=s.some(de=>de.stepName===q);return{passed:!L,message:L?`Step "${q}" was compensated but should not have been`:`Step "${q}" was correctly NOT compensated`,expected:"not compensated",actual:L?"compensated":"not compensated"}}let O=m.reset;function r(){O(),s=[],a=[]}return{...m,reset:r,getCompensations:v,assertCompensationOrder:W,assertCompensated:K,assertNotCompensated:I,runSaga:w}}function ir(e,t,n={}){let{strict:m=!0}=n,s=t.map(W=>{let[K,I]=W.split(":");return{type:K,name:I}}),w=(m?e:e.filter(W=>s.some(K=>W.type===K.type))).map(W=>{let K="name"in W?W.name:void 0,I="stepKey"in W?W.stepKey:void 0,O=K??I;return O?`${W.type}:${O}`:W.type}),v=JSON.stringify(w)===JSON.stringify(t);return{passed:v,message:v?`Event sequence matches: ${t.join(" \u2192 ")}`:`Event sequence mismatch.
|
|
11
|
-
|
|
12
|
-
|
|
2126
|
+
See: https://jagreehal.github.io/awaitly/guides/troubleshooting/#returning-ok-from-workflow-executor-double-wrapping`
|
|
2127
|
+
);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
return ok2(value);
|
|
2131
|
+
} catch (error) {
|
|
2132
|
+
if (isMapperException(error)) {
|
|
2133
|
+
throw error.thrown;
|
|
2134
|
+
}
|
|
2135
|
+
if (isEarlyExitE(error)) {
|
|
2136
|
+
const originalCause = error.meta.origin === "throw" ? error.meta.thrown : error.meta.origin === "result" ? error.meta.resultCause : void 0;
|
|
2137
|
+
return err(error.error, { cause: originalCause });
|
|
2138
|
+
}
|
|
2139
|
+
const mapped = effectiveCatchUnexpected(error);
|
|
2140
|
+
onError?.(mapped, "unexpected", context);
|
|
2141
|
+
return err(mapped, { cause: error });
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
var runStrict = (fn, options) => {
|
|
2145
|
+
return runFn(fn, options);
|
|
2146
|
+
};
|
|
2147
|
+
var run = /* @__PURE__ */ Object.assign(runFn, { strict: runStrict });
|
|
2148
|
+
async function allAsync(results) {
|
|
2149
|
+
if (results.length === 0) {
|
|
2150
|
+
return ok2([]);
|
|
2151
|
+
}
|
|
2152
|
+
return new Promise((resolve) => {
|
|
2153
|
+
let settled = false;
|
|
2154
|
+
let pendingCount = results.length;
|
|
2155
|
+
const values = new Array(results.length);
|
|
2156
|
+
for (let i = 0; i < results.length; i++) {
|
|
2157
|
+
const index = i;
|
|
2158
|
+
Promise.resolve(results[index]).catch((reason) => err(
|
|
2159
|
+
{ type: "PROMISE_REJECTED", cause: reason },
|
|
2160
|
+
{ cause: { type: "PROMISE_REJECTION", reason } }
|
|
2161
|
+
)).then((result) => {
|
|
2162
|
+
if (settled) return;
|
|
2163
|
+
if (!result.ok) {
|
|
2164
|
+
settled = true;
|
|
2165
|
+
resolve(result);
|
|
2166
|
+
return;
|
|
2167
|
+
}
|
|
2168
|
+
values[index] = result.value;
|
|
2169
|
+
pendingCount--;
|
|
2170
|
+
if (pendingCount === 0) {
|
|
2171
|
+
resolve(ok2(values));
|
|
2172
|
+
}
|
|
2173
|
+
});
|
|
2174
|
+
}
|
|
2175
|
+
});
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
// src/workflow/guards.ts
|
|
2179
|
+
function isStepComplete(event) {
|
|
2180
|
+
return event.type === "step_complete";
|
|
2181
|
+
}
|
|
2182
|
+
function isWorkflowCancelled(error) {
|
|
2183
|
+
return typeof error === "object" && error !== null && error.type === "WORKFLOW_CANCELLED";
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
// src/persistence.ts
|
|
2187
|
+
var SnapshotDecodeError = class extends Error {
|
|
2188
|
+
constructor(message, stepId, originalError) {
|
|
2189
|
+
super(message);
|
|
2190
|
+
this.stepId = stepId;
|
|
2191
|
+
this.originalError = originalError;
|
|
2192
|
+
this.name = "SnapshotDecodeError";
|
|
2193
|
+
}
|
|
2194
|
+
stepId;
|
|
2195
|
+
originalError;
|
|
2196
|
+
};
|
|
2197
|
+
function deserializeCauseNew(serialized) {
|
|
2198
|
+
if (serialized.type === "error") {
|
|
2199
|
+
const error = new Error(serialized.message);
|
|
2200
|
+
error.name = serialized.name;
|
|
2201
|
+
if (serialized.stack) {
|
|
2202
|
+
error.stack = serialized.stack;
|
|
2203
|
+
}
|
|
2204
|
+
if (serialized.cause) {
|
|
2205
|
+
error.cause = deserializeCauseNew(serialized.cause);
|
|
2206
|
+
}
|
|
2207
|
+
return error;
|
|
2208
|
+
}
|
|
2209
|
+
return serialized.value !== void 0 ? serialized.value : serialized.stringRepresentation;
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
// src/workflow/cache-encoding.ts
|
|
2213
|
+
function isCachedErrorCause(cause) {
|
|
2214
|
+
return typeof cause === "object" && cause !== null && cause.__cachedMeta === true;
|
|
2215
|
+
}
|
|
2216
|
+
function encodeCachedError(error, meta, originalCause) {
|
|
2217
|
+
return err(error, {
|
|
2218
|
+
cause: { __cachedMeta: true, originalCause, meta }
|
|
2219
|
+
});
|
|
2220
|
+
}
|
|
2221
|
+
function decodeCachedMeta(cause) {
|
|
2222
|
+
if (isCachedErrorCause(cause)) {
|
|
2223
|
+
return cause.meta;
|
|
2224
|
+
}
|
|
2225
|
+
return { origin: "result", resultCause: cause };
|
|
2226
|
+
}
|
|
2227
|
+
|
|
2228
|
+
// src/workflow/resume-state.ts
|
|
2229
|
+
function createResumeStateCollector() {
|
|
2230
|
+
const steps = /* @__PURE__ */ new Map();
|
|
2231
|
+
return {
|
|
2232
|
+
handleEvent: (event) => {
|
|
2233
|
+
if (isStepComplete(event)) {
|
|
2234
|
+
steps.set(event.stepKey, { result: event.result, meta: event.meta });
|
|
2235
|
+
}
|
|
2236
|
+
},
|
|
2237
|
+
getResumeState: () => ({ steps: new Map(steps) }),
|
|
2238
|
+
clear: () => steps.clear()
|
|
2239
|
+
};
|
|
2240
|
+
}
|
|
2241
|
+
|
|
2242
|
+
// src/streaming/types.ts
|
|
2243
|
+
var STREAM_WRITE_ERROR = "STREAM_WRITE_ERROR";
|
|
2244
|
+
var STREAM_READ_ERROR = "STREAM_READ_ERROR";
|
|
2245
|
+
var STREAM_CLOSE_ERROR = "STREAM_CLOSE_ERROR";
|
|
2246
|
+
var STREAM_ENDED = "STREAM_ENDED";
|
|
2247
|
+
function streamWriteError(reason, message, cause) {
|
|
2248
|
+
return {
|
|
2249
|
+
type: STREAM_WRITE_ERROR,
|
|
2250
|
+
reason,
|
|
2251
|
+
message,
|
|
2252
|
+
...cause !== void 0 ? { cause } : {}
|
|
2253
|
+
};
|
|
2254
|
+
}
|
|
2255
|
+
function streamReadError(reason, message, cause) {
|
|
2256
|
+
return {
|
|
2257
|
+
type: STREAM_READ_ERROR,
|
|
2258
|
+
reason,
|
|
2259
|
+
message,
|
|
2260
|
+
...cause !== void 0 ? { cause } : {}
|
|
2261
|
+
};
|
|
2262
|
+
}
|
|
2263
|
+
function streamCloseError(reason, message, cause) {
|
|
2264
|
+
return {
|
|
2265
|
+
type: STREAM_CLOSE_ERROR,
|
|
2266
|
+
reason,
|
|
2267
|
+
message,
|
|
2268
|
+
...cause !== void 0 ? { cause } : {}
|
|
2269
|
+
};
|
|
2270
|
+
}
|
|
2271
|
+
function streamEnded(finalPosition) {
|
|
2272
|
+
return {
|
|
2273
|
+
type: STREAM_ENDED,
|
|
2274
|
+
finalPosition
|
|
2275
|
+
};
|
|
2276
|
+
}
|
|
2277
|
+
|
|
2278
|
+
// src/streaming/backpressure.ts
|
|
2279
|
+
function createBackpressureController(options = {}) {
|
|
2280
|
+
const highWaterMark = options.highWaterMark ?? 16;
|
|
2281
|
+
const lowWaterMark = options.lowWaterMark ?? Math.floor(highWaterMark / 2);
|
|
2282
|
+
const onStateChange = options.onStateChange;
|
|
2283
|
+
let state = "flowing";
|
|
2284
|
+
let bufferedCount = 0;
|
|
2285
|
+
let drainResolvers = [];
|
|
2286
|
+
function updateState(newState) {
|
|
2287
|
+
if (state !== newState) {
|
|
2288
|
+
state = newState;
|
|
2289
|
+
onStateChange?.(newState);
|
|
2290
|
+
if (newState === "flowing" && drainResolvers.length > 0) {
|
|
2291
|
+
const resolvers = drainResolvers;
|
|
2292
|
+
drainResolvers = [];
|
|
2293
|
+
for (const resolve of resolvers) {
|
|
2294
|
+
resolve();
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
function checkState() {
|
|
2300
|
+
if (state === "flowing" && bufferedCount >= highWaterMark) {
|
|
2301
|
+
updateState("paused");
|
|
2302
|
+
} else if (state === "paused" && bufferedCount <= lowWaterMark) {
|
|
2303
|
+
updateState("flowing");
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
return {
|
|
2307
|
+
get state() {
|
|
2308
|
+
return state;
|
|
2309
|
+
},
|
|
2310
|
+
get bufferedCount() {
|
|
2311
|
+
return bufferedCount;
|
|
2312
|
+
},
|
|
2313
|
+
get highWaterMark() {
|
|
2314
|
+
return highWaterMark;
|
|
2315
|
+
},
|
|
2316
|
+
get lowWaterMark() {
|
|
2317
|
+
return lowWaterMark;
|
|
2318
|
+
},
|
|
2319
|
+
increment() {
|
|
2320
|
+
bufferedCount++;
|
|
2321
|
+
checkState();
|
|
2322
|
+
},
|
|
2323
|
+
decrement() {
|
|
2324
|
+
if (bufferedCount > 0) {
|
|
2325
|
+
bufferedCount--;
|
|
2326
|
+
checkState();
|
|
2327
|
+
}
|
|
2328
|
+
},
|
|
2329
|
+
setCount(count) {
|
|
2330
|
+
bufferedCount = Math.max(0, count);
|
|
2331
|
+
checkState();
|
|
2332
|
+
},
|
|
2333
|
+
waitForDrain() {
|
|
2334
|
+
if (state === "flowing") {
|
|
2335
|
+
return Promise.resolve();
|
|
2336
|
+
}
|
|
2337
|
+
return new Promise((resolve) => {
|
|
2338
|
+
drainResolvers.push(resolve);
|
|
2339
|
+
});
|
|
2340
|
+
},
|
|
2341
|
+
reset() {
|
|
2342
|
+
bufferedCount = 0;
|
|
2343
|
+
drainResolvers = [];
|
|
2344
|
+
updateState("flowing");
|
|
2345
|
+
}
|
|
2346
|
+
};
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
// src/workflow/validation.ts
|
|
2350
|
+
async function validateInput(schema, input) {
|
|
2351
|
+
const result = schema["~standard"].validate(input);
|
|
2352
|
+
const resolved = result instanceof Promise ? await result : result;
|
|
2353
|
+
if (resolved.issues) {
|
|
2354
|
+
return err({
|
|
2355
|
+
type: "INPUT_VALIDATION_ERROR",
|
|
2356
|
+
issues: resolved.issues.map((i) => ({
|
|
2357
|
+
message: i.message,
|
|
2358
|
+
path: i.path?.map(
|
|
2359
|
+
(p) => typeof p === "object" ? p.key : p
|
|
2360
|
+
)
|
|
2361
|
+
})),
|
|
2362
|
+
message: `Input validation failed: ${resolved.issues.map((i) => i.message).join(", ")}`
|
|
2363
|
+
});
|
|
2364
|
+
}
|
|
2365
|
+
return ok2(resolved.value);
|
|
2366
|
+
}
|
|
2367
|
+
|
|
2368
|
+
// src/di.ts
|
|
2369
|
+
function withDeps(workflow, overrides) {
|
|
2370
|
+
const forward = (method) => ((...args) => {
|
|
2371
|
+
const last = args.at(-1);
|
|
2372
|
+
const hasConfig = args.length > 0 && typeof last === "object" && last !== null && !Array.isArray(last) && typeof last !== "function";
|
|
2373
|
+
const config = hasConfig ? last : void 0;
|
|
2374
|
+
const head = hasConfig ? args.slice(0, -1) : args;
|
|
2375
|
+
const mergedDeps = { ...overrides, ...config?.deps ?? {} };
|
|
2376
|
+
const mergedConfig = config ? { ...config, deps: mergedDeps } : { deps: mergedDeps };
|
|
2377
|
+
return workflow[method](...head, mergedConfig);
|
|
2378
|
+
});
|
|
2379
|
+
return {
|
|
2380
|
+
run: forward("run"),
|
|
2381
|
+
runWithState: forward("runWithState"),
|
|
2382
|
+
withDeps(nextOverrides) {
|
|
2383
|
+
return withDeps(workflow, { ...overrides, ...nextOverrides });
|
|
2384
|
+
}
|
|
2385
|
+
};
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
// src/workflow/execute.ts
|
|
2389
|
+
function createWorkflow(workflowName, deps, options) {
|
|
2390
|
+
if (typeof workflowName !== "string" || workflowName.length === 0) {
|
|
2391
|
+
throw new TypeError(
|
|
2392
|
+
"createWorkflow(workflowName, deps, options?): first argument must be a non-empty string. Example: createWorkflow('checkout', { chargeCard, sendEmail })"
|
|
2393
|
+
);
|
|
2394
|
+
}
|
|
2395
|
+
const depsActual = deps ?? {};
|
|
2396
|
+
const optionsActual = options;
|
|
2397
|
+
async function internalExecute(runName, userFn, config) {
|
|
2398
|
+
const workflowId = runName ?? crypto.randomUUID();
|
|
2399
|
+
const effectiveDeps = config?.deps ? { ...depsActual, ...config.deps } : depsActual;
|
|
2400
|
+
const compensations = [];
|
|
2401
|
+
const createContextFn = config?.createContext ?? optionsActual?.createContext;
|
|
2402
|
+
const context = createContextFn ? await createContextFn() : void 0;
|
|
2403
|
+
const workflowSignal = config?.signal ?? optionsActual?.signal;
|
|
2404
|
+
const onEventHandler = config?.onEvent ?? optionsActual?.onEvent;
|
|
2405
|
+
const onErrorHandler = config?.onError ?? optionsActual?.onError;
|
|
2406
|
+
const shouldRunHook = config?.shouldRun ?? optionsActual?.shouldRun;
|
|
2407
|
+
const onBeforeStartHook = config?.onBeforeStart ?? optionsActual?.onBeforeStart;
|
|
2408
|
+
const onAfterStepHook = config?.onAfterStep ?? optionsActual?.onAfterStep;
|
|
2409
|
+
const resumeStateOption = config?.resumeState ?? optionsActual?.resumeState;
|
|
2410
|
+
const catchUnexpected = optionsActual?.catchUnexpected ?? defaultCatchUnexpected;
|
|
2411
|
+
const declaredGraph = config?.graph ?? optionsActual?.graph;
|
|
2412
|
+
const workflowData = {};
|
|
2413
|
+
const devWarnings = (config?.devWarnings ?? optionsActual?.devWarnings) === true && process.env.NODE_ENV !== "production";
|
|
2414
|
+
const ctxSetWarned = /* @__PURE__ */ new Set();
|
|
2415
|
+
const ctxGetWarned = /* @__PURE__ */ new Set();
|
|
2416
|
+
const workflowContext = {
|
|
2417
|
+
workflowId,
|
|
2418
|
+
onEvent: onEventHandler,
|
|
2419
|
+
context: context !== void 0 ? context : void 0,
|
|
2420
|
+
signal: workflowSignal,
|
|
2421
|
+
// Data store for static analysis
|
|
2422
|
+
input: {},
|
|
2423
|
+
ref: (key) => workflowData[key],
|
|
2424
|
+
set: (key, value) => {
|
|
2425
|
+
if (devWarnings && !ctxSetWarned.has(key)) {
|
|
2426
|
+
ctxSetWarned.add(key);
|
|
2427
|
+
console.warn(
|
|
2428
|
+
`awaitly: ctx.set('${key}', ...) is deprecated for static analysis. Use step('id', fn, { out: '${key}' }) instead.`
|
|
2429
|
+
);
|
|
2430
|
+
}
|
|
2431
|
+
workflowData[key] = value;
|
|
2432
|
+
},
|
|
2433
|
+
get: (key) => {
|
|
2434
|
+
if (devWarnings && !ctxGetWarned.has(key)) {
|
|
2435
|
+
ctxGetWarned.add(key);
|
|
2436
|
+
console.warn(
|
|
2437
|
+
`awaitly: ctx.get('${key}') is deprecated for static analysis. Use ctx.ref('${key}') instead for tracked dependencies.`
|
|
2438
|
+
);
|
|
2439
|
+
}
|
|
2440
|
+
return workflowData[key];
|
|
2441
|
+
}
|
|
2442
|
+
};
|
|
2443
|
+
const emitEvent = (event) => {
|
|
2444
|
+
const eventWithContext = event.context !== void 0 || context === void 0 ? event : { ...event, context };
|
|
2445
|
+
const eventWithName = eventWithContext.workflowName === void 0 ? { ...eventWithContext, workflowName } : eventWithContext;
|
|
2446
|
+
onEventHandler?.(eventWithName, context);
|
|
2447
|
+
};
|
|
2448
|
+
const createCancelledResult = (reason, lastStepKey2) => {
|
|
2449
|
+
const cancelledError = {
|
|
2450
|
+
type: "WORKFLOW_CANCELLED",
|
|
2451
|
+
reason,
|
|
2452
|
+
lastStepKey: lastStepKey2
|
|
2453
|
+
};
|
|
2454
|
+
return err(catchUnexpected(cancelledError), { cause: cancelledError });
|
|
2455
|
+
};
|
|
2456
|
+
if (workflowSignal?.aborted) {
|
|
2457
|
+
const reason = typeof workflowSignal.reason === "string" ? workflowSignal.reason : workflowSignal.reason instanceof Error ? workflowSignal.reason.message : void 0;
|
|
2458
|
+
emitEvent({
|
|
2459
|
+
type: "workflow_cancelled",
|
|
2460
|
+
workflowId,
|
|
2461
|
+
ts: Date.now(),
|
|
2462
|
+
durationMs: 0,
|
|
2463
|
+
reason
|
|
2464
|
+
});
|
|
2465
|
+
return createCancelledResult(reason);
|
|
2466
|
+
}
|
|
2467
|
+
if (shouldRunHook) {
|
|
2468
|
+
const hookStartTime = performance.now();
|
|
2469
|
+
try {
|
|
2470
|
+
const shouldRunResult = await shouldRunHook(workflowId, context);
|
|
2471
|
+
const hookDuration = performance.now() - hookStartTime;
|
|
2472
|
+
emitEvent({
|
|
2473
|
+
type: "hook_should_run",
|
|
2474
|
+
workflowId,
|
|
2475
|
+
ts: Date.now(),
|
|
2476
|
+
durationMs: hookDuration,
|
|
2477
|
+
result: shouldRunResult,
|
|
2478
|
+
skipped: !shouldRunResult
|
|
2479
|
+
});
|
|
2480
|
+
if (!shouldRunResult) {
|
|
2481
|
+
const skipCause = new Error("Workflow skipped by shouldRun hook");
|
|
2482
|
+
return err(catchUnexpected(skipCause), { cause: skipCause });
|
|
2483
|
+
}
|
|
2484
|
+
} catch (thrown) {
|
|
2485
|
+
const hookDuration = performance.now() - hookStartTime;
|
|
2486
|
+
emitEvent({
|
|
2487
|
+
type: "hook_should_run_error",
|
|
2488
|
+
workflowId,
|
|
2489
|
+
ts: Date.now(),
|
|
2490
|
+
durationMs: hookDuration,
|
|
2491
|
+
error: thrown
|
|
2492
|
+
});
|
|
2493
|
+
return err(catchUnexpected(thrown), { cause: thrown });
|
|
2494
|
+
}
|
|
2495
|
+
}
|
|
2496
|
+
if (onBeforeStartHook) {
|
|
2497
|
+
const hookStartTime = performance.now();
|
|
2498
|
+
try {
|
|
2499
|
+
const beforeStartResult = await onBeforeStartHook(workflowId, context);
|
|
2500
|
+
const hookDuration = performance.now() - hookStartTime;
|
|
2501
|
+
emitEvent({
|
|
2502
|
+
type: "hook_before_start",
|
|
2503
|
+
workflowId,
|
|
2504
|
+
ts: Date.now(),
|
|
2505
|
+
durationMs: hookDuration,
|
|
2506
|
+
result: beforeStartResult,
|
|
2507
|
+
skipped: !beforeStartResult
|
|
2508
|
+
});
|
|
2509
|
+
if (!beforeStartResult) {
|
|
2510
|
+
const skipCause = new Error("Workflow skipped by onBeforeStart hook");
|
|
2511
|
+
return err(catchUnexpected(skipCause), { cause: skipCause });
|
|
2512
|
+
}
|
|
2513
|
+
} catch (thrown) {
|
|
2514
|
+
const hookDuration = performance.now() - hookStartTime;
|
|
2515
|
+
emitEvent({
|
|
2516
|
+
type: "hook_before_start_error",
|
|
2517
|
+
workflowId,
|
|
2518
|
+
ts: Date.now(),
|
|
2519
|
+
durationMs: hookDuration,
|
|
2520
|
+
error: thrown
|
|
2521
|
+
});
|
|
2522
|
+
return err(catchUnexpected(thrown), { cause: thrown });
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
const inputSchema = optionsActual?.inputSchema;
|
|
2526
|
+
const inputValue = optionsActual?.input;
|
|
2527
|
+
if (inputSchema) {
|
|
2528
|
+
const validationResult = await validateInput(inputSchema, inputValue);
|
|
2529
|
+
if (!validationResult.ok) {
|
|
2530
|
+
return err(validationResult.error);
|
|
2531
|
+
}
|
|
2532
|
+
workflowContext.input = validationResult.value;
|
|
2533
|
+
} else if (inputValue !== void 0) {
|
|
2534
|
+
workflowContext.input = inputValue;
|
|
2535
|
+
}
|
|
2536
|
+
const startTs = Date.now();
|
|
2537
|
+
const startTime = performance.now();
|
|
2538
|
+
emitEvent({
|
|
2539
|
+
type: "workflow_start",
|
|
2540
|
+
workflowId,
|
|
2541
|
+
ts: startTs
|
|
2542
|
+
});
|
|
2543
|
+
let cache = config?.cache ?? optionsActual?.cache;
|
|
2544
|
+
const streamStore = config?.streamStore ?? optionsActual?.streamStore;
|
|
2545
|
+
if (resumeStateOption && !cache) {
|
|
2546
|
+
cache = /* @__PURE__ */ new Map();
|
|
2547
|
+
}
|
|
2548
|
+
if (resumeStateOption && cache) {
|
|
2549
|
+
const resumeState = typeof resumeStateOption === "function" ? await resumeStateOption() : resumeStateOption;
|
|
2550
|
+
if (!(resumeState.steps instanceof Map)) {
|
|
2551
|
+
console.warn(
|
|
2552
|
+
`awaitly: resumeState.steps is not a Map (got ${typeof resumeState.steps}). This usually happens when state is serialized with JSON.stringify() directly.
|
|
2553
|
+
Use serializeResumeState() and deserializeResumeState() from 'awaitly/workflow' instead:
|
|
2554
|
+
import { serializeResumeState, deserializeResumeState } from 'awaitly/workflow';
|
|
2555
|
+
const json = JSON.stringify(serializeResumeState(state)); // Save this
|
|
2556
|
+
const restored = deserializeResumeState(JSON.parse(json)); // Load this`
|
|
2557
|
+
);
|
|
2558
|
+
if (typeof resumeState.steps === "object" && resumeState.steps !== null) {
|
|
2559
|
+
resumeState.steps = new Map(Object.entries(resumeState.steps));
|
|
2560
|
+
}
|
|
2561
|
+
}
|
|
2562
|
+
for (const [key, entry] of resumeState.steps) {
|
|
2563
|
+
const { result: result2, meta } = entry;
|
|
2564
|
+
if (result2.ok) {
|
|
2565
|
+
cache.set(key, result2);
|
|
2566
|
+
} else {
|
|
2567
|
+
const effectiveMeta = meta ?? { origin: "result", resultCause: result2.cause };
|
|
2568
|
+
cache.set(key, encodeCachedError(result2.error, effectiveMeta, result2.cause));
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
const snapshotOption = config?.snapshot ?? optionsActual?.snapshot;
|
|
2573
|
+
const snapshotSerialization = optionsActual?.serialization;
|
|
2574
|
+
if (snapshotOption && !resumeStateOption) {
|
|
2575
|
+
if (!cache) {
|
|
2576
|
+
cache = /* @__PURE__ */ new Map();
|
|
2577
|
+
}
|
|
2578
|
+
const snapshot = snapshotOption;
|
|
2579
|
+
const decode = snapshotSerialization?.decode;
|
|
2580
|
+
for (const [stepId, stepResult] of Object.entries(snapshot.steps)) {
|
|
2581
|
+
if (!Object.prototype.hasOwnProperty.call(snapshot.steps, stepId)) {
|
|
2582
|
+
continue;
|
|
2583
|
+
}
|
|
2584
|
+
try {
|
|
2585
|
+
if (stepResult.ok) {
|
|
2586
|
+
const value = decode ? decode(stepResult.value) : stepResult.value;
|
|
2587
|
+
cache.set(stepId, ok2(value));
|
|
2588
|
+
} else {
|
|
2589
|
+
const errorValue = decode ? decode(stepResult.error) : stepResult.error;
|
|
2590
|
+
const deserializedCause = deserializeCauseNew(stepResult.cause);
|
|
2591
|
+
const meta = stepResult.meta?.origin === "throw" ? { origin: "throw", thrown: deserializedCause } : { origin: "result", resultCause: deserializedCause };
|
|
2592
|
+
cache.set(stepId, encodeCachedError(errorValue, meta, deserializedCause));
|
|
2593
|
+
}
|
|
2594
|
+
} catch (e) {
|
|
2595
|
+
throw new SnapshotDecodeError(
|
|
2596
|
+
`Failed to decode step "${stepId}": ${e instanceof Error ? e.message : String(e)}`,
|
|
2597
|
+
stepId,
|
|
2598
|
+
e instanceof Error ? e : void 0
|
|
2599
|
+
);
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
let abortedDuringExecution = false;
|
|
2604
|
+
let abortReason;
|
|
2605
|
+
let lastStepKey;
|
|
2606
|
+
const abortHandler = () => {
|
|
2607
|
+
abortedDuringExecution = true;
|
|
2608
|
+
abortReason = typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0;
|
|
2609
|
+
};
|
|
2610
|
+
if (workflowSignal && !workflowSignal.aborted) {
|
|
2611
|
+
workflowSignal.addEventListener("abort", abortHandler, { once: true });
|
|
2612
|
+
}
|
|
2613
|
+
const checkCancellation = () => {
|
|
2614
|
+
if (abortedDuringExecution || workflowSignal?.aborted) {
|
|
2615
|
+
const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
|
|
2616
|
+
const cancelledError = {
|
|
2617
|
+
type: "WORKFLOW_CANCELLED",
|
|
2618
|
+
reason,
|
|
2619
|
+
lastStepKey
|
|
2620
|
+
};
|
|
2621
|
+
throw cancelledError;
|
|
2622
|
+
}
|
|
2623
|
+
};
|
|
2624
|
+
const callOnAfterStepHook = async (stepKey, result2, _meta) => {
|
|
2625
|
+
if (!onAfterStepHook) return;
|
|
2626
|
+
const hookStartTime = performance.now();
|
|
2627
|
+
try {
|
|
2628
|
+
await onAfterStepHook(stepKey, result2, workflowId, context);
|
|
2629
|
+
const hookDuration = performance.now() - hookStartTime;
|
|
2630
|
+
emitEvent({
|
|
2631
|
+
type: "hook_after_step",
|
|
2632
|
+
workflowId,
|
|
2633
|
+
stepKey,
|
|
2634
|
+
ts: Date.now(),
|
|
2635
|
+
durationMs: hookDuration
|
|
2636
|
+
});
|
|
2637
|
+
} catch (thrown) {
|
|
2638
|
+
const hookDuration = performance.now() - hookStartTime;
|
|
2639
|
+
emitEvent({
|
|
2640
|
+
type: "hook_after_step_error",
|
|
2641
|
+
workflowId,
|
|
2642
|
+
stepKey,
|
|
2643
|
+
ts: Date.now(),
|
|
2644
|
+
durationMs: hookDuration,
|
|
2645
|
+
error: thrown
|
|
2646
|
+
});
|
|
2647
|
+
throw thrown;
|
|
2648
|
+
}
|
|
2649
|
+
};
|
|
2650
|
+
const createCachedStep = (realStep) => {
|
|
2651
|
+
const cachedStepFn = async (idOrOperationOrResult, operationOrOptions, stepOptions) => {
|
|
2652
|
+
if (typeof idOrOperationOrResult !== "string") {
|
|
2653
|
+
throw new Error(
|
|
2654
|
+
'[awaitly] step() requires a string ID as the first argument. Example: step("fetchUser", () => fetchUser(id))'
|
|
2655
|
+
);
|
|
2656
|
+
}
|
|
2657
|
+
const id = idOrOperationOrResult;
|
|
2658
|
+
const opts = stepOptions ?? {};
|
|
2659
|
+
const name = id;
|
|
2660
|
+
const key = Object.prototype.hasOwnProperty.call(opts, "key") ? opts.key : id;
|
|
2661
|
+
const { ttl, out } = opts;
|
|
2662
|
+
checkCancellation();
|
|
2663
|
+
const stepMetadata = extractStepMetadata(opts);
|
|
2664
|
+
if (key && cache && cache.has(key)) {
|
|
2665
|
+
emitEvent({
|
|
2666
|
+
type: "step_cache_hit",
|
|
2667
|
+
workflowId,
|
|
2668
|
+
stepKey: key,
|
|
2669
|
+
name,
|
|
2670
|
+
ts: Date.now(),
|
|
2671
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
2672
|
+
});
|
|
2673
|
+
const cached = cache.get(key);
|
|
2674
|
+
if (cached.ok) {
|
|
2675
|
+
lastStepKey = key;
|
|
2676
|
+
if (out) {
|
|
2677
|
+
workflowData[out] = cached.value;
|
|
2678
|
+
}
|
|
2679
|
+
return cached.value;
|
|
2680
|
+
}
|
|
2681
|
+
const meta = decodeCachedMeta(cached.cause);
|
|
2682
|
+
throw createEarlyExit(cached.error, meta);
|
|
2683
|
+
}
|
|
2684
|
+
if (key && cache) {
|
|
2685
|
+
emitEvent({
|
|
2686
|
+
type: "step_cache_miss",
|
|
2687
|
+
workflowId,
|
|
2688
|
+
stepKey: key,
|
|
2689
|
+
name,
|
|
2690
|
+
ts: Date.now(),
|
|
2691
|
+
...stepMetadata && { metadata: stepMetadata }
|
|
2692
|
+
});
|
|
2693
|
+
}
|
|
2694
|
+
try {
|
|
2695
|
+
const value = await realStep(
|
|
2696
|
+
id,
|
|
2697
|
+
operationOrOptions,
|
|
2698
|
+
opts
|
|
2699
|
+
);
|
|
2700
|
+
if (out) {
|
|
2701
|
+
workflowData[out] = value;
|
|
2702
|
+
}
|
|
2703
|
+
if (opts.compensate) {
|
|
2704
|
+
compensations.push({
|
|
2705
|
+
stepName: name,
|
|
2706
|
+
value,
|
|
2707
|
+
compensate: opts.compensate
|
|
2708
|
+
});
|
|
2709
|
+
}
|
|
2710
|
+
if (key) {
|
|
2711
|
+
lastStepKey = key;
|
|
2712
|
+
if (cache) {
|
|
2713
|
+
cache.set(key, ok2(value), ttl ? { ttl } : void 0);
|
|
2714
|
+
}
|
|
2715
|
+
await callOnAfterStepHook(key, ok2(value));
|
|
2716
|
+
}
|
|
2717
|
+
return value;
|
|
2718
|
+
} catch (thrown) {
|
|
2719
|
+
if (key && isEarlyExit(thrown)) {
|
|
2720
|
+
const exit = thrown;
|
|
2721
|
+
const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
|
|
2722
|
+
const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
|
|
2723
|
+
if (cache) {
|
|
2724
|
+
cache.set(key, errorResult, ttl ? { ttl } : void 0);
|
|
2725
|
+
}
|
|
2726
|
+
await callOnAfterStepHook(key, errorResult, exit.meta);
|
|
2727
|
+
}
|
|
2728
|
+
throw thrown;
|
|
2729
|
+
}
|
|
2730
|
+
};
|
|
2731
|
+
cachedStepFn.try = async (id, operation, opts) => {
|
|
2732
|
+
const { ttl } = opts;
|
|
2733
|
+
const key = opts.key ?? id;
|
|
2734
|
+
const name = id;
|
|
2735
|
+
if (cache && cache.has(key)) {
|
|
2736
|
+
emitEvent({
|
|
2737
|
+
type: "step_cache_hit",
|
|
2738
|
+
workflowId,
|
|
2739
|
+
stepKey: key,
|
|
2740
|
+
name,
|
|
2741
|
+
ts: Date.now()
|
|
2742
|
+
});
|
|
2743
|
+
const cached = cache.get(key);
|
|
2744
|
+
if (cached.ok) {
|
|
2745
|
+
return cached.value;
|
|
2746
|
+
}
|
|
2747
|
+
const meta = decodeCachedMeta(cached.cause);
|
|
2748
|
+
throw createEarlyExit(cached.error, meta);
|
|
2749
|
+
}
|
|
2750
|
+
if (cache) {
|
|
2751
|
+
emitEvent({
|
|
2752
|
+
type: "step_cache_miss",
|
|
2753
|
+
workflowId,
|
|
2754
|
+
stepKey: key,
|
|
2755
|
+
name,
|
|
2756
|
+
ts: Date.now()
|
|
2757
|
+
});
|
|
2758
|
+
}
|
|
2759
|
+
try {
|
|
2760
|
+
const value = await realStep.try(id, operation, { ...opts, key });
|
|
2761
|
+
if (opts.compensate) {
|
|
2762
|
+
compensations.push({
|
|
2763
|
+
stepName: name,
|
|
2764
|
+
value,
|
|
2765
|
+
compensate: opts.compensate
|
|
2766
|
+
});
|
|
2767
|
+
}
|
|
2768
|
+
if (cache) {
|
|
2769
|
+
cache.set(key, ok2(value), ttl ? { ttl } : void 0);
|
|
2770
|
+
}
|
|
2771
|
+
await callOnAfterStepHook(key, ok2(value));
|
|
2772
|
+
return value;
|
|
2773
|
+
} catch (thrown) {
|
|
2774
|
+
if (isEarlyExit(thrown)) {
|
|
2775
|
+
const exit = thrown;
|
|
2776
|
+
const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
|
|
2777
|
+
const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
|
|
2778
|
+
if (cache) {
|
|
2779
|
+
cache.set(key, errorResult, ttl ? { ttl } : void 0);
|
|
2780
|
+
}
|
|
2781
|
+
await callOnAfterStepHook(key, errorResult, exit.meta);
|
|
2782
|
+
}
|
|
2783
|
+
throw thrown;
|
|
2784
|
+
}
|
|
2785
|
+
};
|
|
2786
|
+
cachedStepFn.fromResult = async (id, operation, opts) => {
|
|
2787
|
+
const { ttl } = opts;
|
|
2788
|
+
const key = opts.key ?? id;
|
|
2789
|
+
const name = id;
|
|
2790
|
+
if (cache && cache.has(key)) {
|
|
2791
|
+
emitEvent({
|
|
2792
|
+
type: "step_cache_hit",
|
|
2793
|
+
workflowId,
|
|
2794
|
+
stepKey: key,
|
|
2795
|
+
name,
|
|
2796
|
+
ts: Date.now()
|
|
2797
|
+
});
|
|
2798
|
+
const cached = cache.get(key);
|
|
2799
|
+
if (cached.ok) {
|
|
2800
|
+
return cached.value;
|
|
2801
|
+
}
|
|
2802
|
+
const meta = decodeCachedMeta(cached.cause);
|
|
2803
|
+
throw createEarlyExit(cached.error, meta);
|
|
2804
|
+
}
|
|
2805
|
+
if (cache) {
|
|
2806
|
+
emitEvent({
|
|
2807
|
+
type: "step_cache_miss",
|
|
2808
|
+
workflowId,
|
|
2809
|
+
stepKey: key,
|
|
2810
|
+
name,
|
|
2811
|
+
ts: Date.now()
|
|
2812
|
+
});
|
|
2813
|
+
}
|
|
2814
|
+
try {
|
|
2815
|
+
const value = await realStep.fromResult(id, operation, { ...opts, key });
|
|
2816
|
+
if (cache) {
|
|
2817
|
+
cache.set(key, ok2(value), ttl ? { ttl } : void 0);
|
|
2818
|
+
}
|
|
2819
|
+
await callOnAfterStepHook(key, ok2(value));
|
|
2820
|
+
return value;
|
|
2821
|
+
} catch (thrown) {
|
|
2822
|
+
if (isEarlyExit(thrown)) {
|
|
2823
|
+
const exit = thrown;
|
|
2824
|
+
const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
|
|
2825
|
+
const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
|
|
2826
|
+
if (cache) {
|
|
2827
|
+
cache.set(key, errorResult, ttl ? { ttl } : void 0);
|
|
2828
|
+
}
|
|
2829
|
+
await callOnAfterStepHook(key, errorResult, exit.meta);
|
|
2830
|
+
}
|
|
2831
|
+
throw thrown;
|
|
2832
|
+
}
|
|
2833
|
+
};
|
|
2834
|
+
cachedStepFn.race = realStep.race;
|
|
2835
|
+
cachedStepFn.withFallback = async (id, operation, options2) => {
|
|
2836
|
+
const key = options2.key ?? id;
|
|
2837
|
+
const name = id;
|
|
2838
|
+
if (cache && cache.has(key)) {
|
|
2839
|
+
emitEvent({
|
|
2840
|
+
type: "step_cache_hit",
|
|
2841
|
+
workflowId,
|
|
2842
|
+
stepKey: key,
|
|
2843
|
+
name,
|
|
2844
|
+
ts: Date.now()
|
|
2845
|
+
});
|
|
2846
|
+
const cached = cache.get(key);
|
|
2847
|
+
if (cached.ok) {
|
|
2848
|
+
return cached.value;
|
|
2849
|
+
}
|
|
2850
|
+
const meta = decodeCachedMeta(cached.cause);
|
|
2851
|
+
throw createEarlyExit(cached.error, meta);
|
|
2852
|
+
}
|
|
2853
|
+
if (cache) {
|
|
2854
|
+
emitEvent({
|
|
2855
|
+
type: "step_cache_miss",
|
|
2856
|
+
workflowId,
|
|
2857
|
+
stepKey: key,
|
|
2858
|
+
name,
|
|
2859
|
+
ts: Date.now()
|
|
2860
|
+
});
|
|
2861
|
+
}
|
|
2862
|
+
try {
|
|
2863
|
+
const value = await realStep.withFallback(
|
|
2864
|
+
id,
|
|
2865
|
+
operation,
|
|
2866
|
+
options2
|
|
2867
|
+
);
|
|
2868
|
+
if (cache) {
|
|
2869
|
+
cache.set(key, ok2(value));
|
|
2870
|
+
}
|
|
2871
|
+
await callOnAfterStepHook(key, ok2(value));
|
|
2872
|
+
return value;
|
|
2873
|
+
} catch (thrown) {
|
|
2874
|
+
if (isEarlyExit(thrown)) {
|
|
2875
|
+
const exit = thrown;
|
|
2876
|
+
const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
|
|
2877
|
+
const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
|
|
2878
|
+
if (cache) {
|
|
2879
|
+
cache.set(key, errorResult);
|
|
2880
|
+
}
|
|
2881
|
+
await callOnAfterStepHook(key, errorResult, exit.meta);
|
|
2882
|
+
}
|
|
2883
|
+
throw thrown;
|
|
2884
|
+
}
|
|
2885
|
+
};
|
|
2886
|
+
cachedStepFn.withResource = async (id, options2) => {
|
|
2887
|
+
const key = id;
|
|
2888
|
+
try {
|
|
2889
|
+
const value = await realStep.withResource(id, options2);
|
|
2890
|
+
await callOnAfterStepHook(key, ok2(value));
|
|
2891
|
+
return value;
|
|
2892
|
+
} catch (thrown) {
|
|
2893
|
+
if (isEarlyExit(thrown)) {
|
|
2894
|
+
const exit = thrown;
|
|
2895
|
+
const originalCause = exit.meta.origin === "result" ? exit.meta.resultCause : exit.meta.origin === "throw" ? exit.meta.thrown : void 0;
|
|
2896
|
+
const errorResult = encodeCachedError(exit.error, exit.meta, originalCause);
|
|
2897
|
+
await callOnAfterStepHook(key, errorResult, exit.meta);
|
|
2898
|
+
}
|
|
2899
|
+
throw thrown;
|
|
2900
|
+
}
|
|
2901
|
+
};
|
|
2902
|
+
cachedStepFn.retry = (id, operation, options2) => {
|
|
2903
|
+
const stepOptions = {
|
|
2904
|
+
key: options2.key,
|
|
2905
|
+
// explicitly pass so undefined = don't cache
|
|
2906
|
+
retry: {
|
|
2907
|
+
attempts: options2.attempts,
|
|
2908
|
+
backoff: options2.backoff,
|
|
2909
|
+
initialDelay: options2.initialDelay,
|
|
2910
|
+
maxDelay: options2.maxDelay,
|
|
2911
|
+
jitter: options2.jitter,
|
|
2912
|
+
shouldRetry: options2.shouldRetry,
|
|
2913
|
+
onRetry: options2.onRetry
|
|
2914
|
+
},
|
|
2915
|
+
timeout: options2.timeout,
|
|
2916
|
+
ttl: options2.ttl
|
|
2917
|
+
};
|
|
2918
|
+
return cachedStepFn(id, operation, stepOptions);
|
|
2919
|
+
};
|
|
2920
|
+
cachedStepFn.withTimeout = (id, operation, options2) => {
|
|
2921
|
+
const stepOptions = {
|
|
2922
|
+
key: options2.key,
|
|
2923
|
+
timeout: options2,
|
|
2924
|
+
ttl: options2.ttl
|
|
2925
|
+
};
|
|
2926
|
+
return cachedStepFn(
|
|
2927
|
+
id,
|
|
2928
|
+
operation,
|
|
2929
|
+
stepOptions
|
|
2930
|
+
);
|
|
2931
|
+
};
|
|
2932
|
+
cachedStepFn.sleep = (id, duration, options2) => {
|
|
2933
|
+
if (typeof id !== "string" || id.length === 0) {
|
|
2934
|
+
throw new Error(
|
|
2935
|
+
'[awaitly] step.sleep() requires an explicit string ID as the first argument. Example: step.sleep("delay", "5s")'
|
|
2936
|
+
);
|
|
2937
|
+
}
|
|
2938
|
+
const d = typeof duration === "string" ? parse(duration) : duration;
|
|
2939
|
+
if (!d) {
|
|
2940
|
+
throw new Error(`step.sleep: invalid duration '${duration}'`);
|
|
2941
|
+
}
|
|
2942
|
+
const ms = toMillis(d);
|
|
2943
|
+
const userSignal = options2?.signal;
|
|
2944
|
+
const sleepOperation = async () => {
|
|
2945
|
+
if (workflowSignal?.aborted || userSignal?.aborted) {
|
|
2946
|
+
const e = new Error("Sleep aborted");
|
|
2947
|
+
e.name = "AbortError";
|
|
2948
|
+
throw e;
|
|
2949
|
+
}
|
|
2950
|
+
return new Promise((resolve, reject) => {
|
|
2951
|
+
const state = {
|
|
2952
|
+
timeoutId: void 0
|
|
2953
|
+
};
|
|
2954
|
+
const onAbort = () => {
|
|
2955
|
+
if (state.timeoutId) clearTimeout(state.timeoutId);
|
|
2956
|
+
const e = new Error("Sleep aborted");
|
|
2957
|
+
e.name = "AbortError";
|
|
2958
|
+
reject(e);
|
|
2959
|
+
};
|
|
2960
|
+
workflowSignal?.addEventListener("abort", onAbort, { once: true });
|
|
2961
|
+
userSignal?.addEventListener("abort", onAbort, { once: true });
|
|
2962
|
+
state.timeoutId = setTimeout(() => {
|
|
2963
|
+
workflowSignal?.removeEventListener("abort", onAbort);
|
|
2964
|
+
userSignal?.removeEventListener("abort", onAbort);
|
|
2965
|
+
resolve(ok2(void 0));
|
|
2966
|
+
}, ms);
|
|
2967
|
+
});
|
|
2968
|
+
};
|
|
2969
|
+
return cachedStepFn(id, sleepOperation, {
|
|
2970
|
+
key: options2?.key,
|
|
2971
|
+
ttl: options2?.ttl,
|
|
2972
|
+
description: options2?.description
|
|
2973
|
+
});
|
|
2974
|
+
};
|
|
2975
|
+
const activeWriters = /* @__PURE__ */ new Map();
|
|
2976
|
+
const activeReaders = /* @__PURE__ */ new Map();
|
|
2977
|
+
cachedStepFn.getWritable = (options2) => {
|
|
2978
|
+
const namespace = options2?.namespace ?? "default";
|
|
2979
|
+
const highWaterMark = options2?.highWaterMark ?? 16;
|
|
2980
|
+
if (!streamStore) {
|
|
2981
|
+
throw new Error(
|
|
2982
|
+
"streamStore is required to use getWritable(). Pass a streamStore to createWorkflow options."
|
|
2983
|
+
);
|
|
2984
|
+
}
|
|
2985
|
+
const existingKey = `${workflowId}:${namespace}`;
|
|
2986
|
+
const existing = activeWriters.get(existingKey);
|
|
2987
|
+
if (existing && !existing.closed && !existing.aborted) {
|
|
2988
|
+
return existing.writer;
|
|
2989
|
+
}
|
|
2990
|
+
const backpressure = createBackpressureController({
|
|
2991
|
+
highWaterMark,
|
|
2992
|
+
onStateChange: (state) => {
|
|
2993
|
+
emitEvent({
|
|
2994
|
+
type: "stream_backpressure",
|
|
2995
|
+
workflowId,
|
|
2996
|
+
namespace,
|
|
2997
|
+
bufferedCount: backpressure.bufferedCount,
|
|
2998
|
+
state,
|
|
2999
|
+
ts: Date.now()
|
|
3000
|
+
});
|
|
3001
|
+
}
|
|
3002
|
+
});
|
|
3003
|
+
let position = 0;
|
|
3004
|
+
let writable = true;
|
|
3005
|
+
let aborted = false;
|
|
3006
|
+
let closed = false;
|
|
3007
|
+
emitEvent({
|
|
3008
|
+
type: "stream_created",
|
|
3009
|
+
workflowId,
|
|
3010
|
+
namespace,
|
|
3011
|
+
ts: Date.now()
|
|
3012
|
+
});
|
|
3013
|
+
const writer = {
|
|
3014
|
+
async write(value) {
|
|
3015
|
+
if (closed) {
|
|
3016
|
+
return err(streamWriteError("closed", "Stream is closed"));
|
|
3017
|
+
}
|
|
3018
|
+
if (aborted) {
|
|
3019
|
+
return err(streamWriteError("aborted", "Stream was aborted"));
|
|
3020
|
+
}
|
|
3021
|
+
if (backpressure.state === "paused") {
|
|
3022
|
+
await backpressure.waitForDrain();
|
|
3023
|
+
}
|
|
3024
|
+
const item = {
|
|
3025
|
+
value,
|
|
3026
|
+
position,
|
|
3027
|
+
ts: Date.now()
|
|
3028
|
+
};
|
|
3029
|
+
const result2 = await streamStore.append(workflowId, namespace, item);
|
|
3030
|
+
if (!result2.ok) {
|
|
3031
|
+
emitEvent({
|
|
3032
|
+
type: "stream_error",
|
|
3033
|
+
workflowId,
|
|
3034
|
+
namespace,
|
|
3035
|
+
error: result2.error,
|
|
3036
|
+
position,
|
|
3037
|
+
ts: Date.now()
|
|
3038
|
+
});
|
|
3039
|
+
return err(streamWriteError("store_error", result2.error.message, result2.error));
|
|
3040
|
+
}
|
|
3041
|
+
emitEvent({
|
|
3042
|
+
type: "stream_write",
|
|
3043
|
+
workflowId,
|
|
3044
|
+
namespace,
|
|
3045
|
+
position,
|
|
3046
|
+
ts: Date.now()
|
|
3047
|
+
});
|
|
3048
|
+
position++;
|
|
3049
|
+
backpressure.increment();
|
|
3050
|
+
return ok2(void 0);
|
|
3051
|
+
},
|
|
3052
|
+
async close() {
|
|
3053
|
+
if (closed) {
|
|
3054
|
+
return err(streamCloseError("already_closed", "Stream is already closed"));
|
|
3055
|
+
}
|
|
3056
|
+
const result2 = await streamStore.closeStream(workflowId, namespace);
|
|
3057
|
+
if (!result2.ok) {
|
|
3058
|
+
return err(streamCloseError("store_error", result2.error.message, result2.error));
|
|
3059
|
+
}
|
|
3060
|
+
closed = true;
|
|
3061
|
+
writable = false;
|
|
3062
|
+
emitEvent({
|
|
3063
|
+
type: "stream_close",
|
|
3064
|
+
workflowId,
|
|
3065
|
+
namespace,
|
|
3066
|
+
finalPosition: position,
|
|
3067
|
+
ts: Date.now()
|
|
3068
|
+
});
|
|
3069
|
+
activeWriters.delete(existingKey);
|
|
3070
|
+
return ok2(void 0);
|
|
3071
|
+
},
|
|
3072
|
+
abort(reason) {
|
|
3073
|
+
aborted = true;
|
|
3074
|
+
writable = false;
|
|
3075
|
+
closed = true;
|
|
3076
|
+
emitEvent({
|
|
3077
|
+
type: "stream_error",
|
|
3078
|
+
workflowId,
|
|
3079
|
+
namespace,
|
|
3080
|
+
error: reason,
|
|
3081
|
+
position,
|
|
3082
|
+
ts: Date.now()
|
|
3083
|
+
});
|
|
3084
|
+
activeWriters.delete(existingKey);
|
|
3085
|
+
},
|
|
3086
|
+
get writable() {
|
|
3087
|
+
return writable;
|
|
3088
|
+
},
|
|
3089
|
+
get position() {
|
|
3090
|
+
return position;
|
|
3091
|
+
},
|
|
3092
|
+
get namespace() {
|
|
3093
|
+
return namespace;
|
|
3094
|
+
}
|
|
3095
|
+
};
|
|
3096
|
+
activeWriters.set(existingKey, {
|
|
3097
|
+
writer,
|
|
3098
|
+
backpressure,
|
|
3099
|
+
aborted,
|
|
3100
|
+
closed
|
|
3101
|
+
});
|
|
3102
|
+
return writer;
|
|
3103
|
+
};
|
|
3104
|
+
cachedStepFn.getReadable = (options2) => {
|
|
3105
|
+
const namespace = options2?.namespace ?? "default";
|
|
3106
|
+
const startIndex = options2?.startIndex ?? 0;
|
|
3107
|
+
const pollInterval = options2?.pollInterval ?? 10;
|
|
3108
|
+
const pollTimeout = options2?.pollTimeout ?? 3e4;
|
|
3109
|
+
if (!streamStore) {
|
|
3110
|
+
throw new Error(
|
|
3111
|
+
"streamStore is required to use getReadable(). Pass a streamStore to createWorkflow options."
|
|
3112
|
+
);
|
|
3113
|
+
}
|
|
3114
|
+
const existingKey = `${workflowId}:${namespace}:${startIndex}`;
|
|
3115
|
+
const existing = activeReaders.get(existingKey);
|
|
3116
|
+
if (existing && !existing.closed) {
|
|
3117
|
+
return existing.reader;
|
|
3118
|
+
}
|
|
3119
|
+
const decrementBackpressure = () => {
|
|
3120
|
+
const writerKey = `${workflowId}:${namespace}`;
|
|
3121
|
+
const activeWriter = activeWriters.get(writerKey);
|
|
3122
|
+
if (activeWriter) {
|
|
3123
|
+
activeWriter.backpressure.decrement();
|
|
3124
|
+
}
|
|
3125
|
+
};
|
|
3126
|
+
let position = startIndex;
|
|
3127
|
+
let readable = true;
|
|
3128
|
+
let closed = false;
|
|
3129
|
+
let bufferedItems = [];
|
|
3130
|
+
let bufferIndex = 0;
|
|
3131
|
+
const reader = {
|
|
3132
|
+
async read() {
|
|
3133
|
+
if (closed) {
|
|
3134
|
+
return err(streamReadError("closed", "Reader is closed"));
|
|
3135
|
+
}
|
|
3136
|
+
if (bufferIndex < bufferedItems.length) {
|
|
3137
|
+
const item = bufferedItems[bufferIndex++];
|
|
3138
|
+
position = item.position + 1;
|
|
3139
|
+
decrementBackpressure();
|
|
3140
|
+
emitEvent({
|
|
3141
|
+
type: "stream_read",
|
|
3142
|
+
workflowId,
|
|
3143
|
+
namespace,
|
|
3144
|
+
position: item.position,
|
|
3145
|
+
ts: Date.now()
|
|
3146
|
+
});
|
|
3147
|
+
return ok2(item.value);
|
|
3148
|
+
}
|
|
3149
|
+
const writerKey = `${workflowId}:${namespace}`;
|
|
3150
|
+
const pollStart = Date.now();
|
|
3151
|
+
let hasSeenWriter = activeWriters.has(writerKey);
|
|
3152
|
+
const initialMetaResult = await streamStore.getMetadata(workflowId, namespace);
|
|
3153
|
+
let hasSeenMetadata = initialMetaResult.ok && initialMetaResult.value !== void 0;
|
|
3154
|
+
while (Date.now() - pollStart < pollTimeout) {
|
|
3155
|
+
const result2 = await streamStore.read(workflowId, namespace, position, 100);
|
|
3156
|
+
if (!result2.ok) {
|
|
3157
|
+
return err(streamReadError("store_error", result2.error.message, result2.error));
|
|
3158
|
+
}
|
|
3159
|
+
const items = result2.value;
|
|
3160
|
+
if (items.length > 0) {
|
|
3161
|
+
bufferedItems = items;
|
|
3162
|
+
bufferIndex = 1;
|
|
3163
|
+
const item = items[0];
|
|
3164
|
+
position = item.position + 1;
|
|
3165
|
+
decrementBackpressure();
|
|
3166
|
+
emitEvent({
|
|
3167
|
+
type: "stream_read",
|
|
3168
|
+
workflowId,
|
|
3169
|
+
namespace,
|
|
3170
|
+
position: item.position,
|
|
3171
|
+
ts: Date.now()
|
|
3172
|
+
});
|
|
3173
|
+
return ok2(item.value);
|
|
3174
|
+
}
|
|
3175
|
+
const writerActive = activeWriters.has(writerKey);
|
|
3176
|
+
const metaResult = await streamStore.getMetadata(workflowId, namespace);
|
|
3177
|
+
const metadataExists = metaResult.ok && metaResult.value !== void 0;
|
|
3178
|
+
if (writerActive) hasSeenWriter = true;
|
|
3179
|
+
if (metadataExists) hasSeenMetadata = true;
|
|
3180
|
+
if (metaResult.ok && metaResult.value?.closed) {
|
|
3181
|
+
readable = false;
|
|
3182
|
+
return err(streamEnded(position));
|
|
3183
|
+
}
|
|
3184
|
+
if (hasSeenWriter && !writerActive && !metadataExists) {
|
|
3185
|
+
readable = false;
|
|
3186
|
+
return err(streamEnded(position));
|
|
3187
|
+
}
|
|
3188
|
+
if (hasSeenMetadata && !writerActive && metaResult.ok && !metaResult.value?.closed) {
|
|
3189
|
+
}
|
|
3190
|
+
await new Promise((resolve) => setTimeout(resolve, pollInterval));
|
|
3191
|
+
}
|
|
3192
|
+
readable = false;
|
|
3193
|
+
return err(streamEnded(position));
|
|
3194
|
+
},
|
|
3195
|
+
close() {
|
|
3196
|
+
closed = true;
|
|
3197
|
+
readable = false;
|
|
3198
|
+
bufferedItems = [];
|
|
3199
|
+
activeReaders.delete(existingKey);
|
|
3200
|
+
},
|
|
3201
|
+
get readable() {
|
|
3202
|
+
return readable;
|
|
3203
|
+
},
|
|
3204
|
+
get position() {
|
|
3205
|
+
return position;
|
|
3206
|
+
},
|
|
3207
|
+
get namespace() {
|
|
3208
|
+
return namespace;
|
|
3209
|
+
}
|
|
3210
|
+
};
|
|
3211
|
+
activeReaders.set(existingKey, {
|
|
3212
|
+
reader,
|
|
3213
|
+
position,
|
|
3214
|
+
closed
|
|
3215
|
+
});
|
|
3216
|
+
return reader;
|
|
3217
|
+
};
|
|
3218
|
+
cachedStepFn.streamForEach = async (source, processor, options2) => {
|
|
3219
|
+
const checkpointInterval = options2?.checkpointInterval ?? 1;
|
|
3220
|
+
const concurrency = options2?.concurrency ?? 1;
|
|
3221
|
+
const results = [];
|
|
3222
|
+
let processedCount = 0;
|
|
3223
|
+
let lastPosition = -1;
|
|
3224
|
+
const isStreamReader = (s) => {
|
|
3225
|
+
return typeof s === "object" && s !== null && "read" in s && typeof s.read === "function";
|
|
3226
|
+
};
|
|
3227
|
+
const processItem = async (item, itemIndex, itemPosition, namespace) => {
|
|
3228
|
+
const shouldCheckpoint = checkpointInterval > 0 && itemIndex % checkpointInterval === 0;
|
|
3229
|
+
const stepKey = shouldCheckpoint ? `stream-foreach:${namespace}:pos-${itemPosition}` : void 0;
|
|
3230
|
+
const stepId = stepKey ?? `stream-item-${itemPosition}`;
|
|
3231
|
+
const stepResult = await cachedStepFn(
|
|
3232
|
+
stepId,
|
|
3233
|
+
() => processor(item, itemIndex),
|
|
3234
|
+
{ key: stepKey }
|
|
3235
|
+
);
|
|
3236
|
+
return { index: itemIndex, position: itemPosition, result: stepResult };
|
|
3237
|
+
};
|
|
3238
|
+
if (isStreamReader(source)) {
|
|
3239
|
+
if (concurrency <= 1) {
|
|
3240
|
+
let itemPosition = source.position;
|
|
3241
|
+
let readResult = await source.read();
|
|
3242
|
+
while (readResult.ok) {
|
|
3243
|
+
const item = readResult.value;
|
|
3244
|
+
const { result: result2 } = await processItem(item, processedCount, itemPosition, source.namespace);
|
|
3245
|
+
results.push(result2);
|
|
3246
|
+
lastPosition = itemPosition;
|
|
3247
|
+
processedCount++;
|
|
3248
|
+
itemPosition = source.position;
|
|
3249
|
+
readResult = await source.read();
|
|
3250
|
+
}
|
|
3251
|
+
} else {
|
|
3252
|
+
const resultsMap = /* @__PURE__ */ new Map();
|
|
3253
|
+
let itemIndex = 0;
|
|
3254
|
+
let totalItems = 0;
|
|
3255
|
+
const slots = new Array(concurrency).fill(null);
|
|
3256
|
+
const getSlot = async () => {
|
|
3257
|
+
for (let i = 0; i < slots.length; i++) {
|
|
3258
|
+
if (slots[i] === null) return i;
|
|
3259
|
+
}
|
|
3260
|
+
const activePromises = slots.filter((s) => s !== null);
|
|
3261
|
+
const completed = await Promise.race(activePromises);
|
|
3262
|
+
resultsMap.set(completed.index, { position: completed.position, result: completed.result });
|
|
3263
|
+
slots[completed.slotIndex] = null;
|
|
3264
|
+
return completed.slotIndex;
|
|
3265
|
+
};
|
|
3266
|
+
let itemPosition = source.position;
|
|
3267
|
+
let readResult = await source.read();
|
|
3268
|
+
while (readResult.ok) {
|
|
3269
|
+
const slotIndex = await getSlot();
|
|
3270
|
+
const currentIndex = itemIndex;
|
|
3271
|
+
const currentPosition = itemPosition;
|
|
3272
|
+
const currentItem = readResult.value;
|
|
3273
|
+
const currentSlot = slotIndex;
|
|
3274
|
+
slots[slotIndex] = processItem(currentItem, currentIndex, currentPosition, source.namespace).then((r) => ({ slotIndex: currentSlot, ...r }));
|
|
3275
|
+
totalItems++;
|
|
3276
|
+
itemIndex++;
|
|
3277
|
+
itemPosition = source.position;
|
|
3278
|
+
readResult = await source.read();
|
|
3279
|
+
}
|
|
3280
|
+
for (let i = 0; i < slots.length; i++) {
|
|
3281
|
+
if (slots[i] !== null) {
|
|
3282
|
+
const result2 = await slots[i];
|
|
3283
|
+
resultsMap.set(result2.index, { position: result2.position, result: result2.result });
|
|
3284
|
+
}
|
|
3285
|
+
}
|
|
3286
|
+
for (let i = 0; i < totalItems; i++) {
|
|
3287
|
+
const entry = resultsMap.get(i);
|
|
3288
|
+
if (entry) {
|
|
3289
|
+
results.push(entry.result);
|
|
3290
|
+
lastPosition = entry.position;
|
|
3291
|
+
processedCount++;
|
|
3292
|
+
}
|
|
3293
|
+
}
|
|
3294
|
+
}
|
|
3295
|
+
} else {
|
|
3296
|
+
if (concurrency <= 1) {
|
|
3297
|
+
let index = 0;
|
|
3298
|
+
for await (const item of source) {
|
|
3299
|
+
const { result: result2 } = await processItem(item, index, index, "async-iterable");
|
|
3300
|
+
results.push(result2);
|
|
3301
|
+
lastPosition = index;
|
|
3302
|
+
processedCount++;
|
|
3303
|
+
index++;
|
|
3304
|
+
}
|
|
3305
|
+
} else {
|
|
3306
|
+
const resultsMap = /* @__PURE__ */ new Map();
|
|
3307
|
+
let itemIndex = 0;
|
|
3308
|
+
let totalItems = 0;
|
|
3309
|
+
const slots = new Array(concurrency).fill(null);
|
|
3310
|
+
const getSlot = async () => {
|
|
3311
|
+
for (let i = 0; i < slots.length; i++) {
|
|
3312
|
+
if (slots[i] === null) return i;
|
|
3313
|
+
}
|
|
3314
|
+
const activePromises = slots.filter((s) => s !== null);
|
|
3315
|
+
const completed = await Promise.race(activePromises);
|
|
3316
|
+
resultsMap.set(completed.index, completed.result);
|
|
3317
|
+
slots[completed.slotIndex] = null;
|
|
3318
|
+
return completed.slotIndex;
|
|
3319
|
+
};
|
|
3320
|
+
for await (const item of source) {
|
|
3321
|
+
const slotIndex = await getSlot();
|
|
3322
|
+
const currentIndex = itemIndex;
|
|
3323
|
+
const currentSlot = slotIndex;
|
|
3324
|
+
slots[slotIndex] = processItem(item, currentIndex, currentIndex, "async-iterable").then((r) => ({ slotIndex: currentSlot, ...r }));
|
|
3325
|
+
totalItems++;
|
|
3326
|
+
itemIndex++;
|
|
3327
|
+
}
|
|
3328
|
+
for (let i = 0; i < slots.length; i++) {
|
|
3329
|
+
if (slots[i] !== null) {
|
|
3330
|
+
const result2 = await slots[i];
|
|
3331
|
+
resultsMap.set(result2.index, result2.result);
|
|
3332
|
+
}
|
|
3333
|
+
}
|
|
3334
|
+
for (let i = 0; i < totalItems; i++) {
|
|
3335
|
+
if (resultsMap.has(i)) {
|
|
3336
|
+
results.push(resultsMap.get(i));
|
|
3337
|
+
lastPosition = i;
|
|
3338
|
+
processedCount++;
|
|
3339
|
+
}
|
|
3340
|
+
}
|
|
3341
|
+
}
|
|
3342
|
+
}
|
|
3343
|
+
return {
|
|
3344
|
+
results,
|
|
3345
|
+
processedCount,
|
|
3346
|
+
lastPosition
|
|
3347
|
+
};
|
|
3348
|
+
};
|
|
3349
|
+
cachedStepFn.if = realStep.if;
|
|
3350
|
+
cachedStepFn.label = realStep.label;
|
|
3351
|
+
cachedStepFn.branch = realStep.branch;
|
|
3352
|
+
cachedStepFn.arm = realStep.arm;
|
|
3353
|
+
cachedStepFn.forEach = realStep.forEach;
|
|
3354
|
+
cachedStepFn.item = realStep.item;
|
|
3355
|
+
cachedStepFn.dep = realStep.dep;
|
|
3356
|
+
cachedStepFn.workflow = (id, getter, options2) => cachedStepFn(id, getter, options2);
|
|
3357
|
+
cachedStepFn.all = (id, shape, options2) => {
|
|
3358
|
+
const opts = options2 !== void 0 && Object.prototype.hasOwnProperty.call(options2, "key") ? options2 : { ...options2, key: void 0 };
|
|
3359
|
+
return cachedStepFn(id, async () => ok2(await realStep.all(id, shape)), opts);
|
|
3360
|
+
};
|
|
3361
|
+
cachedStepFn.map = (id, items, mapper, options2) => {
|
|
3362
|
+
const opts = options2 !== void 0 && Object.prototype.hasOwnProperty.call(options2, "key") ? options2 : { ...options2, key: void 0 };
|
|
3363
|
+
return cachedStepFn(id, async () => ok2(await realStep.map(id, items, mapper, options2)), opts);
|
|
3364
|
+
};
|
|
3365
|
+
return cachedStepFn;
|
|
3366
|
+
};
|
|
3367
|
+
const wrappedFn = ({ step }) => {
|
|
3368
|
+
const cachedStep = createCachedStep(step);
|
|
3369
|
+
return userFn({
|
|
3370
|
+
step: cachedStep,
|
|
3371
|
+
steps: bindSteps(effectiveDeps ?? {}, cachedStep),
|
|
3372
|
+
deps: effectiveDeps,
|
|
3373
|
+
ctx: workflowContext
|
|
3374
|
+
});
|
|
3375
|
+
};
|
|
3376
|
+
let result;
|
|
3377
|
+
try {
|
|
3378
|
+
result = await run(wrappedFn, {
|
|
3379
|
+
onError: onErrorHandler,
|
|
3380
|
+
onEvent: onEventHandler,
|
|
3381
|
+
catchUnexpected,
|
|
3382
|
+
workflowId,
|
|
3383
|
+
workflowName,
|
|
3384
|
+
context,
|
|
3385
|
+
graph: declaredGraph,
|
|
3386
|
+
_workflowSignal: workflowSignal
|
|
3387
|
+
});
|
|
3388
|
+
} finally {
|
|
3389
|
+
if (workflowSignal) {
|
|
3390
|
+
workflowSignal.removeEventListener("abort", abortHandler);
|
|
3391
|
+
}
|
|
3392
|
+
}
|
|
3393
|
+
if (!result.ok && compensations.length > 0) {
|
|
3394
|
+
const compensationErrors = [];
|
|
3395
|
+
for (let i = compensations.length - 1; i >= 0; i--) {
|
|
3396
|
+
const comp = compensations[i];
|
|
3397
|
+
try {
|
|
3398
|
+
await comp.compensate(comp.value);
|
|
3399
|
+
} catch (compErr) {
|
|
3400
|
+
compensationErrors.push({ stepName: comp.stepName, error: compErr });
|
|
3401
|
+
}
|
|
3402
|
+
}
|
|
3403
|
+
if (compensationErrors.length > 0) {
|
|
3404
|
+
const sagaError = {
|
|
3405
|
+
type: "SAGA_COMPENSATION_ERROR",
|
|
3406
|
+
originalError: result.error,
|
|
3407
|
+
compensationErrors
|
|
3408
|
+
};
|
|
3409
|
+
result = err(sagaError, { cause: result.cause });
|
|
3410
|
+
}
|
|
3411
|
+
}
|
|
3412
|
+
const durationMs = performance.now() - startTime;
|
|
3413
|
+
if (!result.ok) {
|
|
3414
|
+
let cancelledError;
|
|
3415
|
+
if (isWorkflowCancelled(result.cause)) {
|
|
3416
|
+
cancelledError = result.cause;
|
|
3417
|
+
}
|
|
3418
|
+
if (!cancelledError && abortedDuringExecution && isUnexpectedError(result.error)) {
|
|
3419
|
+
const thrown = result.cause;
|
|
3420
|
+
const isAbortError = thrown != null && typeof thrown === "object" && "name" in thrown && thrown.name === "AbortError";
|
|
3421
|
+
if (isAbortError) {
|
|
3422
|
+
const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
|
|
3423
|
+
cancelledError = {
|
|
3424
|
+
type: "WORKFLOW_CANCELLED",
|
|
3425
|
+
reason,
|
|
3426
|
+
lastStepKey
|
|
3427
|
+
};
|
|
3428
|
+
}
|
|
3429
|
+
}
|
|
3430
|
+
if (cancelledError) {
|
|
3431
|
+
emitEvent({
|
|
3432
|
+
type: "workflow_cancelled",
|
|
3433
|
+
workflowId,
|
|
3434
|
+
ts: Date.now(),
|
|
3435
|
+
durationMs,
|
|
3436
|
+
reason: cancelledError.reason,
|
|
3437
|
+
lastStepKey: cancelledError.lastStepKey
|
|
3438
|
+
});
|
|
3439
|
+
if (cancelledError && !isWorkflowCancelled(result.cause)) {
|
|
3440
|
+
return err(result.error, { cause: cancelledError });
|
|
3441
|
+
}
|
|
3442
|
+
return result;
|
|
3443
|
+
}
|
|
3444
|
+
}
|
|
3445
|
+
if (result.ok && abortedDuringExecution) {
|
|
3446
|
+
const reason = abortReason ?? (typeof workflowSignal?.reason === "string" ? workflowSignal.reason : workflowSignal?.reason instanceof Error ? workflowSignal.reason.message : void 0);
|
|
3447
|
+
emitEvent({
|
|
3448
|
+
type: "workflow_cancelled",
|
|
3449
|
+
workflowId,
|
|
3450
|
+
ts: Date.now(),
|
|
3451
|
+
durationMs,
|
|
3452
|
+
reason,
|
|
3453
|
+
lastStepKey
|
|
3454
|
+
});
|
|
3455
|
+
const cancelledError = {
|
|
3456
|
+
type: "WORKFLOW_CANCELLED",
|
|
3457
|
+
reason,
|
|
3458
|
+
lastStepKey
|
|
3459
|
+
};
|
|
3460
|
+
return err(catchUnexpected(cancelledError), { cause: cancelledError });
|
|
3461
|
+
}
|
|
3462
|
+
if (result.ok) {
|
|
3463
|
+
emitEvent({
|
|
3464
|
+
type: "workflow_success",
|
|
3465
|
+
workflowId,
|
|
3466
|
+
ts: Date.now(),
|
|
3467
|
+
durationMs
|
|
3468
|
+
});
|
|
3469
|
+
} else {
|
|
3470
|
+
emitEvent({
|
|
3471
|
+
type: "workflow_error",
|
|
3472
|
+
workflowId,
|
|
3473
|
+
ts: Date.now(),
|
|
3474
|
+
durationMs,
|
|
3475
|
+
error: result.error
|
|
3476
|
+
});
|
|
3477
|
+
}
|
|
3478
|
+
return result;
|
|
3479
|
+
}
|
|
3480
|
+
function runMethod(fnOrName, maybeFnOrConfig, maybeConfig) {
|
|
3481
|
+
let runName;
|
|
3482
|
+
let fn;
|
|
3483
|
+
let config;
|
|
3484
|
+
if (typeof fnOrName === "string") {
|
|
3485
|
+
runName = fnOrName;
|
|
3486
|
+
fn = maybeFnOrConfig;
|
|
3487
|
+
config = maybeConfig;
|
|
3488
|
+
} else {
|
|
3489
|
+
fn = fnOrName;
|
|
3490
|
+
config = maybeFnOrConfig;
|
|
3491
|
+
}
|
|
3492
|
+
return internalExecute(runName, fn, config);
|
|
3493
|
+
}
|
|
3494
|
+
async function runWithStateMethod(fnOrName, maybeFnOrConfig, maybeConfig) {
|
|
3495
|
+
let runName;
|
|
3496
|
+
let fn;
|
|
3497
|
+
let config;
|
|
3498
|
+
if (typeof fnOrName === "string") {
|
|
3499
|
+
runName = fnOrName;
|
|
3500
|
+
fn = maybeFnOrConfig;
|
|
3501
|
+
config = maybeConfig;
|
|
3502
|
+
} else {
|
|
3503
|
+
fn = fnOrName;
|
|
3504
|
+
config = maybeFnOrConfig;
|
|
3505
|
+
}
|
|
3506
|
+
const collector = createResumeStateCollector();
|
|
3507
|
+
const userOnEvent = config?.onEvent;
|
|
3508
|
+
const mergedOnEvent = (event, ctx) => {
|
|
3509
|
+
collector.handleEvent(event);
|
|
3510
|
+
try {
|
|
3511
|
+
userOnEvent?.(event, ctx);
|
|
3512
|
+
} catch {
|
|
3513
|
+
}
|
|
3514
|
+
};
|
|
3515
|
+
const mergedConfig = {
|
|
3516
|
+
...config,
|
|
3517
|
+
onEvent: mergedOnEvent
|
|
3518
|
+
};
|
|
3519
|
+
let result;
|
|
3520
|
+
let resumeState;
|
|
3521
|
+
try {
|
|
3522
|
+
result = await internalExecute(runName, fn, mergedConfig);
|
|
3523
|
+
} catch (thrown) {
|
|
3524
|
+
const catchUnexpected = optionsActual?.catchUnexpected ?? defaultCatchUnexpected;
|
|
3525
|
+
result = err(catchUnexpected(thrown), { cause: thrown });
|
|
3526
|
+
} finally {
|
|
3527
|
+
resumeState = collector.getResumeState();
|
|
3528
|
+
}
|
|
3529
|
+
return { result, resumeState };
|
|
3530
|
+
}
|
|
3531
|
+
const workflow = {
|
|
3532
|
+
withDeps: (overrides) => withDeps(workflow, overrides),
|
|
3533
|
+
run: runMethod,
|
|
3534
|
+
runWithState: runWithStateMethod
|
|
3535
|
+
};
|
|
3536
|
+
return workflow;
|
|
3537
|
+
}
|
|
3538
|
+
|
|
3539
|
+
// src/testing/test-runner.ts
|
|
3540
|
+
async function testWorkflow(deps, fn, options) {
|
|
3541
|
+
const events = [];
|
|
3542
|
+
const steps = {};
|
|
3543
|
+
const stepOrder = [];
|
|
3544
|
+
const onEvent = (event) => {
|
|
3545
|
+
events.push(event);
|
|
3546
|
+
if (event.type === "step_complete" && event.stepKey) {
|
|
3547
|
+
const stepResult = {
|
|
3548
|
+
output: event.result.ok ? event.result.value : void 0,
|
|
3549
|
+
durationMs: event.durationMs,
|
|
3550
|
+
result: event.result
|
|
3551
|
+
};
|
|
3552
|
+
steps[event.stepKey] = stepResult;
|
|
3553
|
+
stepOrder.push(event.stepKey);
|
|
3554
|
+
}
|
|
3555
|
+
};
|
|
3556
|
+
const workflow = createWorkflow("test-workflow", deps);
|
|
3557
|
+
const start = performance.now();
|
|
3558
|
+
const result = await workflow.run(fn, {
|
|
3559
|
+
onEvent,
|
|
3560
|
+
signal: options?.signal
|
|
3561
|
+
});
|
|
3562
|
+
const durationMs = performance.now() - start;
|
|
3563
|
+
return {
|
|
3564
|
+
result,
|
|
3565
|
+
steps,
|
|
3566
|
+
events,
|
|
3567
|
+
durationMs,
|
|
3568
|
+
stepOrder
|
|
3569
|
+
};
|
|
3570
|
+
}
|
|
3571
|
+
|
|
3572
|
+
// src/testing/index.ts
|
|
3573
|
+
function isTestEarlyExit(e) {
|
|
3574
|
+
return typeof e === "object" && e !== null && "__earlyExit" in e && e.__earlyExit === true;
|
|
3575
|
+
}
|
|
3576
|
+
function createWorkflowHarness(deps, options = {}) {
|
|
3577
|
+
const { recordInvocations = true, clock = Date.now } = options;
|
|
3578
|
+
let scriptedOutcomes = [];
|
|
3579
|
+
const namedOutcomes = /* @__PURE__ */ new Map();
|
|
3580
|
+
let invocationIndex = 0;
|
|
3581
|
+
let invocations = [];
|
|
3582
|
+
function script(outcomes) {
|
|
3583
|
+
scriptedOutcomes = [...outcomes];
|
|
3584
|
+
invocationIndex = 0;
|
|
3585
|
+
namedOutcomes.clear();
|
|
3586
|
+
}
|
|
3587
|
+
function scriptStep(nameOrKey, outcome) {
|
|
3588
|
+
namedOutcomes.set(nameOrKey, outcome);
|
|
3589
|
+
}
|
|
3590
|
+
function getNextOutcome(nameOrKey) {
|
|
3591
|
+
if (nameOrKey && namedOutcomes.has(nameOrKey)) {
|
|
3592
|
+
return namedOutcomes.get(nameOrKey);
|
|
3593
|
+
}
|
|
3594
|
+
if (invocationIndex < scriptedOutcomes.length) {
|
|
3595
|
+
return scriptedOutcomes[invocationIndex++];
|
|
3596
|
+
}
|
|
3597
|
+
return void 0;
|
|
3598
|
+
}
|
|
3599
|
+
function createMockStep() {
|
|
3600
|
+
const mockStep = async (nameOrOperation, operationOrOptions, maybeOptions) => {
|
|
3601
|
+
let name;
|
|
3602
|
+
let operationOrResult;
|
|
3603
|
+
let opts;
|
|
3604
|
+
if (typeof nameOrOperation === "string") {
|
|
3605
|
+
name = nameOrOperation;
|
|
3606
|
+
operationOrResult = operationOrOptions;
|
|
3607
|
+
opts = maybeOptions ?? {};
|
|
3608
|
+
} else {
|
|
3609
|
+
operationOrResult = nameOrOperation;
|
|
3610
|
+
if (typeof operationOrOptions === "string") {
|
|
3611
|
+
name = operationOrOptions;
|
|
3612
|
+
opts = {};
|
|
3613
|
+
} else {
|
|
3614
|
+
opts = operationOrOptions ?? {};
|
|
3615
|
+
name = opts.key ?? "step";
|
|
3616
|
+
}
|
|
3617
|
+
}
|
|
3618
|
+
const startTime = clock();
|
|
3619
|
+
const invocation = {
|
|
3620
|
+
name,
|
|
3621
|
+
key: opts.key,
|
|
3622
|
+
order: invocations.length,
|
|
3623
|
+
timestamp: startTime
|
|
3624
|
+
};
|
|
3625
|
+
if (recordInvocations) {
|
|
3626
|
+
invocations.push(invocation);
|
|
3627
|
+
}
|
|
3628
|
+
const outcome = getNextOutcome(name);
|
|
3629
|
+
if (outcome) {
|
|
3630
|
+
invocation.durationMs = clock() - startTime;
|
|
3631
|
+
switch (outcome.type) {
|
|
3632
|
+
case "ok":
|
|
3633
|
+
invocation.result = ok2(outcome.value);
|
|
3634
|
+
return outcome.value;
|
|
3635
|
+
case "err":
|
|
3636
|
+
invocation.result = err(outcome.error);
|
|
3637
|
+
throw { __earlyExit: true, error: outcome.error };
|
|
3638
|
+
case "throw":
|
|
3639
|
+
throw outcome.error;
|
|
3640
|
+
}
|
|
3641
|
+
}
|
|
3642
|
+
const result = typeof operationOrResult === "function" ? await operationOrResult() : await operationOrResult;
|
|
3643
|
+
invocation.durationMs = clock() - startTime;
|
|
3644
|
+
invocation.result = result;
|
|
3645
|
+
if (!result.ok) {
|
|
3646
|
+
throw { __earlyExit: true, error: result.error };
|
|
3647
|
+
}
|
|
3648
|
+
return result.value;
|
|
3649
|
+
};
|
|
3650
|
+
mockStep.try = async (nameOrOperation, operationOrOpts, maybeOpts) => {
|
|
3651
|
+
let name;
|
|
3652
|
+
let operation;
|
|
3653
|
+
let opts;
|
|
3654
|
+
if (typeof nameOrOperation === "string") {
|
|
3655
|
+
name = nameOrOperation;
|
|
3656
|
+
operation = operationOrOpts;
|
|
3657
|
+
opts = maybeOpts;
|
|
3658
|
+
} else {
|
|
3659
|
+
operation = nameOrOperation;
|
|
3660
|
+
opts = operationOrOpts;
|
|
3661
|
+
name = opts.key ?? "step";
|
|
3662
|
+
}
|
|
3663
|
+
const startTime = clock();
|
|
3664
|
+
const invocation = {
|
|
3665
|
+
name,
|
|
3666
|
+
key: "key" in opts ? opts.key : void 0,
|
|
3667
|
+
order: invocations.length,
|
|
3668
|
+
timestamp: startTime
|
|
3669
|
+
};
|
|
3670
|
+
if (recordInvocations) {
|
|
3671
|
+
invocations.push(invocation);
|
|
3672
|
+
}
|
|
3673
|
+
const outcome = getNextOutcome(name);
|
|
3674
|
+
if (outcome) {
|
|
3675
|
+
invocation.durationMs = clock() - startTime;
|
|
3676
|
+
switch (outcome.type) {
|
|
3677
|
+
case "ok":
|
|
3678
|
+
invocation.result = ok2(outcome.value);
|
|
3679
|
+
return outcome.value;
|
|
3680
|
+
case "err":
|
|
3681
|
+
invocation.result = err(outcome.error);
|
|
3682
|
+
throw { __earlyExit: true, error: outcome.error };
|
|
3683
|
+
case "throw":
|
|
3684
|
+
throw outcome.error;
|
|
3685
|
+
}
|
|
3686
|
+
}
|
|
3687
|
+
try {
|
|
3688
|
+
const value = await operation();
|
|
3689
|
+
invocation.durationMs = clock() - startTime;
|
|
3690
|
+
invocation.result = ok2(value);
|
|
3691
|
+
return value;
|
|
3692
|
+
} catch (error) {
|
|
3693
|
+
invocation.durationMs = clock() - startTime;
|
|
3694
|
+
const mappedError = "error" in opts ? opts.error : opts.onError(error);
|
|
3695
|
+
invocation.result = err(mappedError);
|
|
3696
|
+
throw { __earlyExit: true, error: mappedError };
|
|
3697
|
+
}
|
|
3698
|
+
};
|
|
3699
|
+
return mockStep;
|
|
3700
|
+
}
|
|
3701
|
+
async function run2(fn) {
|
|
3702
|
+
const mockStep = createMockStep();
|
|
3703
|
+
try {
|
|
3704
|
+
const value = await fn({ step: mockStep, deps });
|
|
3705
|
+
return ok2(value);
|
|
3706
|
+
} catch (error) {
|
|
3707
|
+
if (isTestEarlyExit(error)) {
|
|
3708
|
+
return err(error.error);
|
|
3709
|
+
}
|
|
3710
|
+
return err(new UnexpectedError({ cause: error }));
|
|
3711
|
+
}
|
|
3712
|
+
}
|
|
3713
|
+
async function runWithInput(input, fn) {
|
|
3714
|
+
const mockStep = createMockStep();
|
|
3715
|
+
try {
|
|
3716
|
+
const value = await fn({ step: mockStep, deps, input });
|
|
3717
|
+
return ok2(value);
|
|
3718
|
+
} catch (error) {
|
|
3719
|
+
if (isTestEarlyExit(error)) {
|
|
3720
|
+
return err(error.error);
|
|
3721
|
+
}
|
|
3722
|
+
return err(new UnexpectedError({ cause: error }));
|
|
3723
|
+
}
|
|
3724
|
+
}
|
|
3725
|
+
function getInvocations() {
|
|
3726
|
+
return [...invocations];
|
|
3727
|
+
}
|
|
3728
|
+
function assertSteps(expectedNames) {
|
|
3729
|
+
const actualNames = invocations.map((inv) => inv.name ?? inv.key ?? "unnamed").filter((n) => n !== "unnamed");
|
|
3730
|
+
const passed = JSON.stringify(actualNames) === JSON.stringify(expectedNames);
|
|
3731
|
+
return {
|
|
3732
|
+
passed,
|
|
3733
|
+
message: passed ? `Steps invoked in order: ${expectedNames.join(", ")}` : `Expected steps [${expectedNames.join(", ")}] but got [${actualNames.join(", ")}]`,
|
|
3734
|
+
expected: expectedNames,
|
|
3735
|
+
actual: actualNames
|
|
3736
|
+
};
|
|
3737
|
+
}
|
|
3738
|
+
function assertStepCalled(nameOrKey) {
|
|
3739
|
+
const found = invocations.some(
|
|
3740
|
+
(inv) => inv.name === nameOrKey || inv.key === nameOrKey
|
|
3741
|
+
);
|
|
3742
|
+
return {
|
|
3743
|
+
passed: found,
|
|
3744
|
+
message: found ? `Step "${nameOrKey}" was invoked` : `Step "${nameOrKey}" was NOT invoked`,
|
|
3745
|
+
expected: nameOrKey,
|
|
3746
|
+
actual: found
|
|
3747
|
+
};
|
|
3748
|
+
}
|
|
3749
|
+
function assertStepNotCalled(nameOrKey) {
|
|
3750
|
+
const found = invocations.some(
|
|
3751
|
+
(inv) => inv.name === nameOrKey || inv.key === nameOrKey
|
|
3752
|
+
);
|
|
3753
|
+
return {
|
|
3754
|
+
passed: !found,
|
|
3755
|
+
message: !found ? `Step "${nameOrKey}" was correctly NOT invoked` : `Step "${nameOrKey}" was invoked but should not have been`,
|
|
3756
|
+
expected: "not called",
|
|
3757
|
+
actual: found ? "called" : "not called"
|
|
3758
|
+
};
|
|
3759
|
+
}
|
|
3760
|
+
function assertResult(result, expected) {
|
|
3761
|
+
const passed = result.ok === expected.ok && (result.ok ? JSON.stringify(result.value) === JSON.stringify(expected.value) : JSON.stringify(result.error) === JSON.stringify(expected.error));
|
|
3762
|
+
return {
|
|
3763
|
+
passed,
|
|
3764
|
+
message: passed ? `Result matches expected` : `Result does not match expected`,
|
|
3765
|
+
expected,
|
|
3766
|
+
actual: result
|
|
3767
|
+
};
|
|
3768
|
+
}
|
|
3769
|
+
function reset() {
|
|
3770
|
+
scriptedOutcomes = [];
|
|
3771
|
+
namedOutcomes.clear();
|
|
3772
|
+
invocationIndex = 0;
|
|
3773
|
+
invocations = [];
|
|
3774
|
+
}
|
|
3775
|
+
return {
|
|
3776
|
+
script,
|
|
3777
|
+
scriptStep,
|
|
3778
|
+
run: run2,
|
|
3779
|
+
runWithInput,
|
|
3780
|
+
getInvocations,
|
|
3781
|
+
assertSteps,
|
|
3782
|
+
assertStepCalled,
|
|
3783
|
+
assertStepNotCalled,
|
|
3784
|
+
assertResult,
|
|
3785
|
+
reset
|
|
3786
|
+
};
|
|
3787
|
+
}
|
|
3788
|
+
function createMockFn() {
|
|
3789
|
+
let defaultReturn;
|
|
3790
|
+
const returnQueue = [];
|
|
3791
|
+
const calls = [];
|
|
3792
|
+
const fn = ((...args) => {
|
|
3793
|
+
calls.push(args);
|
|
3794
|
+
if (returnQueue.length > 0) {
|
|
3795
|
+
return Promise.resolve(returnQueue.shift());
|
|
3796
|
+
}
|
|
3797
|
+
if (defaultReturn) {
|
|
3798
|
+
return Promise.resolve(defaultReturn);
|
|
3799
|
+
}
|
|
3800
|
+
throw new Error("Mock function called without configured return value");
|
|
3801
|
+
});
|
|
3802
|
+
fn.returns = (result) => {
|
|
3803
|
+
defaultReturn = result;
|
|
3804
|
+
return fn;
|
|
3805
|
+
};
|
|
3806
|
+
fn.returnsOnce = (result) => {
|
|
3807
|
+
returnQueue.push(result);
|
|
3808
|
+
return fn;
|
|
3809
|
+
};
|
|
3810
|
+
fn.getCalls = () => [...calls];
|
|
3811
|
+
fn.getCallCount = () => calls.length;
|
|
3812
|
+
fn.reset = () => {
|
|
3813
|
+
defaultReturn = void 0;
|
|
3814
|
+
returnQueue.length = 0;
|
|
3815
|
+
calls.length = 0;
|
|
3816
|
+
};
|
|
3817
|
+
return fn;
|
|
3818
|
+
}
|
|
3819
|
+
function createSnapshot(invocations, result, events) {
|
|
3820
|
+
const totalDuration = invocations.reduce(
|
|
3821
|
+
(sum, inv) => sum + (inv.durationMs ?? 0),
|
|
3822
|
+
0
|
|
3823
|
+
);
|
|
3824
|
+
return {
|
|
3825
|
+
invocations: invocations.map((inv) => ({
|
|
3826
|
+
...inv,
|
|
3827
|
+
// Normalize timestamps for comparison
|
|
3828
|
+
timestamp: 0
|
|
3829
|
+
})),
|
|
3830
|
+
result,
|
|
3831
|
+
events: events?.map((e) => ({
|
|
3832
|
+
...e,
|
|
3833
|
+
ts: 0
|
|
3834
|
+
// Normalize timestamps
|
|
3835
|
+
})),
|
|
3836
|
+
durationMs: totalDuration
|
|
3837
|
+
};
|
|
3838
|
+
}
|
|
3839
|
+
function compareSnapshots(snapshot1, snapshot2) {
|
|
3840
|
+
const differences = [];
|
|
3841
|
+
if (snapshot1.invocations.length !== snapshot2.invocations.length) {
|
|
3842
|
+
differences.push(
|
|
3843
|
+
`Invocation count: ${snapshot1.invocations.length} vs ${snapshot2.invocations.length}`
|
|
3844
|
+
);
|
|
3845
|
+
}
|
|
3846
|
+
const maxLen = Math.max(
|
|
3847
|
+
snapshot1.invocations.length,
|
|
3848
|
+
snapshot2.invocations.length
|
|
3849
|
+
);
|
|
3850
|
+
for (let i = 0; i < maxLen; i++) {
|
|
3851
|
+
const inv1 = snapshot1.invocations[i];
|
|
3852
|
+
const inv2 = snapshot2.invocations[i];
|
|
3853
|
+
if (!inv1) {
|
|
3854
|
+
differences.push(`Step ${i}: missing in first snapshot`);
|
|
3855
|
+
continue;
|
|
3856
|
+
}
|
|
3857
|
+
if (!inv2) {
|
|
3858
|
+
differences.push(`Step ${i}: missing in second snapshot`);
|
|
3859
|
+
continue;
|
|
3860
|
+
}
|
|
3861
|
+
if (inv1.name !== inv2.name) {
|
|
3862
|
+
differences.push(`Step ${i} name: "${inv1.name}" vs "${inv2.name}"`);
|
|
3863
|
+
}
|
|
3864
|
+
if (inv1.key !== inv2.key) {
|
|
3865
|
+
differences.push(`Step ${i} key: "${inv1.key}" vs "${inv2.key}"`);
|
|
3866
|
+
}
|
|
3867
|
+
if (inv1.result?.ok !== inv2.result?.ok) {
|
|
3868
|
+
differences.push(
|
|
3869
|
+
`Step ${i} result: ${inv1.result?.ok ? "ok" : "err"} vs ${inv2.result?.ok ? "ok" : "err"}`
|
|
3870
|
+
);
|
|
3871
|
+
}
|
|
3872
|
+
}
|
|
3873
|
+
if (snapshot1.result.ok !== snapshot2.result.ok) {
|
|
3874
|
+
differences.push(
|
|
3875
|
+
`Final result: ${snapshot1.result.ok ? "ok" : "err"} vs ${snapshot2.result.ok ? "ok" : "err"}`
|
|
3876
|
+
);
|
|
3877
|
+
}
|
|
3878
|
+
return {
|
|
3879
|
+
equal: differences.length === 0,
|
|
3880
|
+
differences
|
|
3881
|
+
};
|
|
3882
|
+
}
|
|
3883
|
+
function createTestClock(startTime = 0) {
|
|
3884
|
+
let currentTime = startTime;
|
|
3885
|
+
return {
|
|
3886
|
+
now: () => currentTime,
|
|
3887
|
+
advance: (ms) => {
|
|
3888
|
+
currentTime += ms;
|
|
3889
|
+
},
|
|
3890
|
+
set: (time) => {
|
|
3891
|
+
currentTime = time;
|
|
3892
|
+
},
|
|
3893
|
+
reset: () => {
|
|
3894
|
+
currentTime = startTime;
|
|
3895
|
+
}
|
|
3896
|
+
};
|
|
3897
|
+
}
|
|
3898
|
+
function okOutcome(value) {
|
|
3899
|
+
return { type: "ok", value };
|
|
3900
|
+
}
|
|
3901
|
+
function errOutcome(error) {
|
|
3902
|
+
return { type: "err", error };
|
|
3903
|
+
}
|
|
3904
|
+
function throwOutcome(error) {
|
|
3905
|
+
return { type: "throw", error };
|
|
3906
|
+
}
|
|
3907
|
+
function createSagaHarness(deps, options = {}) {
|
|
3908
|
+
const { clock = Date.now } = options;
|
|
3909
|
+
const baseHarness = createWorkflowHarness(deps, options);
|
|
3910
|
+
let compensations = [];
|
|
3911
|
+
let compensationStack = [];
|
|
3912
|
+
async function runSaga(fn) {
|
|
3913
|
+
compensations = [];
|
|
3914
|
+
compensationStack = [];
|
|
3915
|
+
const sagaContext = {
|
|
3916
|
+
step: async (operation, stepOptions) => {
|
|
3917
|
+
try {
|
|
3918
|
+
const result = await baseHarness.run(
|
|
3919
|
+
async ({ step }) => step("saga-step", operation)
|
|
3920
|
+
);
|
|
3921
|
+
if (!result.ok) {
|
|
3922
|
+
await runCompensations();
|
|
3923
|
+
throw { __earlyExit: true, error: result.error };
|
|
3924
|
+
}
|
|
3925
|
+
if (stepOptions?.compensate) {
|
|
3926
|
+
compensationStack.push({
|
|
3927
|
+
value: result.value,
|
|
3928
|
+
compensate: stepOptions.compensate
|
|
3929
|
+
});
|
|
3930
|
+
}
|
|
3931
|
+
return result.value;
|
|
3932
|
+
} catch (error) {
|
|
3933
|
+
if (compensationStack.length > 0) {
|
|
3934
|
+
await runCompensations();
|
|
3935
|
+
}
|
|
3936
|
+
throw error;
|
|
3937
|
+
}
|
|
3938
|
+
}
|
|
3939
|
+
};
|
|
3940
|
+
async function runCompensations() {
|
|
3941
|
+
const toCompensate = [...compensationStack].reverse();
|
|
3942
|
+
compensationStack = [];
|
|
3943
|
+
for (const { name, value, compensate } of toCompensate) {
|
|
3944
|
+
try {
|
|
3945
|
+
await compensate(value);
|
|
3946
|
+
compensations.push({
|
|
3947
|
+
stepName: name,
|
|
3948
|
+
order: compensations.length,
|
|
3949
|
+
value,
|
|
3950
|
+
timestamp: clock()
|
|
3951
|
+
});
|
|
3952
|
+
} catch (error) {
|
|
3953
|
+
console.error(`Compensation failed for step "${name}":`, error);
|
|
3954
|
+
}
|
|
3955
|
+
}
|
|
3956
|
+
}
|
|
3957
|
+
try {
|
|
3958
|
+
const value = await fn({ saga: sagaContext, deps });
|
|
3959
|
+
return ok2(value);
|
|
3960
|
+
} catch (error) {
|
|
3961
|
+
if (isTestEarlyExit(error)) {
|
|
3962
|
+
return err(error.error);
|
|
3963
|
+
}
|
|
3964
|
+
await runCompensations();
|
|
3965
|
+
return err(new UnexpectedError({ cause: error }));
|
|
3966
|
+
}
|
|
3967
|
+
}
|
|
3968
|
+
function getCompensations() {
|
|
3969
|
+
return [...compensations];
|
|
3970
|
+
}
|
|
3971
|
+
function assertCompensationOrder(expectedStepNames) {
|
|
3972
|
+
const actualNames = compensations.map((c) => c.stepName);
|
|
3973
|
+
const passed = JSON.stringify(actualNames) === JSON.stringify(expectedStepNames);
|
|
3974
|
+
return {
|
|
3975
|
+
passed,
|
|
3976
|
+
message: passed ? `Compensations ran in order: ${expectedStepNames.join(" \u2192 ")}` : `Expected compensations [${expectedStepNames.join(" \u2192 ")}] but got [${actualNames.join(" \u2192 ")}]`,
|
|
3977
|
+
expected: expectedStepNames,
|
|
3978
|
+
actual: actualNames
|
|
3979
|
+
};
|
|
3980
|
+
}
|
|
3981
|
+
function assertCompensated(stepName) {
|
|
3982
|
+
const found = compensations.some((c) => c.stepName === stepName);
|
|
3983
|
+
return {
|
|
3984
|
+
passed: found,
|
|
3985
|
+
message: found ? `Step "${stepName}" was compensated` : `Step "${stepName}" was NOT compensated`,
|
|
3986
|
+
expected: stepName,
|
|
3987
|
+
actual: found
|
|
3988
|
+
};
|
|
3989
|
+
}
|
|
3990
|
+
function assertNotCompensated(stepName) {
|
|
3991
|
+
const found = compensations.some((c) => c.stepName === stepName);
|
|
3992
|
+
return {
|
|
3993
|
+
passed: !found,
|
|
3994
|
+
message: !found ? `Step "${stepName}" was correctly NOT compensated` : `Step "${stepName}" was compensated but should not have been`,
|
|
3995
|
+
expected: "not compensated",
|
|
3996
|
+
actual: found ? "compensated" : "not compensated"
|
|
3997
|
+
};
|
|
3998
|
+
}
|
|
3999
|
+
const originalReset = baseHarness.reset;
|
|
4000
|
+
function reset() {
|
|
4001
|
+
originalReset();
|
|
4002
|
+
compensations = [];
|
|
4003
|
+
compensationStack = [];
|
|
4004
|
+
}
|
|
4005
|
+
return {
|
|
4006
|
+
...baseHarness,
|
|
4007
|
+
reset,
|
|
4008
|
+
getCompensations,
|
|
4009
|
+
assertCompensationOrder,
|
|
4010
|
+
assertCompensated,
|
|
4011
|
+
assertNotCompensated,
|
|
4012
|
+
runSaga
|
|
4013
|
+
};
|
|
4014
|
+
}
|
|
4015
|
+
function assertEventSequence(events, expectedSequence, options = {}) {
|
|
4016
|
+
const { strict = true } = options;
|
|
4017
|
+
const expected = expectedSequence.map((s) => {
|
|
4018
|
+
const [type, name] = s.split(":");
|
|
4019
|
+
return { type, name };
|
|
4020
|
+
});
|
|
4021
|
+
const relevantEvents = strict ? events : events.filter((e) => expected.some((exp) => e.type === exp.type));
|
|
4022
|
+
const actual = relevantEvents.map((e) => {
|
|
4023
|
+
const name = "name" in e ? e.name : void 0;
|
|
4024
|
+
const stepKey = "stepKey" in e ? e.stepKey : void 0;
|
|
4025
|
+
const identifier = name ?? stepKey;
|
|
4026
|
+
return identifier ? `${e.type}:${identifier}` : e.type;
|
|
4027
|
+
});
|
|
4028
|
+
const passed = JSON.stringify(actual) === JSON.stringify(expectedSequence);
|
|
4029
|
+
return {
|
|
4030
|
+
passed,
|
|
4031
|
+
message: passed ? `Event sequence matches: ${expectedSequence.join(" \u2192 ")}` : `Event sequence mismatch.
|
|
4032
|
+
Expected: ${expectedSequence.join(" \u2192 ")}
|
|
4033
|
+
Actual: ${actual.join(" \u2192 ")}`,
|
|
4034
|
+
expected: expectedSequence,
|
|
4035
|
+
actual
|
|
4036
|
+
};
|
|
4037
|
+
}
|
|
4038
|
+
function assertEventEmitted(events, expected) {
|
|
4039
|
+
const found = events.find((e) => {
|
|
4040
|
+
return Object.entries(expected).every(([key, value]) => {
|
|
4041
|
+
const eventValue = e[key];
|
|
4042
|
+
if (typeof value === "object" && value !== null) {
|
|
4043
|
+
return JSON.stringify(eventValue) === JSON.stringify(value);
|
|
4044
|
+
}
|
|
4045
|
+
return eventValue === value;
|
|
4046
|
+
});
|
|
4047
|
+
});
|
|
4048
|
+
return {
|
|
4049
|
+
passed: !!found,
|
|
4050
|
+
message: found ? `Event matching ${JSON.stringify(expected)} was emitted` : `No event matching ${JSON.stringify(expected)} was found`,
|
|
4051
|
+
expected,
|
|
4052
|
+
actual: found ?? "not found"
|
|
4053
|
+
};
|
|
4054
|
+
}
|
|
4055
|
+
function assertEventNotEmitted(events, expected) {
|
|
4056
|
+
const result = assertEventEmitted(events, expected);
|
|
4057
|
+
return {
|
|
4058
|
+
passed: !result.passed,
|
|
4059
|
+
message: result.passed ? `Event matching ${JSON.stringify(expected)} was found but should not have been` : `Correctly, no event matching ${JSON.stringify(expected)} was emitted`,
|
|
4060
|
+
expected: "not emitted",
|
|
4061
|
+
actual: result.actual
|
|
4062
|
+
};
|
|
4063
|
+
}
|
|
4064
|
+
function expectOk(result) {
|
|
4065
|
+
if (!result.ok) {
|
|
4066
|
+
throw new Error(
|
|
4067
|
+
`Expected Ok result, got Err: ${JSON.stringify(result.error, null, 2)}`
|
|
4068
|
+
);
|
|
4069
|
+
}
|
|
4070
|
+
}
|
|
4071
|
+
function expectErr(result) {
|
|
4072
|
+
if (result.ok) {
|
|
4073
|
+
throw new Error(
|
|
4074
|
+
`Expected Err result, got Ok: ${JSON.stringify(result.value, null, 2)}`
|
|
4075
|
+
);
|
|
4076
|
+
}
|
|
4077
|
+
}
|
|
4078
|
+
function unwrapOk(result) {
|
|
4079
|
+
expectOk(result);
|
|
4080
|
+
return result.value;
|
|
4081
|
+
}
|
|
4082
|
+
function unwrapErr(result) {
|
|
4083
|
+
expectErr(result);
|
|
4084
|
+
return result.error;
|
|
4085
|
+
}
|
|
4086
|
+
async function unwrapOkAsync(result) {
|
|
4087
|
+
return unwrapOk(await result);
|
|
4088
|
+
}
|
|
4089
|
+
async function unwrapErrAsync(result) {
|
|
4090
|
+
return unwrapErr(await result);
|
|
4091
|
+
}
|
|
4092
|
+
function formatResult(result) {
|
|
4093
|
+
if (isOk(result)) {
|
|
4094
|
+
return `Ok(${formatValue(result.value)})`;
|
|
4095
|
+
}
|
|
4096
|
+
return `Err(${formatValue(result.error)})`;
|
|
4097
|
+
}
|
|
4098
|
+
function formatValue(value) {
|
|
4099
|
+
if (value === null) return "null";
|
|
4100
|
+
if (value === void 0) return "undefined";
|
|
4101
|
+
if (typeof value === "string") return `'${value}'`;
|
|
4102
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
4103
|
+
if (typeof value === "function") return `[Function: ${value.name || "anonymous"}]`;
|
|
4104
|
+
if (Array.isArray(value)) {
|
|
4105
|
+
if (value.length === 0) return "[]";
|
|
4106
|
+
if (value.length <= 3) return `[${value.map(formatValue).join(", ")}]`;
|
|
4107
|
+
return `[${value.slice(0, 3).map(formatValue).join(", ")}, ... (${value.length} items)]`;
|
|
4108
|
+
}
|
|
4109
|
+
if (typeof value === "object") {
|
|
4110
|
+
const obj = value;
|
|
4111
|
+
const keys = Object.keys(obj);
|
|
4112
|
+
if (keys.length === 0) return "{}";
|
|
4113
|
+
if (keys.length <= 4) {
|
|
4114
|
+
const entries = keys.map((k) => `${k}: ${formatValue(obj[k])}`).join(", ");
|
|
4115
|
+
return `{ ${entries} }`;
|
|
4116
|
+
}
|
|
4117
|
+
const sample = keys.slice(0, 3).map((k) => `${k}: ${formatValue(obj[k])}`).join(", ");
|
|
4118
|
+
return `{ ${sample}, ... (${keys.length} keys) }`;
|
|
4119
|
+
}
|
|
4120
|
+
return String(value);
|
|
4121
|
+
}
|
|
4122
|
+
function formatEvent(event) {
|
|
4123
|
+
const type = event.type;
|
|
4124
|
+
const name = "name" in event ? event.name : void 0;
|
|
4125
|
+
const stepKey = "stepKey" in event ? event.stepKey : void 0;
|
|
4126
|
+
const identifier = name ?? stepKey;
|
|
4127
|
+
if (identifier) {
|
|
4128
|
+
return `${type}:${identifier}`;
|
|
4129
|
+
}
|
|
4130
|
+
return type;
|
|
4131
|
+
}
|
|
4132
|
+
function formatEvents(events) {
|
|
4133
|
+
return events.map(formatEvent).join(" \u2192 ");
|
|
4134
|
+
}
|
|
4135
|
+
export {
|
|
4136
|
+
assertEventEmitted,
|
|
4137
|
+
assertEventNotEmitted,
|
|
4138
|
+
assertEventSequence,
|
|
4139
|
+
compareSnapshots,
|
|
4140
|
+
createMockFn,
|
|
4141
|
+
createSagaHarness,
|
|
4142
|
+
createSnapshot,
|
|
4143
|
+
createTestClock,
|
|
4144
|
+
createWorkflowHarness,
|
|
4145
|
+
errOutcome,
|
|
4146
|
+
expectErr,
|
|
4147
|
+
expectOk,
|
|
4148
|
+
formatEvent,
|
|
4149
|
+
formatEvents,
|
|
4150
|
+
formatResult,
|
|
4151
|
+
okOutcome,
|
|
4152
|
+
testWorkflow,
|
|
4153
|
+
throwOutcome,
|
|
4154
|
+
unwrapErr,
|
|
4155
|
+
unwrapErrAsync,
|
|
4156
|
+
unwrapOk,
|
|
4157
|
+
unwrapOkAsync
|
|
4158
|
+
};
|
|
13
4159
|
//# sourceMappingURL=testing.js.map
|