Skip to content

@temporal-contract/contract


@temporal-contract/contract

Type Aliases

ActivityDefaultOptions

ts
type ActivityDefaultOptions = object;

Defined in: types.ts:72

Contract-level default ActivityOptions for a single activity.

Declared on defineActivity so operational behavior (timeouts, retry policy) ships with the contract as a single source of truth shared by every worker, instead of being scattered per-declareWorkflow call.

Merge precedence at the worker (least → most specific): declareWorkflow's activityOptions (workflow-wide default) → this defaultOptions (activity-specific, from the contract author) → activityOptionsByName (explicit per-workflow, per-activity override).

Deployment-specific concerns (taskQueue routing, cancellation type) are deliberately excluded — those belong to the worker's activityOptionsByName, not the portable contract.

Properties

PropertyModifierTypeDefined in
heartbeatTimeout?readonlyDurationValuetypes.ts:76
retry?readonlyActivityRetryPolicytypes.ts:77
scheduleToCloseTimeout?readonlyDurationValuetypes.ts:74
scheduleToStartTimeout?readonlyDurationValuetypes.ts:75
startToCloseTimeout?readonlyDurationValuetypes.ts:73

ActivityDefinition

ts
type ActivityDefinition<TInput, TOutput, TErrors> = object;

Defined in: types.ts:83

Definition of an activity

Type Parameters

Type ParameterDefault type
TInput extends AnySchemaAnySchema
TOutput extends AnySchemaAnySchema
TErrors extends Record<string, ErrorDefinition>Record<string, ErrorDefinition>

Properties

PropertyModifierTypeDefined in
defaultOptions?readonlyActivityDefaultOptionstypes.ts:91
errors?readonlyTErrorstypes.ts:90
inputreadonlyTInputtypes.ts:88
outputreadonlyTOutputtypes.ts:89

ActivityRetryPolicy

ts
type ActivityRetryPolicy = object;

Defined in: types.ts:48

Portable subset of Temporal's RetryPolicy, usable in contract-level activity defaults. Field names and semantics match @temporalio/common's RetryPolicy one-to-one.

Properties

PropertyModifierTypeDefined in
backoffCoefficient?readonlynumbertypes.ts:51
initialInterval?readonlyDurationValuetypes.ts:49
maximumAttempts?readonlynumbertypes.ts:52
maximumInterval?readonlyDurationValuetypes.ts:50
nonRetryableErrorTypes?readonlyreadonly string[]types.ts:53

AnySchema

ts
type AnySchema = StandardSchemaV1;

Defined in: types.ts:8

Base types for validation schemas Any schema that implements the Standard Schema specification This includes Zod, Valibot, ArkType, and other compatible libraries


AnyWorkflowDefinition

ts
type AnyWorkflowDefinition = WorkflowDefinition<AnySchema, AnySchema, Record<string, ActivityDefinition>, Record<string, SignalDefinition>, Record<string, QueryDefinition>, Record<string, UpdateDefinition>, Record<string, SearchAttributeDefinition>, Record<string, ErrorDefinition>>;

Defined in: types.ts:207

Widened constraint variant of WorkflowDefinition.

WorkflowDefinition (no args) resolves the empty-record generics to Record<string, never>, which is the right default for fresh callers but too narrow as a constraint — a Record-of-WorkflowDefinition constraint built from it would reject any literal whose activities, signals, queries, or updates block is non-empty. AnyWorkflowDefinition widens those generics back to their permissive bounds so it can act as the value of Record<string, …> in ContractDefinition without preventing real workflow definitions from satisfying the constraint.


ClientInferInput

ts
type ClientInferInput<T> = StandardSchemaV1.InferInput<T["input"]>;

Defined in: types.ts:337

Infer input type from a definition (client perspective) Client sends the input type (before input schema parsing/transformation)

Type Parameters

Type Parameter
T extends object

ClientInferOutput

ts
type ClientInferOutput<T> = StandardSchemaV1.InferOutput<T["output"]>;

Defined in: types.ts:345

Infer output type from a definition (client perspective) Client receives the output type (after output schema parsing/transformation)

Type Parameters

Type Parameter
T extends object

ContractDefinition

