{"version":3,"sources":["../../src/workflows/workflow.ts"],"names":["WorkflowError","FrameworkError","message","extra","errors","context","run","isRetryable","isFatal","Workflow","Serializable","START","SELF","PREV","NEXT","END","emitter","steps","Map","startStep","undefined","input","Emitter","root","child","namespace","toCamelCase","name","filter","Boolean","creator","getSteps","Array","from","keys","schemas","pick","addStep","step","_addStep","addStrictStep","schema","schemaOrStep","stepOrEmpty","trim","ValueError","has","stepOrFlow","set","handler","asStep","setStart","state","options","RunContext","enter","signal","params","runContext","parse","result","handlers","abort","reason","next","findStep","start","current","get","emit","parseAsync","catch","err","shallowCopy","then","deepCopy","nextStepRaw","at","prev","stepResult","push","error","outputSchema","delStep","delete","overrides","ctx","mappedInput","mappedOutput","output","Object","assign","index","indexOf","createSnapshot","omit","loadSnapshot","snapshot","z","any"],"mappings":";;;;;;;;;;;;AA+EO,MAAMA,sBAIHC,yBAAAA,CAAAA;EAnFV;;;AAoFE,EAAA,WAAA,CAAYC,SAAiBC,KAAAA,EAA2D;AACtF,IAAA,KAAA,CAAMD,OAAAA,EAASC,OAAOC,MAAAA,EAAQ;MAC5BC,OAAAA,EAASF,KAAAA,EAAOG,OAAO,EAAC;MACxBC,WAAAA,EAAa,KAAA;MACbC,OAAAA,EAAS;KACX,CAAA;AACF,EAAA;AACF;AAEO,MAAMC,iBAIHC,6BAAAA,CAAAA;EAjGV;;;;AAkGE,EAAA,OAAuBC,KAAAA,GAAQ,WAAA;AAC/B,EAAA,OAAuBC,IAAAA,GAAO,UAAA;AAC9B,EAAA,OAAuBC,IAAAA,GAAO,UAAA;AAC9B,EAAA,OAAuBC,IAAAA,GAAO,UAAA;AAC9B,EAAA,OAAuBC,GAAAA,GAAM,SAAA;AAEbC,EAAAA,OAAAA;AAEGC,EAAAA,KAAAA,uBAAYC,GAAAA,EAAAA;EACrBC,SAAAA,GAA+BC,MAAAA;AAEzC,EAAA,WAAA,CAA+BC,KAAAA,EAAmC;AAChE,IAAA,KAAA,EAAK,EAAA,KADwBA,KAAAA,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A;AAAe,OAAA,CAAA;AAClDL,MAAAA,OAAAA,EAAS,IAAA,CAAKA,OAAAA;AACdG,MAAAA,SAAAA,EAAW,IAAA,CAAKA,SAAAA;AAChBF,MAAAA,KAAAA,EAAO,IAAA,CAAKA;AACd,KAAA;AACF,EAAA;AAEA+E,EAAAA,YAAAA,CAAaC,QAAAA,EAAkD;AAC7DP,IAAAA,MAAAA,CAAOC,MAAAA,CAAO,MAAMM,QAAAA,CAAAA;AACpB,IAAA,IAAA,CAAK5E,KAAAA,CAAMoB,MAAAA,KAAWyD,KAAAA,CAAEC,GAAAA,EAAG;AAC3B,IAAA,IAAA,CAAK9E,KAAAA,CAAM6D,YAAAA,KAAiBgB,KAAAA,CAAEC,GAAAA,EAAG;AACnC,EAAA;AACF","file":"workflow.cjs","sourcesContent":["/**\n * Copyright 2025 © BeeAI a Series of LF Projects, LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { z, ZodSchema } from \"zod\";\nimport { Serializable } from \"@/internals/serializable.js\";\nimport { Callback, Emitter } from \"@/emitter/emitter.js\";\nimport { RunContext } from \"@/context.js\";\nimport { omit, pick, toCamelCase } from \"remeda\";\nimport { deepCopy, shallowCopy } from \"@/serializer/utils.js\";\nimport { FrameworkError, ValueError } from \"@/errors.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-invalid-void-type\ntype WorkflowStepHandlerReturn<K extends string> = K | ReservedStep | void;\n\nexport interface WorkflowRun<T extends ZodSchema, T2 extends ZodSchema, K extends string> {\n  result: z.output<T2>;\n  steps: WorkflowStepRes<T, K>[];\n  state: z.output<T>;\n}\n\nexport interface WorkflowRunOptions<K extends string> {\n  start?: K;\n  signal?: AbortSignal;\n}\n\nexport interface WorkflowStepDef<T extends ZodSchema, K extends string> {\n  schema: T;\n  handler: WorkflowStepHandler<T, K>;\n}\n\nexport interface WorkflowStepRes<T extends ZodSchema, K extends string> {\n  name: K;\n  next: K | ReservedStep;\n  state: z.output<T>;\n}\n\nexport interface WorkflowRunContext<T extends ZodSchema, K extends string> {\n  steps: WorkflowStepRes<T, K>[];\n  signal: AbortSignal;\n  abort: (reason?: Error) => void;\n}\n\nexport type WorkflowStepHandler<T extends ZodSchema, K extends string> = (\n  state: z.output<T>,\n  context: WorkflowRunContext<T, K>,\n) => Promise<WorkflowStepHandlerReturn<K>> | WorkflowStepHandlerReturn<K>;\n\nexport interface WorkflowEvents<T extends ZodSchema, T2 extends ZodSchema, K extends string> {\n  start: Callback<{ step: K; run: WorkflowRun<T, T2, K> }>;\n  error: Callback<{\n    step: K;\n    error: Error;\n    run: WorkflowRun<T, T2, K>;\n  }>;\n  success: Callback<{\n    step: K;\n    next: K | ReservedStep;\n    state: z.output<T>;\n    run: WorkflowRun<T, T2, K>;\n  }>;\n}\n\ninterface FlowInput<TS extends ZodSchema, TS2 extends ZodSchema = TS> {\n  name?: string;\n  schema: TS;\n  outputSchema?: TS2;\n}\n\ntype RunStep<K extends string> = K | typeof Workflow.END;\ntype ReservedStep =\n  | typeof Workflow.START\n  | typeof Workflow.NEXT\n  | typeof Workflow.PREV\n  | typeof Workflow.END\n  | typeof Workflow.SELF;\nexport type FlowStepName<K extends string> = K | ReservedStep;\n\nexport class WorkflowError<\n  T extends ZodSchema,\n  T2 extends ZodSchema,\n  K extends string,\n> extends FrameworkError {\n  constructor(message: string, extra?: { run?: WorkflowRun<T, T2, K>; errors?: Error[] }) {\n    super(message, extra?.errors, {\n      context: extra?.run ?? {},\n      isRetryable: false,\n      isFatal: true,\n    });\n  }\n}\n\nexport class Workflow<\n  TInput extends ZodSchema,\n  TOutput extends ZodSchema = TInput,\n  TKeys extends string = string,\n> extends Serializable {\n  public static readonly START = \"__start__\";\n  public static readonly SELF = \"__self__\";\n  public static readonly PREV = \"__prev__\";\n  public static readonly NEXT = \"__next__\";\n  public static readonly END = \"__end__\";\n\n  public readonly emitter: Emitter<WorkflowEvents<TInput, TOutput, TKeys>>;\n\n  protected readonly steps = new Map<string, WorkflowStepDef<TInput, TKeys>>();\n  protected startStep: TKeys | undefined = undefined;\n\n  constructor(protected readonly input: FlowInput<TInput, TOutput>) {\n    super();\n    this.emitter = Emitter.root.child({\n      namespace: [\"workflow\", toCamelCase(input?.name ?? \"\")].filter(Boolean),\n      creator: this,\n    });\n  }\n\n  getSteps() {\n    return Array.from(this.steps.keys()) as TKeys[];\n  }\n\n  get name() {\n    return this.input.name ?? \"\";\n  }\n\n  get schemas() {\n    return pick(this.input, [\"schema\", \"outputSchema\"]);\n  }\n\n  addStep<L extends string>(\n    name: L,\n    handler: WorkflowStepHandler<TInput | TOutput, TKeys>,\n  ): Workflow<TInput, TOutput, L | TKeys>;\n  addStep<L extends string, TFlow extends AnyWorkflowFlow>(\n    name: L,\n    flow: Workflow.pipeable<this, TFlow>,\n  ): Workflow<TInput, TOutput, L | TKeys>;\n  addStep<L extends string>(\n    name: L,\n    step: WorkflowStepHandler<TInput | TOutput, TKeys> | AnyWorkflowFlow,\n  ): Workflow<TInput, TOutput, L | TKeys> {\n    return this._addStep(name, step);\n  }\n\n  addStrictStep<L extends string, TI2 extends ZodSchema>(\n    name: L,\n    schema: TI2,\n    handler: WorkflowStepHandler<TI2, TKeys>,\n  ): Workflow<TInput, TOutput, L | TKeys>;\n  addStrictStep<L extends string, TI2 extends ZodSchema, TFlow extends AnyWorkflowFlow>(\n    name: L,\n    schema: TI2,\n    flow: Workflow.pipeable<Workflow<TI2, TOutput, TKeys>, TFlow>,\n  ): Workflow<TInput, TOutput, L | TKeys>;\n  addStrictStep<L extends string, TI2 extends ZodSchema>(\n    name: L,\n    schema: TI2,\n    step: WorkflowStepHandler<TI2, TKeys> | AnyWorkflowFlow,\n  ): Workflow<TInput, TOutput, L | TKeys> {\n    return this._addStep(name, schema, step);\n  }\n\n  protected _addStep<TI2 extends ZodSchema = TInput, L extends string = TKeys>(\n    name: L,\n    schemaOrStep: TI2 | WorkflowStepHandler<TInput, TKeys> | AnyWorkflowFlow,\n    stepOrEmpty?: WorkflowStepHandler<TI2, TKeys> | AnyWorkflowFlow,\n  ): Workflow<TInput, TOutput, L | TKeys> {\n    if (!name.trim()) {\n      throw new ValueError(`Step name cannot be empty!`);\n    }\n    if (this.steps.has(name)) {\n      throw new ValueError(`Step '${name}' already exists!`);\n    }\n    if (name === Workflow.END) {\n      throw new ValueError(`The name '${name}' cannot be used!`);\n    }\n\n    const schema = (schemaOrStep && stepOrEmpty ? schemaOrStep : this.input.schema) as TInput;\n    const stepOrFlow = stepOrEmpty || schemaOrStep;\n\n    this.steps.set(name, {\n      schema,\n      handler: stepOrFlow instanceof Workflow ? stepOrFlow.asStep({}) : stepOrFlow,\n    } as WorkflowStepDef<TInput, TKeys>);\n\n    return this as unknown as Workflow<TInput, TOutput, L | TKeys>;\n  }\n\n  setStart(name: TKeys) {\n    this.startStep = name;\n    return this;\n  }\n\n  run(state: z.input<TInput>, options: WorkflowRunOptions<TKeys> = {}) {\n    return RunContext.enter(\n      this,\n      { signal: options?.signal, params: [state, options] as const },\n      async (runContext): Promise<WorkflowRun<TInput, TOutput, TKeys>> => {\n        const run: WorkflowRun<TInput, TOutput, TKeys> = {\n          steps: [],\n          state: this.input.schema.parse(state),\n          result: undefined as z.output<TOutput>,\n        };\n        const handlers: WorkflowRunContext<TInput, TKeys> = {\n          steps: run.steps,\n          signal: runContext.signal,\n          abort: (reason) => runContext.abort(reason),\n        };\n\n        let next: RunStep<TKeys> =\n          this.findStep(options?.start || this.startStep || this.getSteps()[0]).current ??\n          Workflow.END;\n\n        while (next && next !== Workflow.END) {\n          const name = next;\n          const step = this.steps.get(next);\n          if (!step) {\n            throw new WorkflowError(`Step '${next}' was not found.`, { run });\n          }\n          await runContext.emitter.emit(\"start\", { run, step: next });\n          try {\n            const state = await step.schema\n              .parseAsync(run.state)\n              .catch(async (err: Error) => {\n                throw new WorkflowError(\n                  `Step '${next}' cannot be executed because the provided input doesn't adhere to the step's schema.`,\n                  { run: shallowCopy(run), errors: [err] },\n                );\n              })\n              .then(deepCopy);\n\n            const nextStepRaw = await step.handler(state, handlers);\n            if (nextStepRaw === Workflow.START) {\n              next = run.steps.at(0)?.name!;\n            } else if (nextStepRaw === Workflow.PREV) {\n              next = this.findStep(next).prev;\n            } else if (nextStepRaw === Workflow.SELF) {\n              next = this.findStep(next).current;\n            } else if (!nextStepRaw || nextStepRaw === Workflow.NEXT) {\n              next = this.findStep(next).next || Workflow.END;\n            } else {\n              next = nextStepRaw;\n            }\n\n            const stepResult: WorkflowStepRes<TInput, TKeys> = {\n              name,\n              state,\n              next,\n            };\n            run.steps.push(stepResult);\n            run.state = stepResult.state;\n\n            await runContext.emitter.emit(\"success\", {\n              run: shallowCopy(run),\n              state: stepResult.state,\n              step: stepResult.name,\n              next: stepResult.next,\n            });\n          } catch (error) {\n            await runContext.emitter.emit(\"error\", {\n              run: shallowCopy(run),\n              step: next as TKeys,\n              error,\n            });\n            throw error;\n          }\n        }\n\n        run.result = await (this.input.outputSchema ?? this.input.schema)\n          .parseAsync(run.state)\n          .catch((err) => {\n            throw new WorkflowError(\n              `Workflow has ended but it's state does not adhere to the workflow's output schema.`,\n              { run: shallowCopy(run), errors: [err] },\n            );\n          });\n        return run;\n      },\n    );\n  }\n\n  delStep<L extends TKeys>(name: L): Workflow<TInput, TOutput, Exclude<TKeys, L>> {\n    if (this.startStep === name) {\n      this.startStep = undefined;\n    }\n    this.steps.delete(name);\n    return this as unknown as Workflow<TInput, TOutput, Exclude<TKeys, L>>;\n  }\n\n  asStep<\n    TInput2 extends ZodSchema = TInput,\n    TOutput2 extends ZodSchema = TOutput,\n    TKeys2 extends string = TKeys,\n  >(overrides: {\n    input?: (input: z.output<TInput2>) => z.output<TInput> | z.input<TInput>;\n    output?: (output: z.output<TOutput>) => z.output<TOutput2> | z.input<TOutput2>;\n    start?: TKeys;\n    next?: FlowStepName<TKeys2>;\n  }): WorkflowStepHandler<TInput2, TKeys | TKeys2> {\n    return async (state, ctx) => {\n      const mappedInput = overrides?.input ? overrides.input(state) : state;\n      const result = await this.run(mappedInput, { start: overrides?.start, signal: ctx.signal });\n      const mappedOutput = overrides?.output ? overrides.output(result.state) : result.state;\n      Object.assign(state, mappedOutput);\n      return overrides.next;\n    };\n  }\n\n  protected findStep(current: TKeys) {\n    const steps = this.getSteps();\n    const index = steps.indexOf(current);\n    return {\n      prev: steps[index - 1],\n      current: steps[index],\n      next: steps[index + 1],\n    };\n  }\n\n  createSnapshot() {\n    return {\n      input: omit(this.input, [\"schema\", \"outputSchema\"]),\n      emitter: this.emitter,\n      startStep: this.startStep,\n      steps: this.steps,\n    };\n  }\n\n  loadSnapshot(snapshot: ReturnType<typeof this.createSnapshot>) {\n    Object.assign(this, snapshot);\n    this.input.schema ??= z.any() as unknown as TInput;\n    this.input.outputSchema ??= z.any() as unknown as TOutput;\n  }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace Workflow {\n  export type pipeable<T extends AnyWorkflowFlow, T2 extends AnyWorkflowFlow> =\n    Workflow.state<T> extends Workflow.input<T2> ? T2 : never;\n  export type input<T> = T extends Workflow<infer A, any, any> ? z.input<A> : never;\n  export type state<T> = T extends Workflow<infer A, any, any> ? z.output<A> : never;\n  export type output<T> = T extends Workflow<any, infer A, any> ? z.output<A> : never;\n  export type run<T> = T extends Workflow<infer A, infer B, infer C> ? WorkflowRun<A, B, C> : never;\n}\n\nexport type AnyWorkflowFlow = Workflow<any, any, any>;\n"]}