Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@temporalio/workflow

Package Overview
Dependencies
Maintainers
8
Versions
81
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@temporalio/workflow - npm Package Compare versions

Comparing version 1.7.4 to 1.8.0

3

lib/cancellation-scope.d.ts
/// <reference types="node" />
import type { AsyncLocalStorage as ALS } from 'node:async_hooks';
import { Duration } from '@temporalio/common';
export declare const AsyncLocalStorage: new <T>() => ALS<T>;

@@ -121,4 +122,4 @@ /** Magic symbol used to create the root scope - intentionally not exported */

/** This function is here to avoid a circular dependency between this module and workflow.ts */
declare let sleep: (_: number | string) => Promise<void>;
declare let sleep: (_: Duration) => Promise<void>;
export declare function registerSleepImplementation(fn: typeof sleep): void;
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCancellation = exports.DeterminismViolationError = exports.WorkflowError = void 0;
const common_1 = require("@temporalio/common");
/**

@@ -24,5 +25,2 @@ * Base class for all workflow errors

exports.DeterminismViolationError = DeterminismViolationError;
function looksLikeError(err) {
return typeof err === 'object' && err != null && Object.prototype.hasOwnProperty.call(err, 'name');
}
/**

@@ -32,10 +30,6 @@ * Returns whether provided `err` is caused by cancellation

function isCancellation(err) {
if (!looksLikeError(err))
return false;
return (err.name === 'CancelledFailure' ||
((err.name === 'ActivityFailure' || err.name === 'ChildWorkflowFailure') &&
looksLikeError(err.cause) &&
err.cause.name === 'CancelledFailure'));
return (common_1.CancelledFailure.is(err) ||
((common_1.ActivityFailure.is(err) || common_1.ChildWorkflowFailure.is(err)) && common_1.CancelledFailure.is(err.cause)));
}
exports.isCancellation = isCancellation;
//# sourceMappingURL=errors.js.map
import type { RawSourceMap } from 'source-map';
import { RetryPolicy, TemporalFailure, CommonWorkflowOptions, SearchAttributes, SignalDefinition, QueryDefinition } from '@temporalio/common';
import { RetryPolicy, TemporalFailure, CommonWorkflowOptions, SearchAttributes, SignalDefinition, QueryDefinition, Duration } from '@temporalio/common';
import type { coresdk } from '@temporalio/proto';

@@ -131,2 +131,3 @@ /**

}
declare const isContinueAsNew: unique symbol;
/**

@@ -139,2 +140,10 @@ * Not an actual error, used by the Workflow runtime to abort execution when {@link continueAsNew} is called

constructor(command: coresdk.workflow_commands.IContinueAsNewWorkflowExecution);
/**
* Marker to determine whether an error is an instance of ContinueAsNew.
*/
protected readonly [isContinueAsNew] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/workflow are installed.
*/
static is(error: unknown): error is ContinueAsNew;
}

@@ -157,3 +166,3 @@ /**

*/
workflowRunTimeout?: string;
workflowRunTimeout?: Duration;
/**

@@ -163,3 +172,3 @@ * Timeout for a single Workflow task

*/
workflowTaskTimeout?: string;
workflowTaskTimeout?: Duration;
/**

@@ -325,4 +334,6 @@ * Non-searchable attributes to attach to next Workflow run

}
export interface WorkflowCreateOptionsWithSourceMap extends WorkflowCreateOptions {
export interface WorkflowCreateOptionsInternal extends WorkflowCreateOptions {
sourceMap: RawSourceMap;
registeredActivityNames: Set<string>;
getTimeOfDay(): bigint;
}

@@ -337,1 +348,2 @@ /**

export type DefaultSignalHandler = (signalName: string, ...args: unknown[]) => void | Promise<void>;
export {};
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParentClosePolicy = exports.ChildWorkflowCancellationType = exports.ContinueAsNew = void 0;
const type_helpers_1 = require("@temporalio/common/lib/type-helpers");
const isContinueAsNew = Symbol.for('__temporal_isContinueAsNew');
/**

@@ -13,5 +15,16 @@ * Not an actual error, used by the Workflow runtime to abort execution when {@link continueAsNew} is called

this.name = 'ContinueAsNew';
/**
* Marker to determine whether an error is an instance of ContinueAsNew.
*/
this[_a] = true;
}
/**
* Instanceof check that works when multiple versions of @temporalio/workflow are installed.
*/
static is(error) {
return error instanceof ContinueAsNew || (error instanceof Error && error[isContinueAsNew]);
}
}
exports.ContinueAsNew = ContinueAsNew;
_a = isContinueAsNew;
/**

@@ -18,0 +31,0 @@ * Specifies:

@@ -7,3 +7,3 @@ import type { RawSourceMap } from 'source-map';

import { QueryInput, SignalInput, WorkflowExecuteInput, WorkflowInterceptors } from './interceptors';
import { DefaultSignalHandler, FileLocation, WorkflowInfo, WorkflowCreateOptionsWithSourceMap } from './interfaces';
import { DefaultSignalHandler, FileLocation, WorkflowInfo, WorkflowCreateOptionsInternal } from './interfaces';
import { SinkCall } from './sinks';

@@ -167,4 +167,12 @@ export interface Stack {

readonly sentPatches: Set<string>;
/**
* Buffered sink calls per activation
*/
sinkCalls: SinkCall[];
constructor({ info, now, showStackTraceSources, sourceMap, randomnessSeed, patches, }: WorkflowCreateOptionsWithSourceMap);
/**
* A nanosecond resolution time function, externally injected
*/
readonly getTimeOfDay: () => bigint;
readonly registeredActivityNames: Set<string>;
constructor({ info, now, showStackTraceSources, sourceMap, getTimeOfDay, randomnessSeed, patches, registeredActivityNames, }: WorkflowCreateOptionsInternal);
protected getStackTraces(): Stack[];

