Interface WorkflowBuilder<C, Ready>

Puts a workflow together, starting from what the decorators of its class C declared, and makes its workflow object. Orders.builder() makes one.

Each method adds to what the workflow will have and returns the builder. build() checks the whole workflow, then calls the constructor of C with the arguments constructWith was given. Ready says whether those arguments are known: build() does not compile until they are, unless the constructor takes none.

import assert from "node:assert/strict";
import type { Event } from "itinera/event";
import { type DataBag, dataBag } from "itinera/journey";
import type { Reporter } from "itinera/report";
import { type Outcome, Step } from "itinera/step";
import { Workflow } from "itinera/workflow";
import { integer } from "itinera/value";

class Charge extends Step {
override run(): Outcome {
return this.succeed();
}
}

class Ship extends Step {
override run(): Outcome {
return this.succeed();
}
}

class Audit implements Reporter {
readonly kinds: string[] = [];

report(event: Event): void {
this.kinds.push(event.kind);
}
}

class Orders extends Workflow {
constructor(readonly shop: string) {
super();
}

orderId(data: DataBag): string {
const number = data.read("number", integer).option();
return `${this.shop}-${number.map(String).unwrapOr("unnumbered")}`;
}
}

const orders = Orders.builder()
.name("orders")
.step(Charge.builder("charge").retryBudget(1).noRetryOnAbnormalTermination())
.step(Ship.builder("ship"))
.reporter(Audit)
.idGenerator("orderId", dataBag())
.constructWith("corner")
.build();

const instance = orders.instance({ number: 7 });
assert.equal(instance.descriptor.name, "orders");
assert.equal(instance.journeyId, "corner-7");
assert.deepEqual(
instance.descriptor.steps().map((described) => described.name),
["charge", "ship"],
);
assert.equal(instance.descriptor.steps()[0]?.retryBudget, 1);
assert.equal(instance.descriptor.steps()[0]?.retryOnAbnormalTermination, false);
interface WorkflowBuilder<
    C extends new (...args: never[]) => Workflow,
    Ready extends boolean = [] extends ConstructorParameters<C> ? true : false,
> {
    build(this: WorkflowBuilder<C, true>): Built<InstanceType<C>>;
    constructWith(...args: ConstructorParameters<C>): WorkflowBuilder<C, true>;
    idGenerator<K extends string | symbol>(
        key: K,
        ...requests: Tokens<
            ParametersOf<InstanceType<C>, K>,
            Place<InstanceType<C>, K>,
        >,
    ): this;
    inputAdapter<K extends string | symbol>(
        key: K,
        options: InputAdapterOptions,
        ...requests: Tokens<
            ParametersOf<InstanceType<C>, K>,
            Place<InstanceType<C>, K>,
        >,
    ): this;
    listing(): readonly ListedStep[];
    name(name: string): this;
    policy<P extends WorkflowPolicyClass<unknown>>(
        policy: (P | WorkflowPolicyBuilder<P>) & Provides<
            InstanceType<C>,
            RolesOfOne<P>,
        >,
    ): this;
    provider<T, K extends string | symbol>(
        key: K,
        type: ServiceType<T>,
        options: ProviderOptions,
        ...requests: Tokens<
            ParametersOf<InstanceType<C>, K>,
            Place<InstanceType<C>, K>,
        >,
    ): this;
    reporter(reporter: ReporterClass): this;
    step<S extends StepClass, R>(
        step: StepBuilder<S, R> & Provides<InstanceType<C>, R>,
    ): this;
}

Type Parameters

  • C extends new (...args: never[]) => Workflow
  • Ready extends boolean = [] extends ConstructorParameters<C> ? true : false

Index

  • Checks the whole workflow, then makes its workflow object, calling the constructor with the arguments constructWith was given, and gives it its new workflow descriptor.

    Parameters

    Returns Built<InstanceType<C>>

    Violations listing every violation in how the workflow is put together, before the constructor runs.

    Error if the workflow has no name.

  • Makes the method key of the workflow class its ID generator, called with the workflow object as this to make each instance's journey ID, its parameter, when it has one, making requests, as @idGenerator does for a method it marks: dataBag(), a data bag holding the instance's initial data.

    import assert from "node:assert/strict";
    import type { Event } from "itinera/event";
    import { type DataBag, dataBag } from "itinera/journey";
    import type { Reporter } from "itinera/report";
    import { type Outcome, Step } from "itinera/step";
    import { Workflow } from "itinera/workflow";
    import { integer } from "itinera/value";

    class Charge extends Step {
    override run(): Outcome {
    return this.succeed();
    }
    }

    class Ship extends Step {
    override run(): Outcome {
    return this.succeed();
    }
    }

    class Audit implements Reporter {
    readonly kinds: string[] = [];

    report(event: Event): void {
    this.kinds.push(event.kind);
    }
    }

    class Orders extends Workflow {
    constructor(readonly shop: string) {
    super();
    }

    orderId(data: DataBag): string {
    const number = data.read("number", integer).option();
    return `${this.shop}-${number.map(String).unwrapOr("unnumbered")}`;
    }
    }

    const orders = Orders.builder()
    .name("orders")
    .step(Charge.builder("charge").retryBudget(1).noRetryOnAbnormalTermination())
    .step(Ship.builder("ship"))
    .reporter(Audit)
    .idGenerator("orderId", dataBag())
    .constructWith("corner")
    .build();

    const instance = orders.instance({ number: 7 });
    assert.equal(instance.descriptor.name, "orders");
    assert.equal(instance.journeyId, "corner-7");
    assert.deepEqual(
    instance.descriptor.steps().map((described) => described.name),
    ["charge", "ship"],
    );
    assert.equal(instance.descriptor.steps()[0]?.retryBudget, 1);
    assert.equal(instance.descriptor.steps()[0]?.retryOnAbnormalTermination, false);

    Type Parameters

    • K extends string | symbol

    Parameters

    Returns this

    Error if the workflow has an ID generator already, if key names a field rather than a method of the class, if the method declares its requests with decorators, if a parameter is left without a request, or if one makes a request an ID generator may not make.

  • Makes the method key of the workflow class an input adapter, as options say, after those the workflow has so far, its parameters making requests, in order, as @inputAdapter does for a method it marks.

    import assert from "node:assert/strict";
    import { type Contributor, contributor } from "itinera/journey";
    import { type Provided, service, serviceType } from "itinera/service";
    import {
    type Attempt,
    attempt,
    input,
    type Outcome,
    Step,
    type StepName,
    stepName,
    } from "itinera/step";
    import { key, type Supplied, Workflow } from "itinera/workflow";
    import { integer, string } from "itinera/value";

    interface PaymentGateway {
    take(amount: number): string;
    }

    const PAYMENT_GATEWAY = serviceType<PaymentGateway>("PaymentGateway");

    class Charge extends Step {
    constructor(readonly amount: number) {
    super();
    }

    override run(payments: PaymentGateway, contributing: Contributor): Outcome {
    contributing.contribute("payment", payments.take(this.amount));
    return this.succeed();
    }
    }

    class Orders extends Workflow {
    pricing(step: StepName, inputKey: string): Supplied {
    return this.supply(step === "charge" && inputKey === "amount" ? 40 : 0);
    }

    payments(attempted: Attempt): Provided<PaymentGateway> {
    return this.provide({
    take: (amount) => `${String(amount)} paid, attempt ${String(attempted)}`,
    });
    }
    }

    const orders = Orders.builder()
    .name("orders")
    .step(
    Charge.builder("charge")
    .needs(input("amount", integer))
    .run(service("payments", PAYMENT_GATEWAY), contributor()),
    )
    .inputAdapter("pricing", { steps: ["charge"] }, stepName(), key())
    .provider("payments", PAYMENT_GATEWAY, { perAttempt: true }, attempt())
    .build();

    assert.deepEqual(
    orders
    .instance()
    .descriptor.steps()
    .map((described) => described.name),
    ["charge"],
    );

    // @ts-expect-error the amount is a number, so it cannot be read as a string
    Charge.builder("charge").needs(input("amount", string));

    assert.throws(
    // @ts-expect-error run takes two parameters, and each needs its request
    () => Charge.builder("charge").run(service("payments", PAYMENT_GATEWAY)),
    /Charge.run: parameter 2 carries no request/,
    );

    Orders.builder().inputAdapter(
    // @ts-expect-error payments provides a service, it does not supply an input
    "payments",
    { steps: ["charge"] },
    stepName(),
    key(),
    );

    Type Parameters

    • K extends string | symbol

    Parameters

    Returns this

    Error if key names a field rather than a method of the class, if the name is empty, if the method declares its requests with decorators, if a parameter is left without a request, or if one makes a request an input adapter may not make.

  • Lists the steps the workflow has so far, in order, without running anything and without a workflow object, as the workflow descriptor build() would make lists them.

    import assert from "node:assert/strict";
    import {
    type OnSuccess,
    onStepSuccess,
    StepPolicy,
    stepPolicy,
    } from "itinera/policy";
    import { type Provided, provider, service, serviceType } from "itinera/service";
    import {
    type Outcome,
    RescueStep,
    rescueStep,
    type RescueOutcome,
    Step,
    step,
    } from "itinera/step";
    import {
    inputAdapter,
    key,
    type ListedStep,
    type Supplied,
    withStep,
    Workflow,
    workflow,
    } from "itinera/workflow";

    interface PaymentGateway {
    take(amount: number): string;
    }

    const PAYMENT_GATEWAY = serviceType<PaymentGateway>("PaymentGateway");

    @step()
    class Charge extends Step {
    override run(
    @service("payments", PAYMENT_GATEWAY) payments: PaymentGateway,
    ): Outcome {
    payments.take(40);
    return this.succeed();
    }
    }

    @step()
    class Ship extends Step {
    override run(): Outcome {
    return this.succeed();
    }
    }

    @rescueStep()
    class Refund extends RescueStep {
    override run(): RescueOutcome {
    return this.succeed();
    }
    }

    @stepPolicy({ name: "audit" })
    class Audit extends StepPolicy {
    @onStepSuccess()
    audited(): OnSuccess {
    return this.keepDefault();
    }
    }

    @workflow({ name: "orders" })
    @withStep(Charge, { name: "charge", policies: [Audit], rescue: Refund })
    @withStep(Ship, { name: "ship" })
    class Orders extends Workflow {
    @inputAdapter({ steps: ["charge"] })
    pricing(@key() inputKey: string): Supplied {
    return this.supply(inputKey.length);
    }

    @provider(PAYMENT_GATEWAY, { name: "gateway" })
    payments(): Provided<PaymentGateway> {
    return this.provide({ take: (amount) => `${String(amount)} paid` });
    }
    }

    const listing: readonly ListedStep[] = Orders.listing();

    assert.deepEqual(listing, [
    {
    step: "charge",
    position: 1,
    policies: ["audit"],
    adapter: "pricing",
    services: [{ key: "payments", provider: "gateway" }],
    rescue: { step: "charge_rescue", services: [] },
    },
    { step: "ship", position: 2, policies: [], services: [] },
    ]);
    assert.deepEqual(
    Orders.builder()
    .step(Ship.builder("return"))
    .listing()
    .map((listed) => listed.step),
    ["charge", "ship", "return"],
    );

    Returns readonly ListedStep[]

    Violations listing every violation in how the workflow is put together so far.

    Error if the workflow has no name.

  • Names the workflow, in place of the name @workflow gave it.

    Parameters

    • name: string

    Returns this

    Error if the name is empty.

  • Attaches a workflow policy, after those attached so far: a class declared with @workflowPolicy, or a policy's builder. It compiles only when the workflow class implements every role the policy requests.

    import assert from "node:assert/strict";
    import { type Contributor, contributor } from "itinera/journey";
    import {
    failureCause,
    fromStep,
    type OnFailure,
    type OnSuccess,
    type PolicyDescriptor,
    role,
    type StepFailureCause,
    StepPolicy,
    type StepPolicyBuilder,
    WorkflowPolicy,
    type WorkflowPolicyBuilder,
    } from "itinera/policy";
    import { Step, type Outcome } from "itinera/step";
    import { Workflow } from "itinera/workflow";
    import { integer } from "itinera/value";

    /** A role the shop provides: telling a customer something. */
    interface Messages {
    tell(message: string): void;
    }

    class Charge extends Step {
    override run(): Outcome {
    return this.succeed();
    }
    }

    class Audit extends StepPolicy {
    audited(charged: number, contributing: Contributor): OnSuccess {
    contributing.contribute("audit", `charged ${String(charged)}`);
    return this.keepDefault();
    }

    failed(cause: StepFailureCause): OnFailure {
    return this.failWorkflow(cause);
    }
    }

    class Notify extends WorkflowPolicy<Messages> {
    paid(messages: Messages): void {
    messages.tell("paid");
    }
    }

    class Orders extends Workflow implements Messages {
    readonly told: string[] = [];

    tell(message: string): void {
    this.told.push(message);
    }
    }

    const audit: StepPolicyBuilder<typeof Audit> = Audit.builder("audit")
    .onStepSuccess("audited", fromStep("charged", integer), contributor())
    .onStepFailure("failed", failureCause());
    const notify: WorkflowPolicyBuilder<typeof Notify> = Notify.builder(
    "notify",
    ).onWorkflowSuccess("paid", role<Messages>());

    const orders = Orders.builder()
    .name("orders")
    .step(Charge.builder("charge").policy(audit))
    .policy(notify)
    .build();

    const descriptor = orders.instance().descriptor;
    const attached: readonly PolicyDescriptor[] =
    descriptor.steps()[0]?.policies() ?? [];

    assert.deepEqual(
    attached.map((policy) => policy.name),
    ["audit"],
    );
    assert.deepEqual(attached[0]?.hooks(), ["on step success", "on step failure"]);
    const built = attached[0].build();
    assert.ok(built instanceof Audit);
    assert.deepEqual(attached[0].call(built, "on step failure", ["failure"]), {
    kind: "FailWorkflow",
    reason: { code: "failure" },
    });
    assert.deepEqual(
    descriptor.policies().map((policy) => policy.name),
    ["notify"],
    );

    class Counter extends Workflow {}

    // @ts-expect-error Counter does not implement Messages, which notify requests
    Counter.builder().policy(notify);

    Type Parameters

    Parameters

    Returns this

    Error if the class is not declared with @workflowPolicy, or if the policy's builder was given no hook.

  • Makes the method key of the workflow class a service provider of the service type type, as options say, after those the workflow has so far, its parameters making requests, in order, as @provider does for a method it marks.

    import assert from "node:assert/strict";
    import { type Contributor, contributor } from "itinera/journey";
    import { type Provided, service, serviceType } from "itinera/service";
    import {
    type Attempt,
    attempt,
    input,
    type Outcome,
    Step,
    type StepName,
    stepName,
    } from "itinera/step";
    import { key, type Supplied, Workflow } from "itinera/workflow";
    import { integer, string } from "itinera/value";

    interface PaymentGateway {
    take(amount: number): string;
    }

    const PAYMENT_GATEWAY = serviceType<PaymentGateway>("PaymentGateway");

    class Charge extends Step {
    constructor(readonly amount: number) {
    super();
    }

    override run(payments: PaymentGateway, contributing: Contributor): Outcome {
    contributing.contribute("payment", payments.take(this.amount));
    return this.succeed();
    }
    }

    class Orders extends Workflow {
    pricing(step: StepName, inputKey: string): Supplied {
    return this.supply(step === "charge" && inputKey === "amount" ? 40 : 0);
    }

    payments(attempted: Attempt): Provided<PaymentGateway> {
    return this.provide({
    take: (amount) => `${String(amount)} paid, attempt ${String(attempted)}`,
    });
    }
    }

    const orders = Orders.builder()
    .name("orders")
    .step(
    Charge.builder("charge")
    .needs(input("amount", integer))
    .run(service("payments", PAYMENT_GATEWAY), contributor()),
    )
    .inputAdapter("pricing", { steps: ["charge"] }, stepName(), key())
    .provider("payments", PAYMENT_GATEWAY, { perAttempt: true }, attempt())
    .build();

    assert.deepEqual(
    orders
    .instance()
    .descriptor.steps()
    .map((described) => described.name),
    ["charge"],
    );

    // @ts-expect-error the amount is a number, so it cannot be read as a string
    Charge.builder("charge").needs(input("amount", string));

    assert.throws(
    // @ts-expect-error run takes two parameters, and each needs its request
    () => Charge.builder("charge").run(service("payments", PAYMENT_GATEWAY)),
    /Charge.run: parameter 2 carries no request/,
    );

    Orders.builder().inputAdapter(
    // @ts-expect-error payments provides a service, it does not supply an input
    "payments",
    { steps: ["charge"] },
    stepName(),
    key(),
    );

    Type Parameters

    • T
    • K extends string | symbol

    Parameters

    Returns this

    Error if key names a field rather than a method of the class, if its name or its key is empty, if the method declares its requests with decorators, if a parameter is left without a request, or if one makes a request a service provider may not make.

  • Adds a step after the steps the workflow has so far, as its builder has put it together so far: a class extending Step, declared with @step or not, started with Charge.builder("charge"). It compiles only when the workflow class implements every role the step's policies request.

    Type Parameters

    Parameters

    Returns this

    Error if a parameter of the step's constructor or of its run has no request.