ts
type ContractDefinition<TWorkflows, TActivities> = object;

Defined in: types.ts:352

Contract definition containing workflows and optional global activities

Type Parameters

Type ParameterDefault type
TWorkflows extends Record<string, AnyWorkflowDefinition>Record<string, AnyWorkflowDefinition>
TActivities extends Record<string, ActivityDefinition>Record<string, ActivityDefinition>

Properties

PropertyModifierTypeDefined in
activities?readonlyTActivitiestypes.ts:358
taskQueuereadonlystringtypes.ts:356
workflowsreadonlyTWorkflowstypes.ts:357

DeclaredErrorsOf

ts
type DeclaredErrorsOf<TDef> = TDef extends object ? TErrors extends Record<string, ErrorDefinition> ? TErrors : never : never;

Defined in: types.ts:227

Extract the declared errors map from an activity or workflow definition, or never when the definition declares none.

The conditional is distributive and infer-based (rather than indexing TDef["errors"] directly) for the same reasons as SignalNamesOf: union definitions yield the union of their error maps, and the optional property is tolerated under exactOptionalPropertyTypes.

Type Parameters

Type Parameter
TDef

DurationValue

ts
type DurationValue = string | number;

Defined in: types.ts:41

A Temporal duration: either a number of milliseconds or an ms-formatted string ("30 seconds", "5m", …). Kept as string | number rather than Temporal's template-literal Duration type so the contract package stays free of @temporalio/* dependencies; the worker forwards values to Temporal unchanged.


ErrorDefinition

ts
type ErrorDefinition<TData> = object;

Defined in: types.ts:28

Definition of a typed domain error on an activity or workflow.

Declared under the errors map of defineActivity / defineWorkflow, keyed by error name. The name becomes the ApplicationFailure.type discriminator on the wire, so callers (and Temporal retry policies via retry.nonRetryableErrorTypes) can branch on it.

  • data — optional Standard Schema for the structured payload carried in ApplicationFailure.details. Validated on the producing side before the failure crosses the network boundary, and again when it is rehydrated on the consuming side.
  • message — default human-readable message when the producer doesn't supply one at construction time.
  • nonRetryable — when true, Temporal stops retrying immediately. This lives on the contract (not the call site) so retry semantics are part of the shared source of truth. Defaults to false (retryable).

Type Parameters

Type ParameterDefault type
TData extends AnySchemaAnySchema

Properties

PropertyModifierTypeDefined in
data?readonlyTDatatypes.ts:29
message?readonlystringtypes.ts:30
nonRetryable?readonlybooleantypes.ts:31

InferActivityNames

ts
type InferActivityNames<TContract> = TContract["activities"] extends Record<string, ActivityDefinition> ? keyof TContract["activities"] & string : never;

Defined in: types.ts:386

Extract activity names from a contract (global activities) as a union type

Type Parameters

Type Parameter
TContract extends ContractDefinition

Example

typescript
type MyActivityNames = InferActivityNames<typeof myContract>;
// "log" | "sendEmail"

InferContractWorkflows

ts
type InferContractWorkflows<TContract> = TContract["workflows"];

Defined in: types.ts:399

Extract all workflows from a contract with their definitions

Type Parameters

Type Parameter
TContract extends ContractDefinition

Example

typescript
type MyWorkflows = InferContractWorkflows<typeof myContract>;

InferErrorData

ts
type InferErrorData<TDef> = TDef extends object ? StandardSchemaV1.InferOutput<TSchema> : undefined;

Defined in: types.ts:242

Consumer-side data payload of a declared error: the data schema's output type (post-transform), or undefined when the error declares no data schema. This is the shape a workflow sees after an activity's failure is rehydrated, and a client sees after a workflow's failure is rehydrated.

Type Parameters

Type Parameter
TDef extends ErrorDefinition

InferErrorDataInput

ts
type InferErrorDataInput<TDef> = TDef extends object ? StandardSchemaV1.InferInput<TSchema> : undefined;

Defined in: types.ts:253

Producer-side data payload of a declared error: the data schema's input type (pre-transform) — what an implementation passes to the typed error constructor before boundary validation runs.

Type Parameters

Type Parameter
TDef extends ErrorDefinition

