Skip to content

@temporal-contract/worker


@temporal-contract/worker / activity

activity ​

Classes ​

ActivityDefinitionNotFoundError ​

Defined in: packages/worker/src/errors.ts:111

Error thrown when an activity definition is not found in the contract

Extends ​

  • TaggedErrorInstance<"@temporal-contract/ActivityDefinitionNotFoundError", { activityName: string; availableDefinitions: readonly string[]; }>

Constructors ​

Constructor ​
ts
new ActivityDefinitionNotFoundError(activityName, availableDefinitions?): ActivityDefinitionNotFoundError;

Defined in: packages/worker/src/errors.ts:118

Parameters ​
ParameterTypeDefault value
activityNamestringundefined
availableDefinitionsreadonly string[][]
Returns ​

ActivityDefinitionNotFoundError

Overrides ​
ts
TaggedError(
  ACTIVITY_DEFINITION_NOT_FOUND_ERROR_TAG,
  { name: "ActivityDefinitionNotFoundError" },
)<{
  activityName: string;
  availableDefinitions: readonly string[];
}>.constructor

Properties ​

PropertyModifierTypeInherited fromDefined in
_tagreadonly"@temporal-contract/ActivityDefinitionNotFoundError"TaggedError( ACTIVITY_DEFINITION_NOT_FOUND_ERROR_TAG, { name: "ActivityDefinitionNotFoundError" }, )._tagnode_modules/.pnpm/unthrown@5.11.0/node_modules/unthrown/dist/index.d.mts:2332
activityNamereadonlystringTaggedError( ACTIVITY_DEFINITION_NOT_FOUND_ERROR_TAG, { name: "ActivityDefinitionNotFoundError" }, ).activityNamepackages/worker/src/errors.ts:115
availableDefinitionsreadonlyreadonly string[]TaggedError( ACTIVITY_DEFINITION_NOT_FOUND_ERROR_TAG, { name: "ActivityDefinitionNotFoundError" }, ).availableDefinitionspackages/worker/src/errors.ts:116
cause?publicunknownTaggedError( ACTIVITY_DEFINITION_NOT_FOUND_ERROR_TAG, { name: "ActivityDefinitionNotFoundError" }, ).causenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24
messagepublicstringTaggedError( ACTIVITY_DEFINITION_NOT_FOUND_ERROR_TAG, { name: "ActivityDefinitionNotFoundError" }, ).messagenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
namepublicstringTaggedError( ACTIVITY_DEFINITION_NOT_FOUND_ERROR_TAG, { name: "ActivityDefinitionNotFoundError" }, ).namenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
stack?publicstringTaggedError( ACTIVITY_DEFINITION_NOT_FOUND_ERROR_TAG, { name: "ActivityDefinitionNotFoundError" }, ).stacknode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076

ActivityInputValidationError ​

Defined in: packages/worker/src/errors.ts:146

Error thrown when activity input validation fails.

Extends ​

Constructors ​

Constructor ​
ts
new ActivityInputValidationError(activityName, issues): ActivityInputValidationError;

Defined in: packages/worker/src/errors.ts:149

Parameters ​
ParameterType
activityNamestring
issuesreadonly Issue[]
Returns ​

ActivityInputValidationError

Overrides ​
ts
ValidationError.constructor

Properties ​

PropertyModifierTypeDescriptionInherited fromDefined in
activityNamereadonlystring--packages/worker/src/errors.ts:150
category?readonly"BENIGN" | null-WorkflowInputValidationError.categorynode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:114
cause?readonlyError-ActivityOutputValidationError.causenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:72
details?readonlyunknown[] | null-WorkflowInputValidationError.detailsnode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:112
directionreadonly"input"--packages/worker/src/errors.ts:147
failure?publicIFailureThe original failure that constructed this error. Only present if this error was generated from an external operation.ValidationError.failurenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:78
issuesreadonlyreadonly Issue[]-ValidationError.issuespackages/worker/src/errors.ts:64
messagepublicstring-ValidationError.messagenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
namepublicstring-ValidationError.namenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
nextRetryDelay?readonlyany-WorkflowInputValidationError.nextRetryDelaynode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:113
nonRetryable?readonlyboolean | null-WorkflowInputValidationError.nonRetryablenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:111
stack?publicstring-ValidationError.stacknode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
type?readonlystring | null-WorkflowInputValidationError.typenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:110
stackTraceLimitstaticnumberThe Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)). The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames.ValidationError.stackTraceLimitnode_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:68

Methods ​

captureStackTrace() ​
ts
static captureStackTrace(targetObject, constructorOpt?): void;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:52

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

js
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

js
function a() {
  b();
}

function b() {
  c();
}

function c() {
  // Create an error without stack trace to avoid calculating the stack trace twice.
  const { stackTraceLimit } = Error;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = stackTraceLimit;

  // Capture the stack trace above function b
  Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
  throw error;
}

a();
Parameters ​
ParameterType
targetObjectobject
constructorOpt?Function
Returns ​

void

Inherited from ​

ValidationError.captureStackTrace

create() ​
ts
static create(options): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:131

Create a new ApplicationFailure.

By default, will be retryable (unless its type is included in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterType
optionsApplicationFailureOptions
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.create

fromError() ​
ts
static fromError(error, overrides?): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:125

Create a new ApplicationFailure from an Error object.

First calls ensureApplicationFailure | `ensureApplicationFailure(error)` and then overrides any fields provided in overrides.

Parameters ​
ParameterType
errorunknown
overrides?ApplicationFailureOptions
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.fromError

nonRetryable() ​
ts
static nonRetryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:151

Get a new ApplicationFailure with the nonRetryable flag set to true.

When thrown from an Activity or Workflow, the Activity or Workflow will not be retried (even if type is not listed in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.nonRetryable

prepareStackTrace() ​
ts
static prepareStackTrace(err, stackTraces): any;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:56

Parameters ​
ParameterType
errError
stackTracesCallSite[]
Returns ​

any

See ​

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from ​

ValidationError.prepareStackTrace

retryable() ​
ts
static retryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:140

Get a new ApplicationFailure with the nonRetryable flag set to false. Note that this error will still not be retried if its type is included in RetryPolicy.nonRetryableErrorTypes.

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type (used by RetryPolicy.nonRetryableErrorTypes)
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.retryable


ActivityOutputValidationError ​

Defined in: packages/worker/src/errors.ts:162

Error thrown when activity output validation fails.

Extends ​

Constructors ​

Constructor ​
ts
new ActivityOutputValidationError(activityName, issues): ActivityOutputValidationError;

Defined in: packages/worker/src/errors.ts:165

Parameters ​
ParameterType
activityNamestring
issuesreadonly Issue[]
Returns ​

ActivityOutputValidationError

Overrides ​
ts
ValidationError.constructor

Properties ​

PropertyModifierTypeDescriptionInherited fromDefined in
activityNamereadonlystring--packages/worker/src/errors.ts:166
category?readonly"BENIGN" | null-ValidationError.categorynode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:114
cause?readonlyError-ValidationError.causenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:72
details?readonlyunknown[] | null-ValidationError.detailsnode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:112
directionreadonly"output"--packages/worker/src/errors.ts:163
failure?publicIFailureThe original failure that constructed this error. Only present if this error was generated from an external operation.ValidationError.failurenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:78
issuesreadonlyreadonly Issue[]-ValidationError.issuespackages/worker/src/errors.ts:64
messagepublicstring-ValidationError.messagenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
namepublicstring-ValidationError.namenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
nextRetryDelay?readonlyany-ValidationError.nextRetryDelaynode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:113
nonRetryable?readonlyboolean | null-ValidationError.nonRetryablenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:111
stack?publicstring-ValidationError.stacknode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
type?readonlystring | null-ValidationError.typenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:110
stackTraceLimitstaticnumberThe Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)). The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames.ValidationError.stackTraceLimitnode_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:68

Methods ​

captureStackTrace() ​
ts
static captureStackTrace(targetObject, constructorOpt?): void;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:52

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

js
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

js
function a() {
  b();
}

function b() {
  c();
}

function c() {
  // Create an error without stack trace to avoid calculating the stack trace twice.
  const { stackTraceLimit } = Error;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = stackTraceLimit;

  // Capture the stack trace above function b
  Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
  throw error;
}

