The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** |
| 2 | * The `Sfn.*` combinators — Effect-mirroring constructors over the ASL AST. |
| 3 | * |
| 4 | * Names and semantics track their `Effect` counterparts as closely as the |
| 5 | * target language allows: `Sfn.gen`, `Sfn.retry`, `Sfn.catchTag`, |
| 6 | * `Sfn.catchAll`, `Sfn.all`, `Sfn.forEach`, `Sfn.sleep`, `Sfn.when`, |
| 7 | * `Sfn.match`, `Sfn.succeed`, `Sfn.fail`. Divergences are deliberate: |
| 8 | * `retry` takes an option bag mirroring the `Schedule.exponential` |
| 9 | * vocabulary (a real `Schedule` is opaque and cannot be introspected into |
| 10 | * ASL's `BackoffRate`), and branching goes through `when`/`match` because a |
| 11 | * compiled program cannot branch on runtime JS. |
| 12 | */ |
| 13 | import * as Duration from "effect/Duration"; |
| 14 | import type { Expr, UnwrapExpr } from "./Jsonata.ts"; |
| 15 | import type { |
| 16 | ErrorOutput, |
| 17 | ForEachOptions, |
| 18 | IntegrationOptions, |
| 19 | InvokableFunction, |
| 20 | RetryOptions, |
| 21 | } from "./Node.ts"; |
| 22 | import { |
| 23 | isSfnEffect as isSfn, |
| 24 | make, |
| 25 | type Error as ErrorOf, |
| 26 | type SfnEffect, |
| 27 | type Success, |
| 28 | } from "./Program.ts"; |
| 29 | |
| 30 | /** |
| 31 | * Invoke a Lambda function as a Task state |
| 32 | * (`arn:aws:states:::lambda:invoke`). The payload may embed typed `Expr` |
| 33 | * references and resource `Output`s; the result reference is the function's |
| 34 | * response payload. |
| 35 | * |
| 36 | * Compiling the program emits the `lambda:InvokeFunction` policy statement |
| 37 | * for the function's exact ARN (and its qualified variants) into the |
| 38 | * collected `policyStatements`. |
| 39 | */ |
| 40 | export const invoke = <A = unknown, E = never>( |
| 41 | fn: InvokableFunction, |
| 42 | payload?: unknown, |
| 43 | ): SfnEffect<A, E> => make({ kind: "invoke", fn, payload }); |
| 44 | |
| 45 | /** |
| 46 | * Call an optimized service integration as a Task state, e.g. |
| 47 | * `arn:aws:states:::sqs:sendMessage`. Provide the exact-ARN policy |
| 48 | * statements the execution role needs. |
| 49 | */ |
| 50 | export const integrate = <A = unknown, E = never>(options: IntegrationOptions): SfnEffect<A, E> => |
| 51 | make({ kind: "integrate", options, waitForTaskToken: false }); |
| 52 | |
| 53 | /** |
| 54 | * Call a service integration with the `.waitForTaskToken` callback pattern: |
| 55 | * the state parks until `SendTaskSuccess`/`SendTaskFailure` is called with |
| 56 | * the token. Embed {@link taskToken} (re-exported as `Sfn.taskToken`) in the |
| 57 | * arguments to hand the token to the callback side; the result is the JSON |
| 58 | * given to `SendTaskSuccess`. |
| 59 | */ |
| 60 | export const waitForTaskToken = <A = unknown, E = never>( |
| 61 | options: IntegrationOptions, |
| 62 | ): SfnEffect<A, E> => make({ kind: "integrate", options, waitForTaskToken: true }); |
| 63 | |
| 64 | /** |
| 65 | * Run programs in parallel (an ASL `Parallel` state) — mirrors |
| 66 | * `Effect.all`. The result is the tuple of branch results. |
| 67 | */ |
| 68 | export const all = <const T extends readonly SfnEffect<any, any>[]>( |
| 69 | branches: T, |
| 70 | ): SfnEffect<{ [K in keyof T]: Success<T[K]> }, ErrorOf<T[number]>> => |
| 71 | make({ kind: "all", branches }); |
| 72 | |
| 73 | /** |
| 74 | * Apply `body` to every element of `items` (an ASL inline `Map` state) — |
| 75 | * mirrors `Effect.forEach`, including the `concurrency` option |
| 76 | * (`MaxConcurrency`). The result is the array of iteration results. |
| 77 | */ |
| 78 | export const forEach = <Item, A, E>( |
| 79 | items: Expr<readonly Item[]> | Expr<Item[]>, |
| 80 | body: (item: Expr<Item>) => SfnEffect<A, E>, |
| 81 | options?: ForEachOptions, |
| 82 | ): SfnEffect<A[], E> => |
| 83 | make({ |
| 84 | kind: "forEach", |
| 85 | items: items as Expr<any>, |
| 86 | body: body as (item: Expr<any>) => SfnEffect<any, any>, |
| 87 | options: options ?? {}, |
| 88 | }); |
| 89 | |
| 90 | /** |
| 91 | * Pause the workflow (an ASL `Wait` state) — mirrors `Effect.sleep`. |
| 92 | * Durations round up to whole seconds (ASL's granularity). |
| 93 | */ |
| 94 | export const sleep = (duration: Duration.Input): SfnEffect<void> => |
| 95 | make({ |
| 96 | kind: "sleep", |
| 97 | seconds: Math.max(1, Math.ceil(Duration.toSeconds(duration))), |
| 98 | }); |
| 99 | |
| 100 | /** |
| 101 | * Branch on a typed condition (an ASL `Choice` state) — mirrors |
| 102 | * `Effect.if`. Build conditions with the typed comparators (`Sfn.eq`, |
| 103 | * `Sfn.gt`, `Sfn.and`, …). When `onFalse` is omitted the false branch |
| 104 | * produces `null`. |
| 105 | */ |
| 106 | export const when = <A, E, B = null, E2 = never>( |
| 107 | condition: Expr<boolean>, |
| 108 | onTrue: SfnEffect<A, E>, |
| 109 | onFalse?: SfnEffect<B, E2>, |
| 110 | ): SfnEffect<A | B, E | E2> => make({ kind: "when", condition, onTrue, onFalse }); |
| 111 | |
| 112 | /** |
| 113 | * Branch on a value's literal cases (an ASL `Choice` state with one rule |
| 114 | * per case) — mirrors `Effect.match`-style dispatch. With no `otherwise` |
| 115 | * and no matching case the execution fails with `States.NoChoiceMatched`. |
| 116 | */ |
| 117 | export const match = < |
| 118 | T extends string | number | boolean, |
| 119 | const Cases extends Record<string, SfnEffect<any, any>>, |
| 120 | B = never, |
| 121 | E2 = never, |
| 122 | >( |
| 123 | value: Expr<T>, |
| 124 | cases: Cases, |
| 125 | otherwise?: SfnEffect<B, E2>, |
| 126 | ): SfnEffect<Success<Cases[keyof Cases]> | B, ErrorOf<Cases[keyof Cases]> | E2> => |
| 127 | make({ kind: "match", value, cases, otherwise }); |
| 128 | |
| 129 | /** |
| 130 | * Produce a value (an ASL `Pass` state) — mirrors `Effect.succeed`. The |
| 131 | * value may embed typed `Expr` references from earlier steps. |
| 132 | */ |
| 133 | export const succeed = <const T>(value: T): SfnEffect<UnwrapExpr<T>> => |
| 134 | make({ kind: "succeed", value }); |
| 135 | |
| 136 | /** |
| 137 | * Fail the workflow with a tagged error (an ASL `Fail` state) — mirrors |
| 138 | * `Effect.fail`. The error's `_tag` becomes the ASL `Error` name, so |
| 139 | * `Sfn.catchTag(program, tag, …)` and `Sfn.retry({ while: [tag] })` line up |
| 140 | * with it end-to-end. |
| 141 | */ |
| 142 | export const fail = <E extends { readonly _tag: string }>( |
| 143 | error: E, |
| 144 | cause?: string, |
| 145 | ): SfnEffect<never, E> => |
| 146 | make({ |
| 147 | kind: "fail", |
| 148 | error: error._tag, |
| 149 | cause: cause ?? (error as { message?: string }).message ?? error._tag, |
| 150 | failure: error, |
| 151 | }); |
| 152 | |
| 153 | /** |
| 154 | * Retry a program on failure (ASL `Retry`) — mirrors `Effect.retry`, with |
| 155 | * an option bag in the `Schedule.exponential` vocabulary (`initial`, |
| 156 | * `backoff`, `maxAttempts`, `maxDelay`, `jitter`; `while` takes error |
| 157 | * tags). Multi-state programs are wrapped in a single-branch `Parallel` |
| 158 | * state so the whole program re-runs, matching `Effect.retry` semantics. |
| 159 | */ |
| 160 | export const retry: { |
| 161 | (options: RetryOptions): <A, E>(self: SfnEffect<A, E>) => SfnEffect<A, E>; |
| 162 | <A, E>(self: SfnEffect<A, E>, options: RetryOptions): SfnEffect<A, E>; |
| 163 | } = ((selfOrOptions: SfnEffect<any, any> | RetryOptions, options?: RetryOptions) => |
| 164 | isSfn(selfOrOptions) |
| 165 | ? make({ kind: "retry", inner: selfOrOptions, options: options ?? {} }) |
| 166 | : (self: SfnEffect<any, any>) => |
| 167 | make({ kind: "retry", inner: self, options: selfOrOptions })) as any; |
| 168 | |
| 169 | /** |
| 170 | * Catch failures by tag (ASL `Catch` with `ErrorEquals`) — mirrors |
| 171 | * `Effect.catchTag`, narrowing `E` exactly the same way. The handler |
| 172 | * receives a typed reference to the ASL error output (`{ Error, Cause }`). |
| 173 | */ |
| 174 | export const catchTag: { |
| 175 | <Tag extends string, A2, E2>( |
| 176 | tag: Tag | readonly Tag[], |
| 177 | handler: (error: Expr<ErrorOutput>) => SfnEffect<A2, E2>, |
| 178 | ): <A, E>(self: SfnEffect<A, E>) => SfnEffect<A | A2, Exclude<E, { _tag: Tag }> | E2>; |
| 179 | <A, E, Tag extends string, A2, E2>( |
| 180 | self: SfnEffect<A, E>, |
| 181 | tag: Tag | readonly Tag[], |
| 182 | handler: (error: Expr<ErrorOutput>) => SfnEffect<A2, E2>, |
| 183 | ): SfnEffect<A | A2, Exclude<E, { _tag: Tag }> | E2>; |
| 184 | } = ((...args: any[]) => |
| 185 | isSfn(args[0]) |
| 186 | ? make({ |
| 187 | kind: "catch", |
| 188 | inner: args[0], |
| 189 | tags: Array.isArray(args[1]) ? args[1] : [args[1]], |
| 190 | handler: args[2], |
| 191 | }) |
| 192 | : (self: SfnEffect<any, any>) => |
| 193 | make({ |
| 194 | kind: "catch", |
| 195 | inner: self, |
| 196 | tags: Array.isArray(args[0]) ? args[0] : [args[0]], |
| 197 | handler: args[1], |
| 198 | })) as any; |
| 199 | |
| 200 | /** |
| 201 | * Catch every failure (ASL `Catch` with `States.ALL`) — mirrors |
| 202 | * `Effect.catchAll`. |
| 203 | */ |
| 204 | export const catchAll: { |
| 205 | <A2, E2>( |
| 206 | handler: (error: Expr<ErrorOutput>) => SfnEffect<A2, E2>, |
| 207 | ): <A, E>(self: SfnEffect<A, E>) => SfnEffect<A | A2, E2>; |
| 208 | <A, E, A2, E2>( |
| 209 | self: SfnEffect<A, E>, |
| 210 | handler: (error: Expr<ErrorOutput>) => SfnEffect<A2, E2>, |
| 211 | ): SfnEffect<A | A2, E2>; |
| 212 | } = ((...args: any[]) => |
| 213 | isSfn(args[0]) |
| 214 | ? make({ |
| 215 | kind: "catch", |
| 216 | inner: args[0], |
| 217 | tags: ["States.ALL"], |
| 218 | handler: args[1], |
| 219 | }) |
| 220 | : (self: SfnEffect<any, any>) => |
| 221 | make({ |
| 222 | kind: "catch", |
| 223 | inner: self, |
| 224 | tags: ["States.ALL"], |
| 225 | handler: args[0], |
| 226 | })) as any; |
| 227 | |
| 228 | /** The `States.*` built-in error names, for `retry`/`catchTag`. */ |
| 229 | export const Errors = { |
| 230 | ALL: "States.ALL", |
| 231 | Timeout: "States.Timeout", |
| 232 | TaskFailed: "States.TaskFailed", |
| 233 | Permissions: "States.Permissions", |
| 234 | BranchFailed: "States.BranchFailed", |
| 235 | NoChoiceMatched: "States.NoChoiceMatched", |
| 236 | IntrinsicFailure: "States.IntrinsicFailure", |
| 237 | ExceedToleratedFailureThreshold: "States.ExceedToleratedFailureThreshold", |
| 238 | ItemReaderFailed: "States.ItemReaderFailed", |
| 239 | ResultWriterFailed: "States.ResultWriterFailed", |
| 240 | HeartbeatTimeout: "States.HeartbeatTimeout", |
| 241 | QueryEvaluationError: "States.QueryEvaluationError", |
| 242 | Runtime: "States.Runtime", |
| 243 | } as const; |