InferWorkflowNames

ts
type InferWorkflowNames<TContract> = keyof TContract["workflows"] & string;

Defined in: types.ts:374

Extract workflow names from a contract as a union type

Type Parameters

Type Parameter
TContract extends ContractDefinition

Example

typescript
type MyWorkflowNames = InferWorkflowNames<typeof myContract>;
// "processOrder" | "sendNotification"

QueryDefinition

ts
type QueryDefinition<TInput, TOutput> = object;

Defined in: types.ts:104

Definition of a query

Type Parameters

Type ParameterDefault type
TInput extends AnySchemaAnySchema
TOutput extends AnySchemaAnySchema

Properties

PropertyModifierTypeDefined in
inputreadonlyTInputtypes.ts:108
outputreadonlyTOutputtypes.ts:109

QueryNamesOf

ts
type QueryNamesOf<W> = W extends object ? Q extends Record<string, QueryDefinition> ? keyof Q & string : never : never;

Defined in: types.ts:285

Extract query names declared on a workflow as a string union, or never if the workflow declares no queries. See SignalNamesOf for the rationale behind the distributive infer-based shape.

Type Parameters

Type Parameter
W extends AnyWorkflowDefinition

SearchAttributeDefinition

ts
type SearchAttributeDefinition<TKind> = object;

Defined in: types.ts:160

Definition of a typed search attribute on a workflow.

Type Parameters

Type ParameterDefault type
TKind extends SearchAttributeKindSearchAttributeKind

Properties

PropertyModifierTypeDefined in
kindreadonlyTKindtypes.ts:161

SearchAttributeKind

ts
type SearchAttributeKind = 
  | "TEXT"
  | "KEYWORD"
  | "INT"
  | "DOUBLE"
  | "BOOL"
  | "DATETIME"
  | "KEYWORD_LIST";

Defined in: types.ts:129

The seven Temporal search attribute kinds.

Mirrors @temporalio/common's SearchAttributeType so values flow into Temporal's typedSearchAttributes API unchanged.


SearchAttributeKindToType

ts
type SearchAttributeKindToType<T> = object[T];

Defined in: types.ts:147

Map each SearchAttributeKind to its TypeScript representation.

  • TEXT / KEYWORDstring
  • INT / DOUBLEnumber
  • BOOLboolean
  • DATETIMEDate
  • KEYWORD_LISTstring[]

Type Parameters

Type Parameter
T extends SearchAttributeKind

SignalDefinition

ts
type SignalDefinition<TInput> = object;

Defined in: types.ts:97

Definition of a signal

Type Parameters

Type ParameterDefault type
TInput extends AnySchemaAnySchema

Properties

PropertyModifierTypeDefined in
inputreadonlyTInputtypes.ts:98

SignalNamesOf

ts
type SignalNamesOf<W> = W extends object ? S extends Record<string, SignalDefinition> ? keyof S & string : never : never;

Defined in: types.ts:272

Extract signal names declared on a workflow as a string union, or never if the workflow declares no signals. Used to constrain signalName call sites so typos surface at compile time instead of runtime.

The conditional is intentionally distributive over W (rather than indexing W["signals"] directly) so that union workflow types — e.g. discriminated unions of workflow definitions — yield the union of their signal names rather than the intersection (keyof (A | B) is the intersection of keys, which usually collapses to never). Destructuring signals via infer S also tolerates the property being absent or undefined under exactOptionalPropertyTypes.

Type Parameters

Type Parameter
W extends AnyWorkflowDefinition

UpdateDefinition

ts
type UpdateDefinition<TInput, TOutput> = object;

Defined in: types.ts:115

Definition of an update

Type Parameters

Type ParameterDefault type
TInput extends AnySchemaAnySchema
TOutput extends AnySchemaAnySchema

Properties

PropertyModifierTypeDefined in
inputreadonlyTInputtypes.ts:119
outputreadonlyTOutputtypes.ts:120

UpdateNamesOf

ts
type UpdateNamesOf<W> = W extends object ? U extends Record<string, UpdateDefinition> ? keyof U & string : never : never;

Defined in: types.ts:298