@@ -171,0 +179,0 @@ getAndResetSinkCalls(): SinkCall[];

@@ -40,3 +40,3 @@ "use strict";

class Activator {
constructor({ info, now, showStackTraceSources, sourceMap, randomnessSeed, patches, }) {
constructor({ info, now, showStackTraceSources, sourceMap, getTimeOfDay, randomnessSeed, patches, registeredActivityNames, }) {
/**

@@ -171,3 +171,7 @@ * Cache for modules - referenced in reusable-vm.ts

this.sentPatches = new Set();
/**
* Buffered sink calls per activation
*/
this.sinkCalls = Array();
this.getTimeOfDay = getTimeOfDay;
this.info = info;

@@ -178,2 +182,3 @@ this.now = now;

this.random = (0, alea_1.alea)(randomnessSeed);
this.registeredActivityNames = registeredActivityNames;
if (info.unsafe.isReplaying) {

@@ -465,7 +470,7 @@ for (const patchId of patches) {

}
else if (error instanceof interfaces_1.ContinueAsNew) {
else if (interfaces_1.ContinueAsNew.is(error)) {
this.pushCommand({ continueAsNewWorkflowExecution: error.command }, true);
}
else {
if (!(error instanceof common_1.TemporalFailure)) {
if (!common_1.TemporalFailure.is(error)) {
// This results in an unhandled rejection which will fail the activation

@@ -472,0 +477,0 @@ // preventing it from completing.

import type { coresdk } from '@temporalio/proto';
import { WorkflowCreateOptionsWithSourceMap } from './interfaces';
import { WorkflowCreateOptionsInternal } from './interfaces';
import { SinkCall } from './sinks';

@@ -11,3 +11,3 @@ export { PromiseStackStore } from './internals';

*/
export declare function initRuntime(options: WorkflowCreateOptionsWithSourceMap): void;
export declare function initRuntime(options: WorkflowCreateOptionsInternal): void;
/**

@@ -14,0 +14,0 @@ * Run a chunk of activation jobs

@@ -118,8 +118,8 @@ "use strict";

const workflowFn = mod[info.workflowType];
const defaultWorfklowFn = mod['default'];
const defaultWorkflowFn = mod['default'];
if (typeof workflowFn === 'function') {
activator.workflow = workflowFn;
}
else if (typeof defaultWorfklowFn === 'function') {
activator.workflow = defaultWorfklowFn;
else if (typeof defaultWorkflowFn === 'function') {
activator.workflow = defaultWorkflowFn;
}

@@ -126,0 +126,0 @@ else {

import { ActivityFunction, ActivityOptions, LocalActivityOptions, QueryDefinition, SearchAttributes, SignalDefinition, UntypedActivities, WithWorkflowArgs, Workflow, WorkflowResultType, WorkflowReturnType } from '@temporalio/common';
import { Duration } from '@temporalio/common/lib/time';
import { ChildWorkflowOptions, ChildWorkflowOptionsWithDefaults, ContinueAsNewOptions, DefaultSignalHandler, EnhancedStackTrace, Handler, WorkflowInfo } from './interfaces';
import { Sinks } from './sinks';
import { LoggerSinks, Sinks } from './sinks';
import { ChildWorkflowHandle, ExternalWorkflowHandle } from './workflow-handle';

@@ -17,3 +18,3 @@ /**

*/
export declare function sleep(ms: number | string): Promise<void>;
export declare function sleep(ms: Duration): Promise<void>;
/**

@@ -346,3 +347,3 @@ * Schedule an activity and run outbound interceptors

*/
export declare function condition(fn: () => boolean, timeout: number | string): Promise<boolean>;
export declare function condition(fn: () => boolean, timeout: Duration): Promise<boolean>;
/**

@@ -417,1 +418,15 @@ * Returns a Promise that resolves when `fn` evaluates to `true`.

export declare const enhancedStackTraceQuery: QueryDefinition<EnhancedStackTrace, [], string>;
/**
* Default workflow logger.
* This logger is replay-aware and will omit log messages on workflow replay.
* The messages emitted by this logger are funnelled to the worker's `defaultSinks`, which are installed by default.
*
* Note that since sinks are used to power this logger, any log attributes must be transferable via the
* {@link https://nodejs.org/api/worker_threads.html#worker_threads_port_postmessage_value_transferlist | postMessage}
* API.
*
* `defaultSinks` accepts a user logger and defaults to the `Runtime`'s logger.
*
* See the documentation for `WorkerOptions`, `defaultSinks`, and `Runtime` for more information.
*/
export declare const log: LoggerSinks['defaultWorkerLogger'];
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.enhancedStackTraceQuery = exports.stackTraceQuery = exports.upsertSearchAttributes = exports.setDefaultSignalHandler = exports.setHandler = exports.defineQuery = exports.defineSignal = exports.condition = exports.deprecatePatch = exports.patched = exports.uuid4 = exports.continueAsNew = exports.makeContinueAsNewFunc = exports.proxySinks = exports.inWorkflowContext = exports.workflowInfo = exports.executeChild = exports.startChild = exports.getExternalWorkflowHandle = exports.proxyLocalActivities = exports.proxyActivities = exports.NotAnActivityMethod = exports.scheduleLocalActivity = exports.scheduleActivity = exports.sleep = exports.addDefaultWorkflowOptions = void 0;
exports.log = exports.enhancedStackTraceQuery = exports.stackTraceQuery = exports.upsertSearchAttributes = exports.setDefaultSignalHandler = exports.setHandler = exports.defineQuery = exports.defineSignal = exports.condition = exports.deprecatePatch = exports.patched = exports.uuid4 = exports.continueAsNew = exports.makeContinueAsNewFunc = exports.proxySinks = exports.inWorkflowContext = exports.workflowInfo = exports.executeChild = exports.startChild = exports.getExternalWorkflowHandle = exports.proxyLocalActivities = exports.proxyActivities = exports.NotAnActivityMethod = exports.scheduleLocalActivity = exports.scheduleActivity = exports.sleep = exports.addDefaultWorkflowOptions = void 0;
const common_1 = require("@temporalio/common");

@@ -71,3 +71,3 @@ const time_1 = require("@temporalio/common/lib/time");

function sleep(ms) {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Workflow.sleep(...) may only be used from a Workflow Execution');
const seq = activator.nextSeqs.timer++;

@@ -146,2 +146,7 @@ const durationMs = Math.max(1, (0, time_1.msToNumber)(ms));

const activator = (0, internals_1.getActivator)();
// Eagerly fail the local activity (which will in turn fail the workflow task.
// Do not fail on replay where the local activities may not be registered on the replay worker.
if (!workflowInfo().unsafe.isReplaying && !activator.registeredActivityNames.has(activityType)) {
throw new ReferenceError(`Local activity of type '${activityType}' not registered on worker`);
}
validateLocalActivityOptions(options);

@@ -195,3 +200,3 @@ return new Promise((resolve, reject) => {

function scheduleActivity(activityType, args, options) {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Workflow.scheduleActivity(...) may only be used from a Workflow Execution');
if (options === undefined) {

@@ -216,3 +221,3 @@ throw new TypeError('Got empty activity options');

async function scheduleLocalActivity(activityType, args, options) {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Workflow.scheduleLocalActivity(...) may only be used from a Workflow Execution');
if (options === undefined) {

@@ -460,3 +465,3 @@ throw new TypeError('Got empty activity options');

function getExternalWorkflowHandle(workflowId, runId) {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Workflow.getExternalWorkflowHandle(...) may only be used from a Workflow Execution. Consider using Client.workflow.getHandle(...) instead.)');
return {

@@ -517,5 +522,5 @@ workflowId,

async function startChild(workflowTypeOrFunc, options) {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Workflow.startChild(...) may only be used from a Workflow Execution. Consider using Client.workflow.start(...) instead.)');
const optionsWithDefaults = addDefaultWorkflowOptions(options ?? {});
const workflowType = typeof workflowTypeOrFunc === 'string' ? workflowTypeOrFunc : workflowTypeOrFunc.name;
const workflowType = (0, common_1.extractWorkflowType)(workflowTypeOrFunc);
const execute = (0, interceptors_1.composeInterceptors)(activator.interceptors.outbound, 'startChildWorkflowExecution', startChildWorkflowExecutionNextHandler);

@@ -551,5 +556,5 @@ const [started, completed] = await execute({

async function executeChild(workflowTypeOrFunc, options) {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Workflow.executeChild(...) may only be used from a Workflow Execution. Consider using Client.workflow.execute(...) instead.');
const optionsWithDefaults = addDefaultWorkflowOptions(options ?? {});
const workflowType = typeof workflowTypeOrFunc === 'string' ? workflowTypeOrFunc : workflowTypeOrFunc.name;
const workflowType = (0, common_1.extractWorkflowType)(workflowTypeOrFunc);
const execute = (0, interceptors_1.composeInterceptors)(activator.interceptors.outbound, 'startChildWorkflowExecution', startChildWorkflowExecutionNextHandler);

@@ -594,3 +599,4 @@ const execPromise = execute({

function workflowInfo() {
return (0, internals_1.getActivator)().info;
const activator = assertInWorkflowContext('Workflow.workflowInfo(...) may only be used from a Workflow Execution.');
return activator.info;
}

@@ -641,7 +647,8 @@ exports.workflowInfo = workflowInfo;

return (...args) => {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Proxied sinks functions may only be used from a Workflow Execution.');
activator.sinkCalls.push({
ifaceName: ifaceName,
fnName: fnName,
args,
// Only available from node 17.
args: globalThis.structuredClone ? globalThis.structuredClone(args) : args,
});

@@ -663,4 +670,4 @@ };

function makeContinueAsNewFunc(options) {
const activator = (0, internals_1.getActivator)();
const info = workflowInfo();
const activator = assertInWorkflowContext('Workflow.continueAsNew(...) and Workflow.makeContinueAsNewFunc(...) may only be used from a Workflow Execution.');
const info = activator.info;
const { workflowType, taskQueue, ...rest } = options ?? {};

@@ -784,3 +791,3 @@ const requiredOptions = {

function patchInternal(patchId, deprecated) {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Workflow.patch(...) and Workflow.deprecatePatch may only be used from a Workflow Execution.');
// Patch operation does not support interception at the moment, if it did,

@@ -803,2 +810,3 @@ // this would be the place to start the interception chain

async function condition(fn, timeout) {
assertInWorkflowContext('Workflow.condition(...) may only be used from a Workflow Execution.');
// Prior to 1.5.0, `condition(fn, 0)` was treated as equivalent to `condition(fn, undefined)`

@@ -879,3 +887,3 @@ if (timeout === 0 && !patched(CONDITION_0_PATCH)) {

function setHandler(def, handler) {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Workflow.setHandler(...) may only be used from a Workflow Execution.');
if (def.type === 'signal') {

@@ -919,3 +927,3 @@ if (typeof handler === 'function') {

function setDefaultSignalHandler(handler) {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Workflow.setDefaultSignalHandler(...) may only be used from a Workflow Execution.');
if (typeof handler === 'function') {

@@ -963,3 +971,3 @@ activator.defaultSignalHandler = handler;

function upsertSearchAttributes(searchAttributes) {
const activator = (0, internals_1.getActivator)();
const activator = assertInWorkflowContext('Workflow.upsertSearchAttributes(...) may only be used from a Workflow Execution.');
const mergedSearchAttributes = { ...activator.info.searchAttributes, ...searchAttributes };

@@ -979,2 +987,40 @@ if (!mergedSearchAttributes) {

exports.enhancedStackTraceQuery = defineQuery('__enhanced_stack_trace');
const loggerSinks = proxySinks();
/**
* Symbol used by the SDK logger to extract a timestamp from log attributes.
* Also defined in `worker/logger.ts` - intentionally not shared.
*/
const LogTimestamp = Symbol.for('log_timestamp');
/**
* Default workflow logger.
* This logger is replay-aware and will omit log messages on workflow replay.
* The messages emitted by this logger are funnelled to the worker's `defaultSinks`, which are installed by default.
*
* Note that since sinks are used to power this logger, any log attributes must be transferable via the
* {@link https://nodejs.org/api/worker_threads.html#worker_threads_port_postmessage_value_transferlist | postMessage}
* API.
*
* `defaultSinks` accepts a user logger and defaults to the `Runtime`'s logger.
*
* See the documentation for `WorkerOptions`, `defaultSinks`, and `Runtime` for more information.
*/
exports.log = Object.fromEntries(['trace', 'debug', 'info', 'warn', 'error'].map((level) => {
return [
level,
(message, attrs) => {
assertInWorkflowContext('Workflow.log(...) may only be used from a Workflow Execution.)');
return loggerSinks.defaultWorkerLogger[level](message, {
// Inject the call time in nanosecond resolution as expected by the worker logger.
[LogTimestamp]: (0, internals_1.getActivator)().getTimeOfDay(),
...attrs,
});
},
];
}));
function assertInWorkflowContext(message) {
const activator = (0, internals_1.maybeGetActivator)();
if (activator == null)
throw new common_1.IllegalStateError(message);
return activator;
}
//# sourceMappingURL=workflow.js.map
{
"name": "@temporalio/workflow",
"version": "1.7.4",
"version": "1.8.0",
"description": "Temporal.io SDK Workflow sub-package",

@@ -25,4 +25,4 @@ "keywords": [

"dependencies": {
"@temporalio/common": "1.7.4",
"@temporalio/proto": "1.7.4"
"@temporalio/common": "1.8.0",
"@temporalio/proto": "1.8.0"
},

@@ -39,3 +39,3 @@ "devDependencies": {

],
"gitHead": "fb4088a8174b60b7a3fc7763ed39dbfc514a3e56"
"gitHead": "17d16e4dca39513470dd4b6e30d9af06dafd00d6"
}
import type { AsyncLocalStorage as ALS } from 'node:async_hooks';
import { CancelledFailure, IllegalStateError } from '@temporalio/common';
import { CancelledFailure, Duration, IllegalStateError } from '@temporalio/common';
import { untrackPromise } from './stack-helpers';

@@ -205,3 +205,3 @@

/** This function is here to avoid a circular dependency between this module and workflow.ts */
let sleep = (_: number | string): Promise<void> => {
let sleep = (_: Duration): Promise<void> => {
throw new IllegalStateError('Workflow has not been properly initialized');

@@ -208,0 +208,0 @@ };

@@ -0,1 +1,2 @@

import { ActivityFailure, CancelledFailure, ChildWorkflowFailure } from '@temporalio/common';
/**

@@ -15,6 +16,2 @@ * Base class for all workflow errors

function looksLikeError(err: unknown): err is { name: string; cause?: unknown } {
return typeof err === 'object' && err != null && Object.prototype.hasOwnProperty.call(err, 'name');
}
/**

@@ -24,9 +21,6 @@ * Returns whether provided `err` is caused by cancellation

export function isCancellation(err: unknown): boolean {
if (!looksLikeError(err)) return false;
return (
err.name === 'CancelledFailure' ||
((err.name === 'ActivityFailure' || err.name === 'ChildWorkflowFailure') &&
looksLikeError(err.cause) &&
err.cause.name === 'CancelledFailure')
CancelledFailure.is(err) ||
((ActivityFailure.is(err) || ChildWorkflowFailure.is(err)) && CancelledFailure.is(err.cause))
);
}

@@ -9,2 +9,3 @@ import type { RawSourceMap } from 'source-map';

QueryDefinition,
Duration,
} from '@temporalio/common';

@@ -168,2 +169,4 @@ import { checkExtends } from '@temporalio/common/lib/type-helpers';

const isContinueAsNew = Symbol.for('__temporal_isContinueAsNew');
/**

@@ -178,2 +181,14 @@ * Not an actual error, used by the Workflow runtime to abort execution when {@link continueAsNew} is called

}
/**
* Marker to determine whether an error is an instance of ContinueAsNew.
*/
protected readonly [isContinueAsNew] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/workflow are installed.
*/
static is(error: unknown): error is ContinueAsNew {
return error instanceof ContinueAsNew || (error instanceof Error && (error as any)[isContinueAsNew]);
}
}

@@ -197,3 +212,3 @@

*/
workflowRunTimeout?: string;
workflowRunTimeout?: Duration;
/**

@@ -203,3 +218,3 @@ * Timeout for a single Workflow task

*/
workflowTaskTimeout?: string;
workflowTaskTimeout?: Duration;
/**

@@ -392,4 +407,6 @@ * Non-searchable attributes to attach to next Workflow run

export interface WorkflowCreateOptionsWithSourceMap extends WorkflowCreateOptions {
export interface WorkflowCreateOptionsInternal extends WorkflowCreateOptions {
sourceMap: RawSourceMap;
registeredActivityNames: Set<string>;
getTimeOfDay(): bigint;
}

@@ -396,0 +413,0 @@

@@ -32,3 +32,3 @@ import type { RawSourceMap } from 'source-map';

WorkflowInfo,
WorkflowCreateOptionsWithSourceMap,
WorkflowCreateOptionsInternal,
} from './interfaces';

@@ -275,4 +275,14 @@ import { SinkCall } from './sinks';

/**
* Buffered sink calls per activation
*/
sinkCalls = Array<SinkCall>();
/**
* A nanosecond resolution time function, externally injected
*/
public readonly getTimeOfDay: () => bigint;
public readonly registeredActivityNames: Set<string>;
constructor({

@@ -283,5 +293,8 @@ info,

sourceMap,
getTimeOfDay,
randomnessSeed,
patches,
}: WorkflowCreateOptionsWithSourceMap) {
registeredActivityNames,
}: WorkflowCreateOptionsInternal) {
this.getTimeOfDay = getTimeOfDay;
this.info = info;

@@ -292,2 +305,3 @@ this.now = now;

this.random = alea(randomnessSeed);
this.registeredActivityNames = registeredActivityNames;

@@ -616,6 +630,6 @@ if (info.unsafe.isReplaying) {

this.pushCommand({ cancelWorkflowExecution: {} }, true);
} else if (error instanceof ContinueAsNew) {
} else if (ContinueAsNew.is(error)) {
this.pushCommand({ continueAsNewWorkflowExecution: error.command }, true);
} else {
if (!(error instanceof TemporalFailure)) {
if (!TemporalFailure.is(error)) {
// This results in an unhandled rejection which will fail the activation

@@ -622,0 +636,0 @@ // preventing it from completing.

@@ -13,3 +13,3 @@ /**

import { WorkflowInterceptorsFactory } from './interceptors';
import { WorkflowCreateOptionsWithSourceMap, WorkflowInfo } from './interfaces';
import { WorkflowCreateOptionsInternal, WorkflowInfo } from './interfaces';
import { Activator, getActivator } from './internals';

@@ -96,3 +96,3 @@ import { SinkCall } from './sinks';

*/
export function initRuntime(options: WorkflowCreateOptionsWithSourceMap): void {
export function initRuntime(options: WorkflowCreateOptionsInternal): void {
const info: WorkflowInfo = fixPrototypes(options.info);

@@ -142,8 +142,8 @@ info.unsafe.now = OriginalDate.now;

const workflowFn = mod[info.workflowType];
const defaultWorfklowFn = mod['default'];
const defaultWorkflowFn = mod['default'];
if (typeof workflowFn === 'function') {
activator.workflow = workflowFn;
} else if (typeof defaultWorfklowFn === 'function') {
activator.workflow = defaultWorfklowFn;
} else if (typeof defaultWorkflowFn === 'function') {
activator.workflow = defaultWorkflowFn;
} else {

@@ -150,0 +150,0 @@ const details =

@@ -5,2 +5,3 @@ import {

compileRetryPolicy,
extractWorkflowType,
IllegalStateError,

@@ -20,3 +21,3 @@ LocalActivityOptions,

} from '@temporalio/common';
import { msOptionalToTs, msToNumber, msToTs, tsToMs } from '@temporalio/common/lib/time';
import { Duration, msOptionalToTs, msToNumber, msToTs, tsToMs } from '@temporalio/common/lib/time';
import { composeInterceptors } from '@temporalio/common/lib/interceptors';

@@ -42,4 +43,4 @@ import { CancellationScope, registerSleepImplementation } from './cancellation-scope';

} from './interfaces';
import { LocalActivityDoBackoff, getActivator, maybeGetActivator } from './internals';
import { Sinks } from './sinks';
import { Activator, LocalActivityDoBackoff, getActivator, maybeGetActivator } from './internals';
import { LoggerSinks, Sinks } from './sinks';
import { untrackPromise } from './stack-helpers';

@@ -113,4 +114,4 @@ import { ChildWorkflowHandle, ExternalWorkflowHandle } from './workflow-handle';

*/
export function sleep(ms: number | string): Promise<void> {
const activator = getActivator();
export function sleep(ms: Duration): Promise<void> {
const activator = assertInWorkflowContext('Workflow.sleep(...) may only be used from a Workflow Execution');
const seq = activator.nextSeqs.timer++;

@@ -205,2 +206,7 @@

const activator = getActivator();
// Eagerly fail the local activity (which will in turn fail the workflow task.
// Do not fail on replay where the local activities may not be registered on the replay worker.
if (!workflowInfo().unsafe.isReplaying && !activator.registeredActivityNames.has(activityType)) {
throw new ReferenceError(`Local activity of type '${activityType}' not registered on worker`);
}
validateLocalActivityOptions(options);

@@ -258,3 +264,5 @@

export function scheduleActivity<R>(activityType: string, args: any[], options: ActivityOptions): Promise<R> {
const activator = getActivator();
const activator = assertInWorkflowContext(
'Workflow.scheduleActivity(...) may only be used from a Workflow Execution'
);
if (options === undefined) {

@@ -284,3 +292,5 @@ throw new TypeError('Got empty activity options');

): Promise<R> {
const activator = getActivator();
const activator = assertInWorkflowContext(
'Workflow.scheduleLocalActivity(...) may only be used from a Workflow Execution'
);
if (options === undefined) {

@@ -584,3 +594,5 @@ throw new TypeError('Got empty activity options');

export function getExternalWorkflowHandle(workflowId: string, runId?: string): ExternalWorkflowHandle {
const activator = getActivator();
const activator = assertInWorkflowContext(
'Workflow.getExternalWorkflowHandle(...) may only be used from a Workflow Execution. Consider using Client.workflow.getHandle(...) instead.)'
);
return {

@@ -707,5 +719,7 @@ workflowId,

): Promise<ChildWorkflowHandle<T>> {
const activator = getActivator();
const activator = assertInWorkflowContext(
'Workflow.startChild(...) may only be used from a Workflow Execution. Consider using Client.workflow.start(...) instead.)'
);
const optionsWithDefaults = addDefaultWorkflowOptions(options ?? ({} as any));
const workflowType = typeof workflowTypeOrFunc === 'string' ? workflowTypeOrFunc : workflowTypeOrFunc.name;
const workflowType = extractWorkflowType(workflowTypeOrFunc);
const execute = composeInterceptors(

@@ -807,5 +821,7 @@ activator.interceptors.outbound,

): Promise<WorkflowResultType<T>> {
const activator = getActivator();
const activator = assertInWorkflowContext(
'Workflow.executeChild(...) may only be used from a Workflow Execution. Consider using Client.workflow.execute(...) instead.'
);
const optionsWithDefaults = addDefaultWorkflowOptions(options ?? ({} as any));
const workflowType = typeof workflowTypeOrFunc === 'string' ? workflowTypeOrFunc : workflowTypeOrFunc.name;
const workflowType = extractWorkflowType(workflowTypeOrFunc);
const execute = composeInterceptors(

@@ -854,3 +870,4 @@ activator.interceptors.outbound,

export function workflowInfo(): WorkflowInfo {
return getActivator().info;
const activator = assertInWorkflowContext('Workflow.workflowInfo(...) may only be used from a Workflow Execution.');
return activator.info;
}

@@ -905,7 +922,10 @@

return (...args: any[]) => {
const activator = getActivator();
const activator = assertInWorkflowContext(
'Proxied sinks functions may only be used from a Workflow Execution.'
);
activator.sinkCalls.push({
ifaceName: ifaceName as string,
fnName: fnName as string,
args,
// Only available from node 17.
args: (globalThis as any).structuredClone ? (globalThis as any).structuredClone(args) : args,
});

@@ -931,4 +951,6 @@ };

): (...args: Parameters<F>) => Promise<never> {
const activator = getActivator();
const info = workflowInfo();
const activator = assertInWorkflowContext(
'Workflow.continueAsNew(...) and Workflow.makeContinueAsNewFunc(...) may only be used from a Workflow Execution.'
);
const info = activator.info;
const { workflowType, taskQueue, ...rest } = options ?? {};

@@ -1056,3 +1078,5 @@ const requiredOptions = {

function patchInternal(patchId: string, deprecated: boolean): boolean {
const activator = getActivator();
const activator = assertInWorkflowContext(
'Workflow.patch(...) and Workflow.deprecatePatch may only be used from a Workflow Execution.'
);
// Patch operation does not support interception at the moment, if it did,

@@ -1083,3 +1107,3 @@ // this would be the place to start the interception chain

*/
export function condition(fn: () => boolean, timeout: number | string): Promise<boolean>;
export function condition(fn: () => boolean, timeout: Duration): Promise<boolean>;

@@ -1091,3 +1115,4 @@ /**

export async function condition(fn: () => boolean, timeout?: number | string): Promise<void | boolean> {
export async function condition(fn: () => boolean, timeout?: Duration): Promise<void | boolean> {
assertInWorkflowContext('Workflow.condition(...) may only be used from a Workflow Execution.');
// Prior to 1.5.0, `condition(fn, 0)` was treated as equivalent to `condition(fn, undefined)`

@@ -1180,3 +1205,3 @@ if (timeout === 0 && !patched(CONDITION_0_PATCH)) {

): void {
const activator = getActivator();
const activator = assertInWorkflowContext('Workflow.setHandler(...) may only be used from a Workflow Execution.');
if (def.type === 'signal') {

@@ -1214,3 +1239,5 @@ if (typeof handler === 'function') {

export function setDefaultSignalHandler(handler: DefaultSignalHandler | undefined): void {
const activator = getActivator();
const activator = assertInWorkflowContext(
'Workflow.setDefaultSignalHandler(...) may only be used from a Workflow Execution.'
);
if (typeof handler === 'function') {

@@ -1256,3 +1283,5 @@ activator.defaultSignalHandler = handler;

export function upsertSearchAttributes(searchAttributes: SearchAttributes): void {
const activator = getActivator();
const activator = assertInWorkflowContext(
'Workflow.upsertSearchAttributes(...) may only be used from a Workflow Execution.'
);

@@ -1275,1 +1304,44 @@ const mergedSearchAttributes = { ...activator.info.searchAttributes, ...searchAttributes };

export const enhancedStackTraceQuery = defineQuery<EnhancedStackTrace>('__enhanced_stack_trace');
const loggerSinks = proxySinks<LoggerSinks>();
/**
* Symbol used by the SDK logger to extract a timestamp from log attributes.
* Also defined in `worker/logger.ts` - intentionally not shared.
*/
const LogTimestamp = Symbol.for('log_timestamp');
/**
* Default workflow logger.
* This logger is replay-aware and will omit log messages on workflow replay.
* The messages emitted by this logger are funnelled to the worker's `defaultSinks`, which are installed by default.
*
* Note that since sinks are used to power this logger, any log attributes must be transferable via the
* {@link https://nodejs.org/api/worker_threads.html#worker_threads_port_postmessage_value_transferlist | postMessage}
* API.
*
* `defaultSinks` accepts a user logger and defaults to the `Runtime`'s logger.
*
* See the documentation for `WorkerOptions`, `defaultSinks`, and `Runtime` for more information.
*/
export const log: LoggerSinks['defaultWorkerLogger'] = Object.fromEntries(
(['trace', 'debug', 'info', 'warn', 'error'] as Array<keyof LoggerSinks['defaultWorkerLogger']>).map((level) => {
return [
level,
(message: string, attrs: Record<string, unknown>) => {
assertInWorkflowContext('Workflow.log(...) may only be used from a Workflow Execution.)');
return loggerSinks.defaultWorkerLogger[level](message, {
// Inject the call time in nanosecond resolution as expected by the worker logger.
[LogTimestamp]: getActivator().getTimeOfDay(),
...attrs,
});
},
];
})
) as any;
function assertInWorkflowContext(message: string): Activator {
const activator = maybeGetActivator();
if (activator == null) throw new IllegalStateError(message);
return activator;
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc