Interface WorkflowBuilder<C, Ready>
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
Index
Methods
build
-
Checks the whole workflow, then makes its workflow object, calling the constructor with the arguments
constructWithwas given, and gives it its new workflow descriptor.Parameters
- this: WorkflowBuilder<C, true>
Returns Built<InstanceType<C>>
construct With
-
Keeps the arguments the workflow class's constructor is called with when the workflow is built.
Parameters
- ...args: ConstructorParameters<C>
Returns WorkflowBuilder<C, true>
id Generator
-
idGenerator<K extends string | symbol>(
key: K,
...requests: Tokens<
ParametersOf<InstanceType<C>, K>,
Place<InstanceType<C>, K>,
>,
): thisMakes the method
keyof the workflow class its ID generator, called with the workflow object asthisto make each instance's journey ID, its parameter, when it has one, makingrequests, as@idGeneratordoes 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
Returns this
input Adapter
-
inputAdapter<K extends string | symbol>(
key: K,
options: InputAdapterOptions,
...requests: Tokens<
ParametersOf<InstanceType<C>, K>,
Place<InstanceType<C>, K>,
>,
): thisMakes the method
keyof the workflow class an input adapter, asoptionssay, after those the workflow has so far, its parameters makingrequests, in order, as@inputAdapterdoes 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
- key: K
- options: InputAdapterOptions
- ...requests: Tokens<ParametersOf<InstanceType<C>, K>, Place<InstanceType<C>, K>>
Returns this
listing
-
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[]
name
policy
-
policy<P extends WorkflowPolicyClass<unknown>>(
policy: (P | WorkflowPolicyBuilder<P>) & Provides<
InstanceType<C>,
RolesOfOne<P>,
>,
): thisAttaches 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
- P extends WorkflowPolicyClass<unknown>
Parameters
- policy: (P | WorkflowPolicyBuilder<P>) & Provides<InstanceType<C>, RolesOfOne<P>>
Returns this
provider
-
provider<T, K extends string | symbol>(
key: K,
type: ServiceType<T>,
options: ProviderOptions,
...requests: Tokens<
ParametersOf<InstanceType<C>, K>,
Place<InstanceType<C>, K>,
>,
): thisMakes the method
keyof the workflow class a service provider of the service typetype, asoptionssay, after those the workflow has so far, its parameters makingrequests, in order, as@providerdoes 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
- key: K
- type: ServiceType<T>
- options: ProviderOptions
- ...requests: Tokens<ParametersOf<InstanceType<C>, K>, Place<InstanceType<C>, K>>
Returns this
reporter
-
Adds a class of reporters, after those the workflow lists so far.
Parameters
- reporter: ReporterClass
Returns this
step
-
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@stepor not, started withCharge.builder("charge"). It compiles only when the workflow class implements every role the step's policies request.Type Parameters
- S extends StepClass
- R
Returns this
Puts a workflow together, starting from what the decorators of its class
Cdeclared, 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 ofCwith the argumentsconstructWithwas given.Readysays whether those arguments are known:build()does not compile until they are, unless the constructor takes none.