Extract update names declared on a workflow as a string union, or never if the workflow declares no updates. See SignalNamesOf for the rationale behind the distributive infer-based shape.

Type Parameters

Type Parameter
W extends AnyWorkflowDefinition

WorkerInferInput

ts
type WorkerInferInput<T> = StandardSchemaV1.InferOutput<T["input"]>;

Defined in: types.ts:321

Infer input type from a definition (worker perspective) Worker receives the output type (after input schema parsing/transformation)

Type Parameters

Type Parameter
T extends object

WorkerInferOutput

ts
type WorkerInferOutput<T> = StandardSchemaV1.InferInput<T["output"]>;

Defined in: types.ts:329

Infer output type from a definition (worker perspective) Worker returns the input type (before output schema parsing/transformation)

Type Parameters

Type Parameter
T extends object

WorkflowDefinition

ts
type WorkflowDefinition<TInput, TOutput, TActivities, TSignals, TQueries, TUpdates, TSearchAttributes, TErrors> = object;

Defined in: types.ts:175

Definition of a workflow.

Generic parameters preserve the schema literal types of input/output and the declared shape of activities/signals/queries/updates/search attributes through defineWorkflow so client and worker call sites can infer typed payloads. Empty-collection generics default to Record<string, never> so that, when no signals/queries/updates/etc. are declared, keyof resolves to never rather than string — turning typos in signalName/queryName/updateName into compile-time errors.

Type Parameters

Type ParameterDefault type
TInput extends AnySchemaAnySchema
TOutput extends AnySchemaAnySchema
TActivities extends Record<string, ActivityDefinition>Record<string, never>
TSignals extends Record<string, SignalDefinition>Record<string, never>
TQueries extends Record<string, QueryDefinition>Record<string, never>
TUpdates extends Record<string, UpdateDefinition>Record<string, never>
TSearchAttributes extends Record<string, SearchAttributeDefinition>Record<string, never>
TErrors extends Record<string, ErrorDefinition>Record<string, never>

Properties

PropertyModifierTypeDefined in
activities?readonlyTActivitiestypes.ts:187
errors?readonlyTErrorstypes.ts:192
inputreadonlyTInputtypes.ts:185
outputreadonlyTOutputtypes.ts:186
queries?readonlyTQueriestypes.ts:189
searchAttributes?readonlyTSearchAttributestypes.ts:191
signals?readonlyTSignalstypes.ts:188
updates?readonlyTUpdatestypes.ts:190

Functions

defineActivity()

ts
function defineActivity<TActivity>(definition): TActivity;

Defined in: builder.ts:61

Define a Temporal activity with type-safe input and output schemas.

Activities are the building blocks of Temporal workflows that execute business logic and interact with external services. This function preserves TypeScript types while providing a consistent structure for activity definitions.

Type Parameters

Type ParameterDescription
TActivity extends ActivityDefinitionThe activity definition type with input/output schemas

Parameters

ParameterTypeDescription
definitionTActivityThe activity definition containing input and output schemas

Returns

TActivity

The same definition with preserved types for type inference

Example

typescript
import { defineActivity } from '@temporal-contract/contract';
import { z } from 'zod';

export const sendEmail = defineActivity({
  input: z.object({
    to: z.string().email(),
    subject: z.string(),
    body: z.string(),
  }),
  output: z.object({
    messageId: z.string(),
    sentAt: z.date(),
  }),
  // Typed domain errors — the error name becomes the
  // `ApplicationFailure.type` on the wire, `data` its validated payload,
  // and `nonRetryable` drives Temporal's retry policy from the contract.
  errors: {
    RecipientRejected: {
      data: z.object({ reason: z.string() }),
      nonRetryable: true,
    },
  },
  // Contract-level ActivityOptions defaults shared by every worker.
  // Merge precedence: declareWorkflow's activityOptions
  // < defaultOptions < activityOptionsByName.
  defaultOptions: {
    startToCloseTimeout: "30 seconds",
    retry: { maximumAttempts: 5 },
  },
});

defineContract()

ts
function defineContract<TContract>(definition): TContract;

Defined in: builder.ts:302

Define a complete Temporal contract with type-safe workflows and activities.

A contract is the central definition that ties together your Temporal application's workflows and activities. It provides:

  • Type safety across client, worker, and workflow code
  • Automatic validation at runtime
  • Compile-time verification of implementations
  • Clear API boundaries and documentation

The contract validates the structure and ensures:

  • Task queue is specified
  • At least one workflow is defined
  • Valid JavaScript identifiers are used
  • No conflicts between global and workflow-specific activities
  • All schemas implement the Standard Schema specification

Type Parameters

Type ParameterDescription
TContract extends ContractDefinitionThe contract definition type

Parameters

ParameterTypeDescription
definitionTContractThe complete contract definition

Returns

TContract

The same definition with preserved types for type inference

Throws

If the contract structure is invalid

Composition-first. Define resources individually with defineActivity / defineWorkflow (and friends), then reference them here — don't inline definitions in defineContract. Named resources are reusable across workflows and contracts, get precise hover/jump-to-definition, and keep the contract itself a readable table of contents.

Example

typescript
import { defineActivity, defineContract, defineWorkflow } from '@temporal-contract/contract';
import { z } from 'zod';

// Define resources first...
const chargePayment = defineActivity({
  input: z.object({ amount: z.number() }),
  output: z.object({ transactionId: z.string() }),
});

const logEvent = defineActivity({
  input: z.object({ message: z.string() }),
  output: z.void(),
});

const processOrder = defineWorkflow({
  input: z.object({ orderId: z.string() }),
  output: z.object({ success: z.boolean() }),
  activities: { chargePayment },
});

// ...then compose the contract from references.
export const myContract = defineContract({
  taskQueue: 'orders',
  workflows: { processOrder },
  // Optional global activities shared across workflows
  activities: { logEvent },
});

defineQuery()

ts
function defineQuery<TQuery>(definition): TQuery;

Defined in: builder.ts:126

Define a Temporal query with type-safe input and output schemas.

Queries allow you to read the current state of a running workflow without modifying it. They are synchronous and should not perform any mutations.