a();
Parameters ​
ParameterType
targetObjectobject
constructorOpt?Function
Returns ​

void

Inherited from ​

ValidationError.captureStackTrace

create() ​
ts
static create(options): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:131

Create a new ApplicationFailure.

By default, will be retryable (unless its type is included in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterType
optionsApplicationFailureOptions
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.create

fromError() ​
ts
static fromError(error, overrides?): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:125

Create a new ApplicationFailure from an Error object.

First calls ensureApplicationFailure | `ensureApplicationFailure(error)` and then overrides any fields provided in overrides.

Parameters ​
ParameterType
errorunknown
overrides?ApplicationFailureOptions
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.fromError

nonRetryable() ​
ts
static nonRetryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:151

Get a new ApplicationFailure with the nonRetryable flag set to true.

When thrown from an Activity or Workflow, the Activity or Workflow will not be retried (even if type is not listed in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.nonRetryable

prepareStackTrace() ​
ts
static prepareStackTrace(err, stackTraces): any;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:56

Parameters ​
ParameterType
errError
stackTracesCallSite[]
Returns ​

any

See ​

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from ​

ValidationError.prepareStackTrace

retryable() ​
ts
static retryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:140

Get a new ApplicationFailure with the nonRetryable flag set to false. Note that this error will still not be retried if its type is included in RetryPolicy.nonRetryableErrorTypes.

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type (used by RetryPolicy.nonRetryableErrorTypes)
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.retryable


ApplicationFailure ​

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:109

ApplicationFailures are used to communicate application-specific failures in Workflows and Activities.

The type property is matched against RetryPolicy.nonRetryableErrorTypes to determine if an instance of this error is retryable. Another way to avoid retrying is by setting the nonRetryable flag to true.

In Workflows, if you throw a non-ApplicationFailure, the Workflow Task will fail and be retried. If you throw an ApplicationFailure, the Workflow Execution will fail.

In Activities, you can either throw an ApplicationFailure or another Error to fail the Activity Task. In the latter case, the Error will be converted to an ApplicationFailure. The conversion is done as following:

  • type is set to error.constructor?.name ?? error.name
  • message is set to error.message
  • nonRetryable is set to false
  • details are set to null
  • cause is set to error.cause when it is an Error
  • stack trace is copied from the original error

When an Activity Execution fails, the ApplicationFailure from the last Activity Task will be the cause of the ActivityFailure thrown in the Workflow.

Extends ​

  • TemporalFailure

Extended by ​

Constructors ​

Constructor ​
ts
new ApplicationFailure(
   message?, 
   type?, 
   nonRetryable?, 
   details?, 
   cause?, 
   nextRetryDelay?, 
   category?
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:118

Alternatively, use fromError or create.

Parameters ​
ParameterType
message?string | null
type?string | null
nonRetryable?boolean | null
details?unknown[] | null
cause?Error
nextRetryDelay?any
category?"BENIGN" | null
Returns ​

ApplicationFailure

Overrides ​
ts
TemporalFailure.constructor

Properties ​

PropertyModifierTypeDescriptionInherited fromDefined in
category?readonly"BENIGN" | null--node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:114
cause?readonlyError-ActivityOutputValidationError.causenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:72
details?readonlyunknown[] | null--node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:112
failure?publicIFailureThe original failure that constructed this error. Only present if this error was generated from an external operation.TemporalFailure.failurenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:78
messagepublicstring-TemporalFailure.messagenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
namepublicstring-TemporalFailure.namenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
nextRetryDelay?readonlyany--node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:113
nonRetryable?readonlyboolean | null--node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:111
stack?publicstring-TemporalFailure.stacknode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
type?readonlystring | null--node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:110
stackTraceLimitstaticnumberThe Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)). The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames.TemporalFailure.stackTraceLimitnode_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:68

Methods ​

captureStackTrace() ​
ts
static captureStackTrace(targetObject, constructorOpt?): void;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:52

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

js
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

js
function a() {
  b();
}

function b() {
  c();
}

function c() {
  // Create an error without stack trace to avoid calculating the stack trace twice.
  const { stackTraceLimit } = Error;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = stackTraceLimit;

  // Capture the stack trace above function b
  Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
  throw error;
}

a();
Parameters ​
ParameterType
targetObjectobject
constructorOpt?Function
Returns ​

void

Inherited from ​
ts
TemporalFailure.captureStackTrace
create() ​
ts
static create(options): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:131

Create a new ApplicationFailure.

By default, will be retryable (unless its type is included in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterType
optionsApplicationFailureOptions
Returns ​

ApplicationFailure

fromError() ​
ts
static fromError(error, overrides?): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:125

Create a new ApplicationFailure from an Error object.

First calls ensureApplicationFailure | `ensureApplicationFailure(error)` and then overrides any fields provided in overrides.

Parameters ​
ParameterType
errorunknown
overrides?ApplicationFailureOptions
Returns ​

ApplicationFailure

nonRetryable() ​
ts
static nonRetryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:151

Get a new ApplicationFailure with the nonRetryable flag set to true.

When thrown from an Activity or Workflow, the Activity or Workflow will not be retried (even if type is not listed in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

prepareStackTrace() ​
ts
static prepareStackTrace(err, stackTraces): any;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:56

Parameters ​
ParameterType
errError
stackTracesCallSite[]
Returns ​

any

See ​

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from ​
ts
TemporalFailure.prepareStackTrace
retryable() ​
ts
static retryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:140

Get a new ApplicationFailure with the nonRetryable flag set to false. Note that this error will still not be retried if its type is included in RetryPolicy.nonRetryableErrorTypes.

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type (used by RetryPolicy.nonRetryableErrorTypes)
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure


ContractError ​

Defined in: packages/contract/dist/errors-impl-D7p9uupF.d.mts:45

A typed domain error declared on a contract's errors map.

One class covers every declared error; the errorName field is the per-error discriminant (it equals the key in the contract's errors map and the ApplicationFailure.type on the wire). Narrow a union with it:

ts
if (result.isErr() && result.error instanceof ContractError) {
  switch (result.error.errorName) {
    case "PaymentDeclined":
      result.error.data; // { reason: string }
  }
}

The unthrown _tag ("@temporal-contract/ContractError") discriminates a ContractError from the other tagged errors in a Result's error channel (e.g. via result.match({ errCases: (m) => m.with(P.tag("@temporal-contract/ContractError"), …) })); errorName then narrows to the concrete declared error.

Extends ​

  • ContractError_base<{ cause?: unknown; data: TData; errorName: TName; }>

Type Parameters ​

Type ParameterDefault type
TName extends stringstring
TDataunknown

Constructors ​

Constructor ​
ts
new ContractError<TName, TData>(args): ContractError<TName, TData>;

Defined in: packages/contract/dist/errors-impl-D7p9uupF.d.mts:52

Parameters ​
ParameterType
args{ cause?: unknown; data: TData; errorName: TName; message: string; }
args.cause?unknown
args.dataTData
args.errorNameTName
args.messagestring
Returns ​

ContractError<TName, TData>

Overrides ​
ts
ContractError_base<{
  / Declared error name — the ApplicationFailure.type discriminator. /
  errorName: TName;
  / Structured payload validated against the declared data schema. /
  data: TData;
  cause?: unknown;
}>.constructor

Properties ​

PropertyModifierTypeDescriptionInherited fromDefined in
_tagreadonly"@temporal-contract/ContractError"-ContractError_base._tagnode_modules/.pnpm/unthrown@5.11.0/node_modules/unthrown/dist/index.d.mts:2332
cause?publicunknown-ActivityDefinitionNotFoundError.causenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24
datareadonlyTDataStructured payload validated against the declared data schema.ContractError_base.datapackages/contract/dist/errors-impl-D7p9uupF.d.mts:49
errorNamereadonlyTNameDeclared error name — the ApplicationFailure.type discriminator.ContractError_base.errorNamepackages/contract/dist/errors-impl-D7p9uupF.d.mts:47
messagepublicstring-ContractError_base.messagenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
namepublicstring-ContractError_base.namenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
stack?publicstring-ContractError_base.stacknode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076

ContractErrorDataValidationError ​

Defined in: packages/worker/src/errors.ts:280

Error thrown when a contract-declared error's data payload fails validation against its declared schema at the Temporal boundary — a deterministic contract-misuse bug, so the failure is terminal (nonRetryable) like the other validation errors. (A ContractError whose name isn't declared at all is a ContractMisuseError.)

Extends ​

Constructors ​

Constructor ​
ts
new ContractErrorDataValidationError(errorName, issues): ContractErrorDataValidationError;

Defined in: packages/worker/src/errors.ts:281

Parameters ​
ParameterType
errorNamestring
issuesreadonly Issue[]
Returns ​

ContractErrorDataValidationError

Overrides ​
ts
ValidationError.constructor

Properties ​

PropertyModifierTypeDescriptionInherited fromDefined in
category?readonly"BENIGN" | null-ValidationError.categorynode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:114
cause?readonlyError-ValidationError.causenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:72
details?readonlyunknown[] | null-ValidationError.detailsnode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:112
errorNamereadonlystring--packages/worker/src/errors.ts:282
failure?publicIFailureThe original failure that constructed this error. Only present if this error was generated from an external operation.ValidationError.failurenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:78
issuesreadonlyreadonly Issue[]-ValidationError.issuespackages/worker/src/errors.ts:64
messagepublicstring-ValidationError.messagenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
namepublicstring-ValidationError.namenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
nextRetryDelay?readonlyany-ValidationError.nextRetryDelaynode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:113
nonRetryable?readonlyboolean | null-ValidationError.nonRetryablenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:111
stack?publicstring-ValidationError.stacknode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
type?readonlystring | null-ValidationError.typenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:110
stackTraceLimitstaticnumberThe Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)). The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames.ValidationError.stackTraceLimitnode_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:68

Methods ​

captureStackTrace() ​
ts
static captureStackTrace(targetObject, constructorOpt?): void;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:52

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

js
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

js
function a() {
  b();
}

function b() {
  c();
}

function c() {
  // Create an error without stack trace to avoid calculating the stack trace twice.
  const { stackTraceLimit } = Error;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = stackTraceLimit;

  // Capture the stack trace above function b
  Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
  throw error;
}

a();
Parameters ​
ParameterType
targetObjectobject
constructorOpt?Function
Returns ​

void

Inherited from ​

ValidationError.captureStackTrace

create() ​
ts
static create(options): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:131

Create a new ApplicationFailure.

By default, will be retryable (unless its type is included in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterType
optionsApplicationFailureOptions
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.create

fromError() ​
ts
static fromError(error, overrides?): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:125

Create a new ApplicationFailure from an Error object.

First calls ensureApplicationFailure | `ensureApplicationFailure(error)` and then overrides any fields provided in overrides.

Parameters ​
ParameterType
errorunknown
overrides?ApplicationFailureOptions
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.fromError

nonRetryable() ​
ts
static nonRetryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:151

Get a new ApplicationFailure with the nonRetryable flag set to true.

When thrown from an Activity or Workflow, the Activity or Workflow will not be retried (even if type is not listed in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.nonRetryable

prepareStackTrace() ​
ts
static prepareStackTrace(err, stackTraces): any;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:56

Parameters ​
ParameterType
errError
stackTracesCallSite[]
Returns ​

any

See ​

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from ​

ValidationError.prepareStackTrace

retryable() ​
ts
static retryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:140

Get a new ApplicationFailure with the nonRetryable flag set to false. Note that this error will still not be retried if its type is included in RetryPolicy.nonRetryableErrorTypes.

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type (used by RetryPolicy.nonRetryableErrorTypes)
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.retryable


ContractMisuseError ​

Defined in: packages/worker/src/errors.ts:334

Error thrown when code misuses the contract surface — a deterministic programming bug, never a payload problem. Outside the sandbox it is the startup failure of declareActivitiesHandler (missing, conflicting or ambiguous implementations); at an activity boundary it is a ContractError whose name the activity doesn't declare. Inside the workflow sandbox it fires at one of two points with two different runtime consequences:

  • Binding a signal/query/update handler for a name the contract doesn't declare, using an async-validating schema where Temporal requires synchronous validation, throwing an undeclared ContractError, or continuing as new into an undeclared workflow. These throw from inside the running implementation — handleSignal/handleQuery/handleUpdate execute there, after Temporal has already invoked the workflow function — so the throw is classified as a normal workflow failure and fails the Workflow Execution terminally with a clear message, the same way throw context.errors.X(...) does. A plain Error at that point would instead be classified as a Workflow Task failure and retried indefinitely, leaving the execution silently Running forever — this is the case ValidationError's siblings all guard against, and it's genuinely true here.
  • Reaching an activity that no options cover (see buildRawActivitiesProxy in internal.ts). This one is different: it throws at module top level, inside declareWorkflow itself, before Temporal ever invokes the workflow function. A throw there is a Workflow Task failure regardless of the error class — nonRetryable never reaches a FailWorkflowExecution command from this path — so it stalls the workflow via indefinite workflow-task retry exactly like the plain TypeError it replaces. That is deliberate (see activity-bounds.ts); the value here is a typed, named, greppable failure, not a different retry outcome — and TypedWorker.create's registration check, which imports the workflows module, fails worker startup on it.

Extends ValidationError for family consistency with its siblings (a schema-validation failure at the wire boundary), even though the second case above doesn't share their retry-outcome rationale.

Carries no schema issues (the misuse is structural, not a payload validation failure), so the issues array is always empty.

Extends ​

Constructors ​

Constructor ​
ts
new ContractMisuseError(message): ContractMisuseError;

Defined in: packages/worker/src/errors.ts:335

Parameters ​
ParameterType
messagestring
Returns ​

ContractMisuseError

Overrides ​
ts
ValidationError.constructor

Properties ​

PropertyModifierTypeDescriptionInherited fromDefined in
category?readonly"BENIGN" | null-ValidationError.categorynode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:114
cause?readonlyError-ValidationError.causenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:72
details?readonlyunknown[] | null-ValidationError.detailsnode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:112
failure?publicIFailureThe original failure that constructed this error. Only present if this error was generated from an external operation.ValidationError.failurenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:78
issuesreadonlyreadonly Issue[]-ValidationError.issuespackages/worker/src/errors.ts:64
messagepublicstring-ValidationError.messagenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
namepublicstring-ValidationError.namenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
nextRetryDelay?readonlyany-ValidationError.nextRetryDelaynode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:113
nonRetryable?readonlyboolean | null-ValidationError.nonRetryablenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:111
stack?publicstring-ValidationError.stacknode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
type?readonlystring | null-ValidationError.typenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:110
stackTraceLimitstaticnumberThe Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)). The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames.ValidationError.stackTraceLimitnode_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:68

Methods ​

captureStackTrace() ​
ts
static captureStackTrace(targetObject, constructorOpt?): void;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:52

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

js
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

js
function a() {
  b();
}

function b() {
  c();
}

function c() {
  // Create an error without stack trace to avoid calculating the stack trace twice.
  const { stackTraceLimit } = Error;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = stackTraceLimit;

  // Capture the stack trace above function b
  Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
  throw error;
}

a();
Parameters ​
ParameterType
targetObjectobject
constructorOpt?Function
Returns ​

void

Inherited from ​

ValidationError.captureStackTrace

create() ​
ts
static create(options): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:131

Create a new ApplicationFailure.

By default, will be retryable (unless its type is included in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterType
optionsApplicationFailureOptions
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.create

fromError() ​
ts
static fromError(error, overrides?): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:125

Create a new ApplicationFailure from an Error object.

First calls ensureApplicationFailure | `ensureApplicationFailure(error)` and then overrides any fields provided in overrides.

Parameters ​
ParameterType
errorunknown
overrides?ApplicationFailureOptions
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.fromError

nonRetryable() ​
ts
static nonRetryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:151

Get a new ApplicationFailure with the nonRetryable flag set to true.

When thrown from an Activity or Workflow, the Activity or Workflow will not be retried (even if type is not listed in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.nonRetryable

prepareStackTrace() ​
ts
static prepareStackTrace(err, stackTraces): any;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:56

Parameters ​
ParameterType
errError
stackTracesCallSite[]
Returns ​

any

See ​

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from ​

ValidationError.prepareStackTrace

retryable() ​
ts
static retryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:140

Get a new ApplicationFailure with the nonRetryable flag set to false. Note that this error will still not be retried if its type is included in RetryPolicy.nonRetryableErrorTypes.

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type (used by RetryPolicy.nonRetryableErrorTypes)
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

Inherited from ​

ValidationError.retryable


abstract ValidationError ​

Defined in: packages/worker/src/errors.ts:60

Base class for the contract's runtime validation failures — workflow and activity input/output, plus query/update payloads. (Invalid signal payloads are not errors: signals are fire-and-forget, so the worker drops and logs them instead of failing the execution.)

These extend Temporal's ApplicationFailure with nonRetryable: true rather than a plain Error, and that distinction is load-bearing. The TypeScript SDK classifies a non-TemporalFailure thrown from workflow code as a Workflow Task failure — presumed to be a transient code bug or non-determinism — and retries the task indefinitely, leaving the execution silently Running forever (it looks like the worker "hung"). Only a TemporalFailure such as ApplicationFailure fails the Workflow Execution terminally. The same logic applies at the activity boundary, where Temporal's default retry policy has unlimited attempts: a plain Error would retry forever too.

Contract validation failures are deterministic — the schema is static, so bad input/output never becomes valid on replay or retry — so they are surfaced as non-retryable, failing fast with a clear error instead of an infinite retry loop.

The concrete subclass name is passed through as the failure type, so it stays discriminable after crossing Temporal's serialization boundary (where the JS class identity is lost) via failure.type. The message carries only the failing field paths (see summarizeIssues) because it is stored in history unencrypted; the full issues — schema messages included, which may echo payload values — ride details[0] as { message, path } records, which payload codecs do encrypt. The raw issues also remain available as a property for in-process inspection.

See issue #251.

Extends ​

Extended by ​

Properties ​

PropertyModifierTypeDescriptionInherited fromDefined in
category?readonly"BENIGN" | null-WorkflowInputValidationError.categorynode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:114
cause?readonlyError-ActivityOutputValidationError.causenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:72
details?readonlyunknown[] | null-WorkflowInputValidationError.detailsnode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:112
failure?publicIFailureThe original failure that constructed this error. Only present if this error was generated from an external operation.ApplicationFailure.failurenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:78
issuesreadonlyreadonly Issue[]--packages/worker/src/errors.ts:64
messagepublicstring-ApplicationFailure.messagenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
namepublicstring-ApplicationFailure.namenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
nextRetryDelay?readonlyany-WorkflowInputValidationError.nextRetryDelaynode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:113
nonRetryable?readonlyboolean | null-WorkflowInputValidationError.nonRetryablenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:111
stack?publicstring-ApplicationFailure.stacknode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
type?readonlystring | null-WorkflowInputValidationError.typenode_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:110
stackTraceLimitstaticnumberThe Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)). The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames.ApplicationFailure.stackTraceLimitnode_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:68

Methods ​

captureStackTrace() ​
ts
static captureStackTrace(targetObject, constructorOpt?): void;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:52

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

js
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

js
function a() {
  b();
}

function b() {
  c();
}

function c() {
  // Create an error without stack trace to avoid calculating the stack trace twice.
  const { stackTraceLimit } = Error;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = stackTraceLimit;

  // Capture the stack trace above function b
  Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
  throw error;
}

a();
Parameters ​
ParameterType
targetObjectobject
constructorOpt?Function
Returns ​

void

Inherited from ​

ApplicationFailure.captureStackTrace

create() ​
ts
static create(options): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:131

Create a new ApplicationFailure.

By default, will be retryable (unless its type is included in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterType
optionsApplicationFailureOptions
Returns ​

ApplicationFailure

Inherited from ​

ApplicationFailure.create

fromError() ​
ts
static fromError(error, overrides?): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:125

Create a new ApplicationFailure from an Error object.

First calls ensureApplicationFailure | `ensureApplicationFailure(error)` and then overrides any fields provided in overrides.

Parameters ​
ParameterType
errorunknown
overrides?ApplicationFailureOptions
Returns ​

ApplicationFailure

Inherited from ​

ApplicationFailure.fromError

nonRetryable() ​
ts
static nonRetryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:151

Get a new ApplicationFailure with the nonRetryable flag set to true.

When thrown from an Activity or Workflow, the Activity or Workflow will not be retried (even if type is not listed in RetryPolicy.nonRetryableErrorTypes).

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

Inherited from ​

ApplicationFailure.nonRetryable

prepareStackTrace() ​
ts
static prepareStackTrace(err, stackTraces): any;

Defined in: node_modules/.pnpm/@types+node@22.20.4/node_modules/@types/node/globals.d.ts:56

Parameters ​
ParameterType
errError
stackTracesCallSite[]
Returns ​

any

See ​

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from ​

ApplicationFailure.prepareStackTrace

retryable() ​
ts
static retryable(
   message?, 
   type?, 
   ...details
): ApplicationFailure;

Defined in: node_modules/.pnpm/@temporalio+common@1.24.0/node_modules/@temporalio/common/lib/failure.d.ts:140

Get a new ApplicationFailure with the nonRetryable flag set to false. Note that this error will still not be retried if its type is included in RetryPolicy.nonRetryableErrorTypes.

Parameters ​
ParameterTypeDescription
message?string | nullOptional error message
type?string | nullOptional error type (used by RetryPolicy.nonRetryableErrorTypes)
...details?unknown[]Optional details about the failure. Serialized by the Worker's PayloadConverter.
Returns ​

ApplicationFailure

Inherited from ​

ApplicationFailure.retryable

Type Aliases ​

ActivitiesHandler ​

ts
type ActivitiesHandler<TContract> = TContract["activities"] extends Record<string, ActivityDefinition> ? ActivitiesImplementations<TContract["activities"]> : object & UnionToIntersection<{ [TWorkflow in keyof TContract["workflows"]]: TContract["workflows"][TWorkflow]["activities"] extends Record<string, ActivityDefinition> ? ActivitiesImplementations<TContract["workflows"][TWorkflow]["activities"]> : {} }[keyof TContract["workflows"]]>;

Defined in: packages/worker/src/activity.ts:563

Activities handler ready for Temporal's Worker.create({ activities }).

Flat shape: every activity (global + all workflow-local) lives at the root of the returned map. See the doc comment on ContractResultActivitiesImplementations for why the input you write is nested by workflow while this output is flat.

Type Parameters ​

Type Parameter
TContract extends ContractDefinition

ActivityIdempotencyKeyOf ​

ts
type ActivityIdempotencyKeyOf<TActivity> = TActivity["idempotencyKey"] extends (input) => string ? string : undefined;

Defined in: packages/worker/src/activity.ts:334

string for an activity that declares idempotencyKey, undefined for one that does not.

Type Parameters ​

Type Parameter
TActivity extends ActivityDefinition

ActivityImplementationFor ​

ts
type ActivityImplementationFor<TContract, TWorkflowName, TActivityName, TContext> = TContract["workflows"][TWorkflowName]["activities"] extends Record<string, ActivityDefinition> ? ResultActivityImplementation<TContract["workflows"][TWorkflowName]["activities"][TActivityName], TContext> : never;

Defined in: packages/worker/src/activity.ts:461

The correctly-typed implementation function for one workflow-local activity of a contract. Lets a standalone implementation typecheck outside the declareActivitiesHandler call so it can live in its own module (with precise args/helpers inference) and be assigned into the nested implementations map later:

Type Parameters ​

Type ParameterDefault type
TContract extends ContractDefinition-
TWorkflowName extends keyof TContract["workflows"] & string-
TActivityName extends keyof TContract["workflows"][TWorkflowName]["activities"] & string-
TContext extends Record<string, unknown> | EmptyContextEmptyContext

Example ​

ts
const validateOrder: ActivityImplementationFor<
  typeof myContract,
  "orderWorkflow",
  "validateOrder"
> = ({ errors, input }) =>
  input.orderId ? OkAsync({ valid: true }) : ErrAsync(errors.EmptyOrder({}));

declareActivitiesHandler({
  contract: myContract,
  activities: { orderWorkflow: { validateOrder } },
});

The optional TContext parameter mirrors the handler's injected context (createContext seed + middleware accumulation); leave it defaulted when the implementation doesn't read helpers.context.

See GlobalActivityImplementationFor for the contract-global variant.


ActivityImplementationHelpers ​

ts
type ActivityImplementationHelpers<TActivity, TContext> = object;

Defined in: packages/worker/src/activity.ts:309

First argument passed to every activity implementation — everything the invocation carries, including its input.

  • errors — typed constructors for the errors declared on this activity's contract entry. Err(errors.PaymentDeclined({ reason })) surfaces to the calling workflow as a typed, schema-validated error.
  • context — the accumulated typed context: the createContext seed plus everything injected by the middleware chain via next({ context }) (an empty object when neither is configured). Use it to inject dependencies (service clients, repositories) instead of closing over them at module scope.
  • input — the validated input, the SAME value the second parameter carries. It is on the record so a whole implementation is one destructuring, which is oRPC's own shape and its own word for it (ProcedureHandlerOptions carries input, and the handler still takes it positionally). One name across the three transports is the point: a developer moving between them destructures input in each.

Type Parameters ​

Type ParameterDefault type
TActivity extends ActivityDefinition-
TContext extends Record<string, unknown> | EmptyContextEmptyContext

Properties ​

PropertyModifierTypeDescriptionDefined in
contextreadonlyTContext-packages/worker/src/activity.ts:314
errorsreadonlyActivityErrorConstructorsOf<TActivity>-packages/worker/src/activity.ts:313
idempotencyKeyreadonlyActivityIdempotencyKeyOf<TActivity>The activity's idempotency key for this invocation — string when the contract declares idempotencyKey, and undefined when it does not, so reaching for a key that was never declared is a type error rather than a silent undefined reaching a payment gateway. Derived from the validated input, verbatim. Stable across retries of this activity, across worker crashes, and across a fresh workflow execution with the same input — see idempotencyKey on the contract's defineActivity.packages/worker/src/activity.ts:327
inputreadonlyWorkerInferInput<TActivity>-packages/worker/src/activity.ts:315

ActivityInvocationInfo ​

ts
type ActivityInvocationInfo = object;

Defined in: packages/worker/src/middleware.ts:13

Per-invocation description handed to middleware and createContext.

Properties ​

PropertyModifierTypeDescriptionDefined in
activityNamereadonlystringFlat runtime name of the activity (as Temporal sees it).packages/worker/src/middleware.ts:15
workflowNamereadonlystring | undefinedOwning workflow for workflow-local activities; undefined for global ones. Shared-definition caveat: workflowName identifies the scope the implementation was registered under, not the workflow that is calling right now (Temporal's flat activity namespace erases the caller). When one defineActivity object is referenced from several scopes and implemented with the same function reference, the activity registers once under the first scope encountered — global first, then the contract's workflow declaration order — and every invocation reports that scope's workflowName. To know the actual calling workflow inside an activity, read Context.current().info.workflowType from @temporalio/activity. Standalone calls: a client's startActivity / executeActivity has no calling workflow at all, yet workflowName still reports the registration scope. Context.current().info.workflowExecution is undefined there; fall back to info.activityId.packages/worker/src/middleware.ts:36

ActivityMiddleware ​

ts
type ActivityMiddleware<TContextIn, TContextOut> = (invocation, next) => AsyncResult<unknown, 
  | ApplicationFailure
  | AnyContractError>;

Defined in: packages/worker/src/middleware.ts:115

Contract-aware middleware wrapped around every activity implementation.

Middleware runs inside the validation boundary — invocation.input is already validated against the contract's input schema, and whatever the chain returns on the ok channel is still validated against the output schema afterwards. Because it operates on the unthrown AsyncResult rather than thrown exceptions, a middleware observes modeled failures (ApplicationFailure, contract errors) on the err channel and can short-circuit by returning its own result without calling next.

Context accumulates through the chain: TContextIn is what this middleware receives (the createContext seed for the outermost one), TContextOut extends TContextIn is what it passes downstream via next({ context }). A middleware that only reads context leaves both parameters equal and stays valid unchanged. Compose typed chains with composeActivityMiddleware; pin a middleware's context types without a variable annotation via declareActivityMiddleware.

Type Parameters ​

Type ParameterDefault type
TContextIn extends Record<string, unknown> | EmptyContextEmptyContext
TContextOut extends TContextInTContextIn

Parameters ​

ParameterType
invocationActivityInvocationInfo & object
nextActivityMiddlewareNext<TContextOut>

Returns ​

AsyncResult<unknown, | ApplicationFailure | AnyContractError>

Examples ​

Log every activity invocation and its outcome (read-only)

ts
import { ApplicationFailure } from '@temporal-contract/worker/activity';
import { P } from "unthrown";

const logging: ActivityMiddleware = ({ activityName, workflowName }, next) =>
  next().tapErrCases((matcher) =>
    matcher.with(
      P.instanceOf(ApplicationFailure),
      P.tag("@temporal-contract/ContractError"),
      (error) => {
        logger.warn({ activityName, workflowName, error }, "activity failed");
      },
    ),
  );

Guard-and-narrow: inject a tenant id for everything downstream

ts
const auth = declareActivityMiddleware<EmptyContext, { tenantId: string }>(
  (invocation, next) => {
    const tenantId = readTenant(invocation.input);
    if (!tenantId) {
      return ErrAsync(ApplicationFailure.create({ type: "Unauthenticated", nonRetryable: true }));
    }
    return next({ context: { tenantId } });
  },
);

ActivityMiddlewareNext ​

ts
type ActivityMiddlewareNext<TContextOut> = (opts?) => AsyncResult<unknown, 
  | ApplicationFailure
  | AnyContractError>;

Defined in: packages/worker/src/middleware.ts:59

Continuation invoked by an ActivityMiddleware.

  • next() — forward unchanged.
  • next({ context: { ... } }) — extend the typed context flowing downstream; the patch is shallow-merged over the current context, so later middleware and the implementation see the accumulated value.
  • next({ input: ... }) — substitute the input. A substituted input is re-validated against the activity's input schema before it flows downstream — an invalid substitution fails terminally with ActivityInputValidationError, so middleware cannot smuggle unvalidated data past the contract boundary.

Type Parameters ​

Type ParameterDefault type
TContextOut extends Record<string, unknown> | EmptyContextEmptyContext

Parameters ​

ParameterType
opts?{ context?: TContextOut; input?: unknown; }
opts.context?TContextOut
opts.input?unknown

Returns ​

AsyncResult<unknown, | ApplicationFailure | AnyContractError>


AnyActivityMiddleware ​

ts
type AnyActivityMiddleware = ActivityMiddleware<Record<string, unknown>, Record<string, unknown>>;

Defined in: packages/worker/src/middleware.ts:131

Context-erased middleware shape used by the runtime chain.


AnyContractError ​

ts
type AnyContractError = ContractError<string, unknown>;

Defined in: packages/contract/dist/errors-impl-D7p9uupF.d.mts:63

Widest ContractError instantiation — useful as a constraint or for instanceof-style narrowing before discriminating on errorName.


ContractErrorConstructors ​

ts
type ContractErrorConstructors<TErrors> = { [K in keyof TErrors & string]: TErrors[K] extends { data: AnySchema } ? (data: InferErrorDataInput<TErrors[K]>, options?: ContractErrorOptions) => ContractError<K, InferErrorDataInput<TErrors[K]>> : (options?: ContractErrorOptions) => ContractError<K, undefined> };

Defined in: packages/contract/dist/errors-impl-D7p9uupF.d.mts:91

Map of typed error constructors for a declared errors map, handed to implementations (activity helpers / workflow context). Errors with a data schema take the payload first; data-less errors take only options.

Type Parameters ​

Type Parameter
TErrors extends Record<string, ErrorDefinition>

ContractErrorOptions ​

ts
type ContractErrorOptions = object;

Defined in: packages/contract/dist/errors-impl-D7p9uupF.d.mts:69

Per-instance options accepted by a typed error constructor. The nonRetryable flag is deliberately absent: retry semantics live on the contract's ErrorDefinition, not the call site.

Properties ​

PropertyModifierTypeDefined in
cause?readonlyunknownpackages/contract/dist/errors-impl-D7p9uupF.d.mts:71
message?readonlystringpackages/contract/dist/errors-impl-D7p9uupF.d.mts:70

DeclareActivitiesHandlerOptions ​

ts
type DeclareActivitiesHandlerOptions<TContract, TContext, TInjected> = object;

Defined in: packages/worker/src/activity.ts:497

Options for declareActivitiesHandler.

Type Parameters ​

Type ParameterDefault type
TContract extends ContractDefinition-
TContext extends Record<string, unknown> | EmptyContextEmptyContext
TInjected extends TContextTContext

Properties ​

PropertyTypeDescriptionDefined in
activitiesNoInfer<ContractResultActivitiesImplementations<TContract, TInjected>>Nested implementations map mirroring the contract's structure — see ContractResultActivitiesImplementations. Wrapped in NoInfer so TContract/TInjected are inferred from contract/middleware only: letting TypeScript infer into the key-remapped mapped type breaks contextual typing of the implementation lambdas (their args degrade to implicit any).packages/worker/src/activity.ts:512
contractTContract-packages/worker/src/activity.ts:502
createContext?(info) => TContext | Promise<TContext>Build the typed dependency context seed handed to the middleware chain and, accumulated, to every implementation as helpers.context. Invoked once per activity execution, so it can produce request-scoped values; close over singletons (DB pools, service clients) for per-worker dependencies. Omitted → the seed is an empty object. For scoped, resource-releasing contexts (per-invocation loggers, transactions), the recommended implementation is demesne's Layer.forkScope — see the "Dependency Injection" section of the activity-handlers guide.packages/worker/src/activity.ts:525
middleware?ActivityMiddleware<TContext, TInjected>Contract-aware middleware wrapped around every activity implementation. Pass a single middleware, or a typed chain built with composeActivityMiddleware — the chain's final context type (TInjected) is what implementations receive as helpers.context. See ActivityMiddleware.packages/worker/src/activity.ts:533

EmptyContext ​

ts
type EmptyContext = Record<never, never>;

Defined in: packages/worker/src/middleware.ts:44

The empty middleware context. Record<never, never> rather than {} so an empty context is a real "no properties" type instead of the anything-goes empty-object type. (Mirrors amqp-contract's EmptyContext.)


GlobalActivityImplementationFor ​

ts
type GlobalActivityImplementationFor<TContract, TActivityName, TContext> = TContract["activities"] extends Record<string, ActivityDefinition> ? ResultActivityImplementation<TContract["activities"][TActivityName], TContext> : never;

Defined in: packages/worker/src/activity.ts:485

The correctly-typed implementation function for one global activity of a contract — the contract.activities-scoped sibling of ActivityImplementationFor.

Type Parameters ​

Type ParameterDefault type
TContract extends ContractDefinition-
TActivityName extends keyof TContract["activities"] & string-
TContext extends Record<string, unknown> | EmptyContextEmptyContext

Example ​

ts
const sendEmail: GlobalActivityImplementationFor<typeof myContract, "sendEmail"> =
  ({ input: args }) => OkAsync({ sent: true });

QualifyFailureOptions ​

ts
type QualifyFailureOptions = object;

Defined in: packages/worker/src/activity.ts:107

Options for qualifyFailure. expected is required — it is the triage decision that separates modeled failures from defects.

Properties ​

PropertyTypeDescriptionDefined in
details?unknown[]Structured payload forwarded to the workflow (avoids parsing message).packages/worker/src/activity.ts:135
expectedErrorClass | readonly ErrorClass[] | ((cause) => boolean) | "any"Which rejection causes are anticipated and should be wrapped into the modeled ApplicationFailure: - an error-class constructor (matched with instanceof), - an array of error-class constructors (any match wraps), - a predicate (cause: unknown) => boolean, - the literal "any" — a deliberate, greppable escape hatch that wraps every rejection (the pre-v8 blanket behavior). Anything that doesn't match rides unthrown's defect channel instead: an unanticipated throw (a TypeError from a bug, an assertion failure) is not a domain outcome, and blanket-wrapping it would disguise the bug as the declared failure type and subject it to that type's retry semantics.packages/worker/src/activity.ts:124
message?stringFallback message when the rejection is not an Error (default: String(error)).packages/worker/src/activity.ts:126
nonRetryable?booleanMark the failure non-retryable — Temporal stops retrying immediately. When omitted, a matched cause that is itself an ApplicationFailure with nonRetryable: true propagates its non-retryability (see remarks); set false explicitly to force the wrapped failure retryable.packages/worker/src/activity.ts:133

Variables ​

ACTIVITY_CANCELLED_ERROR_TAG ​

ts
const ACTIVITY_CANCELLED_ERROR_TAG: "@temporal-contract/ActivityCancelledError" = "@temporal-contract/ActivityCancelledError";

Defined in: packages/worker/src/error-tags.ts:24

_tag of ActivityCancelledError — a call to an activity was cancelled.


ACTIVITY_DEFINITION_NOT_FOUND_ERROR_TAG ​

ts
const ACTIVITY_DEFINITION_NOT_FOUND_ERROR_TAG: "@temporal-contract/ActivityDefinitionNotFoundError" = "@temporal-contract/ActivityDefinitionNotFoundError";

Defined in: packages/worker/src/error-tags.ts:27

_tag of ActivityDefinitionNotFoundError — an implementation was supplied for an undeclared activity.


ACTIVITY_ERROR_TAG ​

ts
const ACTIVITY_ERROR_TAG: "@temporal-contract/ActivityError" = "@temporal-contract/ActivityError";

Defined in: packages/worker/src/error-tags.ts:21

_tag of ActivityError — an activity call failed for a reason other than a declared contract error.


CHILD_WORKFLOW_CANCELLED_ERROR_TAG ​

ts
const CHILD_WORKFLOW_CANCELLED_ERROR_TAG: "@temporal-contract/ChildWorkflowCancelledError" = "@temporal-contract/ChildWorkflowCancelledError";

Defined in: packages/worker/src/error-tags.ts:34

_tag of ChildWorkflowCancelledError — a child-workflow operation was cancelled.


CHILD_WORKFLOW_ERROR_TAG ​

ts
const CHILD_WORKFLOW_ERROR_TAG: "@temporal-contract/ChildWorkflowError" = "@temporal-contract/ChildWorkflowError";

Defined in: packages/worker/src/error-tags.ts:31

_tag of ChildWorkflowError — a child-workflow operation failed.


CHILD_WORKFLOW_NOT_FOUND_ERROR_TAG ​

ts
const CHILD_WORKFLOW_NOT_FOUND_ERROR_TAG: "@temporal-contract/ChildWorkflowNotFoundError" = "@temporal-contract/ChildWorkflowNotFoundError";

Defined in: packages/worker/src/error-tags.ts:37

_tag of ChildWorkflowNotFoundError — the child workflow isn't declared on the contract.


WORKFLOW_CANCELLED_ERROR_TAG ​

ts
const WORKFLOW_CANCELLED_ERROR_TAG: "@temporal-contract/WorkflowCancelledError" = "@temporal-contract/WorkflowCancelledError";

Defined in: packages/worker/src/error-tags.ts:40

_tag of WorkflowCancelledError — a typed cancellation scope was cancelled.

Functions ​

composeActivityMiddleware() ​

Call Signature ​

ts
function composeActivityMiddleware<TSeed, TA>(m1): ActivityMiddleware<TSeed, TA>;

Defined in: packages/worker/src/middleware.ts:159

Compose middleware outermost-first into a single ActivityMiddleware whose context type accumulates across the chain — each middleware's TContextOut bounds the next one's TContextIn, so the composed result's out-context is the last middleware's. For chains longer than eight, nest: a composed chain is itself an ActivityMiddleware and can be the first argument of an outer composeActivityMiddleware call.

(Mirrors amqp-contract's composeMiddleware overload approach.)

Type Parameters ​
Type Parameter
TSeed extends Record<string, unknown> | EmptyContext
TA extends Record<string, unknown> | EmptyContext
Parameters ​
ParameterType
m1ActivityMiddleware<TSeed, TA>
Returns ​

ActivityMiddleware<TSeed, TA>

Call Signature ​

ts
function composeActivityMiddleware<TSeed, TA, TB>(m1, m2): ActivityMiddleware<TSeed, TB>;

Defined in: packages/worker/src/middleware.ts:163

Compose middleware outermost-first into a single ActivityMiddleware whose context type accumulates across the chain — each middleware's TContextOut bounds the next one's TContextIn, so the composed result's out-context is the last middleware's. For chains longer than eight, nest: a composed chain is itself an ActivityMiddleware and can be the first argument of an outer composeActivityMiddleware call.

(Mirrors amqp-contract's composeMiddleware overload approach.)

Type Parameters ​
Type Parameter
TSeed extends Record<string, unknown> | EmptyContext
TA extends Record<string, unknown> | EmptyContext
TB extends Record<string, unknown> | EmptyContext
Parameters ​
ParameterType
m1ActivityMiddleware<TSeed, TA>
m2ActivityMiddleware<TA, TB>
Returns ​

ActivityMiddleware<TSeed, TB>

Call Signature ​

ts
function composeActivityMiddleware<TSeed, TA, TB, TC>(
   m1, 
   m2, 
   m3
): ActivityMiddleware<TSeed, TC>;

Defined in: packages/worker/src/middleware.ts:168

Compose middleware outermost-first into a single ActivityMiddleware whose context type accumulates across the chain — each middleware's TContextOut bounds the next one's TContextIn, so the composed result's out-context is the last middleware's. For chains longer than eight, nest: a composed chain is itself an ActivityMiddleware and can be the first argument of an outer composeActivityMiddleware call.

(Mirrors amqp-contract's composeMiddleware overload approach.)

Type Parameters ​
Type Parameter
TSeed extends Record<string, unknown> | EmptyContext
TA extends Record<string, unknown> | EmptyContext
TB extends Record<string, unknown> | EmptyContext
TC extends Record<string, unknown> | EmptyContext
Parameters ​
ParameterType
m1ActivityMiddleware<TSeed, TA>
m2ActivityMiddleware<TA, TB>
m3ActivityMiddleware<TB, TC>
Returns ​

ActivityMiddleware<TSeed, TC>

Call Signature ​

ts
function composeActivityMiddleware<TSeed, TA, TB, TC, TD>(
   m1, 
   m2, 
   m3, 
   m4
): ActivityMiddleware<TSeed, TD>;

Defined in: packages/worker/src/middleware.ts:178

Compose middleware outermost-first into a single ActivityMiddleware whose context type accumulates across the chain — each middleware's TContextOut bounds the next one's TContextIn, so the composed result's out-context is the last middleware's. For chains longer than eight, nest: a composed chain is itself an ActivityMiddleware and can be the first argument of an outer composeActivityMiddleware call.

(Mirrors amqp-contract's composeMiddleware overload approach.)

Type Parameters ​
Type Parameter
TSeed extends Record<string, unknown> | EmptyContext
TA extends Record<string, unknown> | EmptyContext
TB extends Record<string, unknown> | EmptyContext
TC extends Record<string, unknown> | EmptyContext
TD extends Record<string, unknown> | EmptyContext
Parameters ​
ParameterType
m1ActivityMiddleware<TSeed, TA>
m2ActivityMiddleware<TA, TB>
m3ActivityMiddleware<TB, TC>
m4ActivityMiddleware<TC, TD>
Returns ​

ActivityMiddleware<TSeed, TD>

Call Signature ​

ts
function composeActivityMiddleware<TSeed, TA, TB, TC, TD, TE>(
   m1, 
   m2, 
   m3, 
   m4, 
   m5
): ActivityMiddleware<TSeed, TE>;

Defined in: packages/worker/src/middleware.ts:190

Compose middleware outermost-first into a single ActivityMiddleware whose context type accumulates across the chain — each middleware's TContextOut bounds the next one's TContextIn, so the composed result's out-context is the last middleware's. For chains longer than eight, nest: a composed chain is itself an ActivityMiddleware and can be the first argument of an outer composeActivityMiddleware call.

(Mirrors amqp-contract's composeMiddleware overload approach.)

Type Parameters ​
Type Parameter
TSeed extends Record<string, unknown> | EmptyContext
TA extends Record<string, unknown> | EmptyContext
TB extends Record<string, unknown> | EmptyContext
TC extends Record<string, unknown> | EmptyContext
TD extends Record<string, unknown> | EmptyContext
TE extends Record<string, unknown> | EmptyContext
Parameters ​
ParameterType
m1ActivityMiddleware<TSeed, TA>
m2ActivityMiddleware<TA, TB>
m3ActivityMiddleware<TB, TC>
m4ActivityMiddleware<TC, TD>
m5ActivityMiddleware<TD, TE>
Returns ​

ActivityMiddleware<TSeed, TE>

Call Signature ​

ts
function composeActivityMiddleware<TSeed, TA, TB, TC, TD, TE, TF>(
   m1, 
   m2, 
   m3, 
   m4, 
   m5, 
   m6
): ActivityMiddleware<TSeed, TF>;

Defined in: packages/worker/src/middleware.ts:204

Compose middleware outermost-first into a single ActivityMiddleware whose context type accumulates across the chain — each middleware's TContextOut bounds the next one's TContextIn, so the composed result's out-context is the last middleware's. For chains longer than eight, nest: a composed chain is itself an ActivityMiddleware and can be the first argument of an outer composeActivityMiddleware call.

(Mirrors amqp-contract's composeMiddleware overload approach.)

Type Parameters ​
Type Parameter
TSeed extends Record<string, unknown> | EmptyContext
TA extends Record<string, unknown> | EmptyContext
TB extends Record<string, unknown> | EmptyContext
TC extends Record<string, unknown> | EmptyContext
TD extends Record<string, unknown> | EmptyContext
TE extends Record<string, unknown> | EmptyContext
TF extends Record<string, unknown> | EmptyContext
Parameters ​
ParameterType
m1ActivityMiddleware<TSeed, TA>
m2ActivityMiddleware<TA, TB>
m3ActivityMiddleware<TB, TC>
m4ActivityMiddleware<TC, TD>
m5ActivityMiddleware<TD, TE>
m6ActivityMiddleware<TE, TF>
Returns ​

ActivityMiddleware<TSeed, TF>

Call Signature ​

ts
function composeActivityMiddleware<TSeed, TA, TB, TC, TD, TE, TF, TG>(
   m1, 
   m2, 
   m3, 
   m4, 
   m5, 
   m6, 
   m7
): ActivityMiddleware<TSeed, TG>;

Defined in: packages/worker/src/middleware.ts:220

Compose middleware outermost-first into a single ActivityMiddleware whose context type accumulates across the chain — each middleware's TContextOut bounds the next one's TContextIn, so the composed result's out-context is the last middleware's. For chains longer than eight, nest: a composed chain is itself an ActivityMiddleware and can be the first argument of an outer composeActivityMiddleware call.

(Mirrors amqp-contract's composeMiddleware overload approach.)

Type Parameters ​
Type Parameter
TSeed extends Record<string, unknown> | EmptyContext
TA extends Record<string, unknown> | EmptyContext
TB extends Record<string, unknown> | EmptyContext
TC extends Record<string, unknown> | EmptyContext
TD extends Record<string, unknown> | EmptyContext
TE extends Record<string, unknown> | EmptyContext
TF extends Record<string, unknown> | EmptyContext
TG extends Record<string, unknown> | EmptyContext
Parameters ​
ParameterType
m1ActivityMiddleware<TSeed, TA>
m2ActivityMiddleware<TA, TB>
m3ActivityMiddleware<TB, TC>
m4ActivityMiddleware<TC, TD>
m5ActivityMiddleware<TD, TE>
m6ActivityMiddleware<TE, TF>
m7ActivityMiddleware<TF, TG>
Returns ​

ActivityMiddleware<TSeed, TG>

Call Signature ​

ts
function composeActivityMiddleware<TSeed, TA, TB, TC, TD, TE, TF, TG, TH>(
   m1, 
   m2, 
   m3, 
   m4, 
   m5, 
   m6, 
   m7, 
   m8
): ActivityMiddleware<TSeed, TH>;

Defined in: packages/worker/src/middleware.ts:238

Compose middleware outermost-first into a single ActivityMiddleware whose context type accumulates across the chain — each middleware's TContextOut bounds the next one's TContextIn, so the composed result's out-context is the last middleware's. For chains longer than eight, nest: a composed chain is itself an ActivityMiddleware and can be the first argument of an outer composeActivityMiddleware call.

(Mirrors amqp-contract's composeMiddleware overload approach.)

Type Parameters ​
Type Parameter
TSeed extends Record<string, unknown> | EmptyContext
TA extends Record<string, unknown> | EmptyContext
TB extends Record<string, unknown> | EmptyContext
TC extends Record<string, unknown> | EmptyContext
TD extends Record<string, unknown> | EmptyContext
TE extends Record<string, unknown> | EmptyContext
TF extends Record<string, unknown> | EmptyContext
TG extends Record<string, unknown> | EmptyContext
TH extends Record<string, unknown> | EmptyContext
Parameters ​
ParameterType
m1ActivityMiddleware<TSeed, TA>
m2ActivityMiddleware<TA, TB>
m3ActivityMiddleware<TB, TC>
m4ActivityMiddleware<TC, TD>
m5ActivityMiddleware<TD, TE>
m6ActivityMiddleware<TE, TF>
m7ActivityMiddleware<TF, TG>
m8ActivityMiddleware<TG, TH>
Returns ​

ActivityMiddleware<TSeed, TH>


declareActivitiesHandler() ​

ts
function declareActivitiesHandler<TContract, TContext, TInjected>(options): ActivitiesHandler<TContract>;

Defined in: packages/worker/src/activity.ts:668

Create a typed activities handler with automatic validation and Result pattern.

This wraps all activity implementations with:

  • Validation at network boundaries
  • AsyncResult<T, ApplicationFailure | declared errors> pattern for explicit error handling
  • Automatic conversion from Result to Promise (throwing on Error)
  • Typed constructors for contract-declared errors and an optional dependency context (see ActivityImplementationHelpers)
  • An optional contract-aware middleware chain (see ActivityMiddleware)

TypeScript ensures ALL activities (global + workflow-specific) are implemented.

Use this to create the activities object for the Temporal Worker.

Type Parameters ​

Type ParameterDefault type
TContract extends ContractDefinition-
TContext extends Record<string, unknown> | EmptyContextEmptyContext
TInjected extends Record<string, unknown> | EmptyContextTContext

Parameters ​

ParameterType
optionsDeclareActivitiesHandlerOptions<TContract, TContext, TInjected>

Returns ​

ActivitiesHandler<TContract>

Example ​

ts
import { declareActivitiesHandler, ApplicationFailure } from '@temporal-contract/worker/activity';
import { fromPromise, Ok, Err } from 'unthrown';
import { myContract } from './contract.js';

export const activities = declareActivitiesHandler({
  contract: myContract,
  // Typed dependency injection: implementations receive this via
  // `helpers.context` instead of closing over module state.
  createContext: () => ({ emailService }),
  activities: {
    // Activity returns AsyncResult instead of throwing.
    sendEmail: ({ errors, context, input }) =>
      fromPromise(
        context.emailService.send(input),
        (error) =>
          // Wrap technical errors in ApplicationFailure. `nonRetryable`
          // is per-instance: set it to true on permanent failures so
          // Temporal stops retrying immediately. Note the conditional
          // spread for `cause` — under `exactOptionalPropertyTypes`,
          // omit the key entirely rather than passing `undefined`.
          ApplicationFailure.create({
            type: 'EMAIL_SEND_FAILED',
            message: 'Failed to send email',
            nonRetryable: false,
            ...(error instanceof Error ? { cause: error } : {}),
          }),
      ).flatMap((outcome) =>
        outcome.accepted
          ? Ok({ sent: true })
          : // Contract-declared error: typed on the caller's side, with
            // `nonRetryable` taken from the contract declaration.
            Err(errors.RecipientRejected({ reason: outcome.reason })),
      ),
  },
});

// Wire into a worker with this package's typed factory — the task queue
// comes from the contract.
import { NativeConnection } from '@temporalio/worker';
import { TypedWorker, workflowsPathFromURL } from '@temporal-contract/worker/worker';

const connection = await NativeConnection.connect({ address: 'localhost:7233' });
const worker = await TypedWorker.create({
  contract: myContract,
  connection,
  workflowsPath: workflowsPathFromURL(import.meta.url, './workflows.js'),
  activities,
}).get();

Remarks ​

The wrapper accepts implementations in the AsyncResult<T, ApplicationFailure | declared errors> shape and produces ordinary Promise-returning Temporal handlers (Err(ApplicationFailure) → thrown; Err(ContractError) → data validated against the declared schema and thrown as an ApplicationFailure with type = error name, details[0] = data, nonRetryable from the contract; Ok(...) → output validated against the contract, then resolved with the implementation's original value — the calling side parses it on receive; defect → original cause re-thrown). It does not hide Temporal's @temporalio/activity runtime: inside the body you can still call Context.current() from @temporalio/activity to access heartbeats (heartbeat(details), heartbeatDetails), activity info (attempt number, workflow IDs), and the async-completion task token. See the "Working with the Activity Context" section of the worker implementation guide for end-to-end examples.


declareActivityMiddleware() ​

ts
function declareActivityMiddleware<TContextIn, TContextOut>(middleware): ActivityMiddleware<TContextIn, TContextOut>;

Defined in: packages/worker/src/middleware.ts:140

Identity helper that pins a middleware's context types without a variable annotation. (Mirrors amqp-contract's defineMiddleware.)

Type Parameters ​

Type ParameterDefault type
TContextIn extends Record<string, unknown> | EmptyContextEmptyContext
TContextOut extends Record<string, unknown> | EmptyContextTContextIn

Parameters ​

ParameterType
middlewareActivityMiddleware<TContextIn, TContextOut>

Returns ​

ActivityMiddleware<TContextIn, TContextOut>


qualifyFailure() ​

ts
function qualifyFailure(errorType, options): <TDefect>(cause, defect) => TDefect | ApplicationFailure;

Defined in: packages/worker/src/activity.ts:242

Build a qualifier for fromPromise that triages each rejection: causes matching options.expected are wrapped in a modeled ApplicationFailure of the given errorType; everything else goes to unthrown's defect channel.

Triage philosophy: fromPromise's qualify step exists to force a per-cause decision — is this failure part of the activity's model, or a bug? A qualifier that wraps everything erases that decision: a TypeError from a typo would surface as, say, EMAIL_SEND_FAILED and inherit its retry semantics, hiding the defect from operators and from the defect channel's fail-loud handling. expected is therefore required: name the failure classes (or predicate) you anticipate; let the rest stay defects that re-throw at the activity edge with their original cause. The literal expected: "any" remains as an explicit, greppable escape hatch for the old blanket behavior.

For a matched Error cause, the wrapper keeps the cause's own message and preserves it as cause (so stack traces survive the activity → workflow boundary); a matched non-Error cause falls back to options.message (or String(cause)).

A cancellation (CancelledFailure, AbortError) is never wrapped — it always rides the defect channel, so it still reaches Temporal as a cancellation.

Parameters ​

ParameterType
errorTypestring
optionsQualifyFailureOptions

Returns ​

<TDefect>(cause, defect) => TDefect | ApplicationFailure

Example ​

ts
import { declareActivitiesHandler, qualifyFailure } from '@temporal-contract/worker/activity';
import { fromPromise } from 'unthrown';

export const activities = declareActivitiesHandler({
  contract: myContract,
  activities: {
    sendEmail: ({ input: args }) =>
      fromPromise(
        emailService.send(args),
        // Anticipated: the SDK's typed error. Anything else (TypeError,
        // assertion failure, ...) is a defect and re-throws at the edge.
        qualifyFailure('EMAIL_SEND_FAILED', { expected: EmailServiceError }),
      ).map(() => ({ sent: true })),
    chargeCard: ({ input: args }) =>
      fromPromise(
        paymentGateway.charge(args),
        qualifyFailure('CARD_DECLINED', {
          // Several anticipated classes; a predicate works too.
          expected: [CardDeclinedError, GatewayTimeoutError],
          // Permanent failure: opt out of the configured retry policy.
          nonRetryable: true,
        }),
      ),
  },
});

Remarks ​

A matched cause is always wrapped — even when it is already an ApplicationFailure — so the resulting failure's type is guaranteed to be the declared one (retry policies keyed on retry.nonRetryableErrorTypes can rely on it), with the original failure preserved as cause. Retryability of the wrapper: when options.nonRetryable is set it wins unconditionally; when it is omitted and the matched cause is an ApplicationFailure with nonRetryable: true, the wrapper inherits nonRetryable: true (a permanent inner failure no longer silently becomes retryable just because it was re-typed).

Released under the MIT License.