Synchronous validation required. Temporal query handlers must complete synchronously, so the input and output schemas you pass here must validate synchronously. In practice this rules out async refinements (e.g. Zod's .refine(async (x) => …)). Standard Schema doesn't expose the sync/async distinction at the type level, so the worker checks at runtime and throws if it ever receives a Promise from ~standard.validate. Use plain Zod / Valibot / ArkType object schemas without async refinements.

Type Parameters

Type ParameterDescription
TQuery extends QueryDefinitionThe query definition type with input/output schemas

Parameters

ParameterTypeDescription
definitionTQueryThe query definition containing input and output schemas

Returns

TQuery

The same definition with preserved types for type inference

Example

typescript
import { defineQuery } from '@temporal-contract/contract';
import { z } from 'zod';

export const getOrderStatus = defineQuery({
  input: z.object({ orderId: z.string() }),
  output: z.object({
    status: z.enum(['pending', 'processing', 'completed', 'failed']),
    updatedAt: z.date(),
  }),
});

defineSearchAttribute()

ts
function defineSearchAttribute<TKind>(definition): SearchAttributeDefinition<TKind>;

Defined in: builder.ts:198

Define a typed search attribute on a workflow.

Search attributes are indexed on Temporal's visibility store and let you query / filter workflow executions by domain attributes. Declaring them on the contract means the client's workflow-start options and (eventually) the worker's search-attribute reader are constrained to declared keys with the right value types.

Type Parameters

Type Parameter
TKind extends SearchAttributeKind

Parameters

ParameterType
definitionSearchAttributeDefinition<TKind>

Returns

SearchAttributeDefinition<TKind>

Example

typescript
import { defineSearchAttribute } from '@temporal-contract/contract';

defineWorkflow({
  input: z.object({ orderId: z.string() }),
  output: z.object({ status: z.string() }),
  searchAttributes: {
    customerId: defineSearchAttribute({ kind: 'KEYWORD' }),
    priority: defineSearchAttribute({ kind: 'INT' }),
    placedAt: defineSearchAttribute({ kind: 'DATETIME' }),
  },
});

The seven Temporal kinds map to TypeScript types like so:

kindTS type
TEXTstring
KEYWORDstring
INTnumber
DOUBLEnumber
BOOLboolean
DATETIMEDate
KEYWORD_LISTstring[]

defineSignal()

ts
function defineSignal<TSignal>(definition): TSignal;

Defined in: builder.ts:90

Define a Temporal signal with type-safe input schema.

Signals are asynchronous messages sent to running workflows to update their state or trigger certain behaviors. This function ensures type safety for signal payloads.

Type Parameters

Type ParameterDescription
TSignal extends SignalDefinitionThe signal definition type with input schema

Parameters

ParameterTypeDescription
definitionTSignalThe signal definition containing input schema

Returns

TSignal

The same definition with preserved types for type inference

Example

typescript
import { defineSignal } from '@temporal-contract/contract';
import { z } from 'zod';

export const approveOrder = defineSignal({
  input: z.object({
    orderId: z.string(),
    approvedBy: z.string(),
  }),
});

defineUpdate()

ts
function defineUpdate<TUpdate>(definition): TUpdate;

Defined in: builder.ts:158

Define a Temporal update with type-safe input and output schemas.

Updates are similar to signals but return a value and wait for the workflow to process them before completing. They provide a synchronous way to modify workflow state and get immediate feedback.

Type Parameters

Type ParameterDescription
TUpdate extends UpdateDefinitionThe update definition type with input/output schemas

Parameters

ParameterTypeDescription
definitionTUpdateThe update definition containing input and output schemas

Returns

TUpdate

The same definition with preserved types for type inference

Example

typescript
import { defineUpdate } from '@temporal-contract/contract';
import { z } from 'zod';

export const updateOrderQuantity = defineUpdate({
  input: z.object({
    orderId: z.string(),
    newQuantity: z.number().positive(),
  }),
  output: z.object({
    success: z.boolean(),
    totalPrice: z.number(),
  }),
});

defineWorkflow()

ts
function defineWorkflow<TWorkflow>(definition): TWorkflow;

Defined in: builder.ts:237

Define a Temporal workflow with type-safe input, output, and associated operations.

Workflows are durable functions that orchestrate activities, handle timeouts, and manage long-running processes. This function provides type safety for the entire workflow definition including activities, signals, queries, and updates.

Type Parameters

Type ParameterDescription
TWorkflow extends AnyWorkflowDefinitionThe workflow definition type with all associated schemas

Parameters

ParameterTypeDescription
definitionTWorkflowThe workflow definition containing input, output, and operations

Returns

TWorkflow

The same definition with preserved types for type inference

Example

typescript
import { defineWorkflow, defineActivity, defineSignal } from '@temporal-contract/contract';
import { z } from 'zod';

export const processOrder = defineWorkflow({
  input: z.object({ orderId: z.string() }),
  output: z.object({ success: z.boolean() }),
  activities: {
    validatePayment: defineActivity({
      input: z.object({ orderId: z.string() }),
      output: z.object({ valid: z.boolean() }),
    }),
  },
  signals: {
    cancel: defineSignal({
      input: z.object({ reason: z.string() }),
    }),
  },
});

formatIssue()

ts
function formatIssue(issue): string;

Defined in: format.ts:40

Render a Standard Schema StandardSchemaV1.Issue into a human-readable string that includes the failing field's path.

Example output:

  • at items[0].quantity: Expected number, received undefined
  • at customerId: Expected string, received undefined
  • at user["first name"]: Expected string, received undefined
  • Validation error (no path)

Path segments come either as bare PropertyKey values or as { key: PropertyKey } objects (per the spec); both are normalized.

  • Numeric keys → [N]
  • String keys that are valid JS identifiers → bare (first) or .key
  • String keys that aren't valid identifiers → ["..."] with JSON-style escaping (handles dots, spaces, leading digits, the empty string, the literal string "0", embedded quotes, etc.)
  • Symbol / other PropertyKey[Symbol(name)]

Parameters

ParameterType
issueIssue

Returns

string


summarizeIssues()

ts
function summarizeIssues(issues): string;

Defined in: format.ts:66

Join a list of validation issues into a single message, with each issue rendered via formatIssue so field paths surface in the error text.

Parameters

ParameterType
issuesreadonly Issue[]

Returns

string

Released under the MIT License.