Socket
Socket
Sign inDemoInstall

@temporalio/workflow

Package Overview
Dependencies
Maintainers
4
Versions
79
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 0.9.0 to 0.11.0

2

lib/cancellation-scope.d.ts

@@ -115,4 +115,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) => Promise<void>;
declare let sleep: (_: number | string) => Promise<void>;
export declare function registerSleepImplementation(fn: typeof sleep): void;
export {};

@@ -53,4 +53,4 @@ /**

*/
export { Workflow, WorkflowHandlers, WorkflowResultType, ActivityCancellationType, ActivityFunction, ActivityInterface, ActivityOptions, RetryOptions, rootCause, IllegalStateError, defaultDataConverter, DataConverter, WorkflowIdReusePolicy, ActivityFailure, ApplicationFailure, CancelledFailure, ChildWorkflowFailure, ServerFailure, TemporalFailure, TerminatedFailure, TimeoutFailure, } from '@temporalio/common';
export { ChildWorkflowOptions, ChildWorkflowCancellationType, WorkflowInfo } from './interfaces';
export { Workflow, WorkflowResultType, ActivityCancellationType, ActivityFunction, ActivityInterface, ActivityOptions, RetryOptions, rootCause, IllegalStateError, defaultDataConverter, DataConverter, WorkflowIdReusePolicy, ActivityFailure, ApplicationFailure, CancelledFailure, ChildWorkflowFailure, ServerFailure, TemporalFailure, TerminatedFailure, TimeoutFailure, } from '@temporalio/common';
export { ChildWorkflowOptions, ChildWorkflowCancellationType, ContinueAsNewOptions, ParentClosePolicy, WorkflowInfo, } from './interfaces';
export * from './errors';

@@ -57,0 +57,0 @@ export * from './workflow';

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

Object.defineProperty(exports, "__esModule", { value: true });
exports.ApplyMode = exports.Trigger = exports.CancellationScope = exports.ROOT_SCOPE = exports.AsyncLocalStorage = exports.ChildWorkflowCancellationType = exports.TimeoutFailure = exports.TerminatedFailure = exports.TemporalFailure = exports.ServerFailure = exports.ChildWorkflowFailure = exports.CancelledFailure = exports.ApplicationFailure = exports.ActivityFailure = exports.WorkflowIdReusePolicy = exports.defaultDataConverter = exports.IllegalStateError = exports.rootCause = exports.ActivityCancellationType = void 0;
exports.ApplyMode = exports.Trigger = exports.CancellationScope = exports.ROOT_SCOPE = exports.AsyncLocalStorage = exports.ParentClosePolicy = exports.ChildWorkflowCancellationType = exports.TimeoutFailure = exports.TerminatedFailure = exports.TemporalFailure = exports.ServerFailure = exports.ChildWorkflowFailure = exports.CancelledFailure = exports.ApplicationFailure = exports.ActivityFailure = exports.WorkflowIdReusePolicy = exports.defaultDataConverter = exports.IllegalStateError = exports.rootCause = exports.ActivityCancellationType = void 0;
var common_1 = require("@temporalio/common");

@@ -83,2 +83,3 @@ Object.defineProperty(exports, "ActivityCancellationType", { enumerable: true, get: function () { return common_1.ActivityCancellationType; } });

Object.defineProperty(exports, "ChildWorkflowCancellationType", { enumerable: true, get: function () { return interfaces_1.ChildWorkflowCancellationType; } });
Object.defineProperty(exports, "ParentClosePolicy", { enumerable: true, get: function () { return interfaces_1.ParentClosePolicy; } });
__exportStar(require("./errors"), exports);

@@ -85,0 +86,0 @@ __exportStar(require("./workflow"), exports);

@@ -8,3 +8,3 @@ /**

*/
import { ActivityOptions, WorkflowExecution, Headers, Next, WorkflowHandlers } from '@temporalio/common';
import { ActivityOptions, WorkflowExecution, Headers, Next } from '@temporalio/common';
import { coresdk } from '@temporalio/proto/lib/coresdk';

@@ -39,8 +39,2 @@ import { ChildWorkflowOptions, ContinueAsNewOptions } from './interfaces';

/**
* Called when Workflow is created from a factory function
*
* @return the Workflow handlers
*/
create?: (input: WorkflowCreateInput, next: Next<this, 'create'>) => Promise<WorkflowHandlers>;
/**
* Called when Workflow execute method is called

@@ -47,0 +41,0 @@ *

@@ -88,3 +88,3 @@ import { coresdk } from '@temporalio/proto/lib/coresdk';

}
export declare type RequiredChildWorkflowOptions = Required<Pick<ChildWorkflowOptions, 'workflowId' | 'workflowIdReusePolicy' | 'cancellationType' | 'taskQueue'>>;
export declare type RequiredChildWorkflowOptions = Required<Pick<ChildWorkflowOptions, 'workflowId' | 'cancellationType'>>;
export declare type ChildWorkflowOptionsWithDefaults = ChildWorkflowOptions & RequiredChildWorkflowOptions;

@@ -1,6 +0,6 @@

import { WorkflowSignalType, DataConverter, WorkflowHandlers } from '@temporalio/common';
import { WorkflowSignalType, DataConverter, Workflow, WorkflowQueryType } from '@temporalio/common';
import { coresdk } from '@temporalio/proto/lib/coresdk';
import { RNG } from './alea';
import { WorkflowInfo } from './interfaces';
import { QueryInput, SignalInput, WorkflowInterceptors } from './interceptors';
import { QueryInput, SignalInput, WorkflowExecuteInput, WorkflowInterceptors } from './interceptors';
import { ExternalCall, ExternalDependencies } from './dependencies';

@@ -13,2 +13,6 @@ export declare type ResolveFunction<T = any> = (val: T) => any;

}
export interface Condition {
fn(): boolean;
resolve(): void;
}
export declare type ActivationHandlerFunction<K extends keyof coresdk.workflow_activation.IWFActivationJob> = (activation: NonNullable<coresdk.workflow_activation.IWFActivationJob[K]>) => Promise<void> | void;

@@ -19,3 +23,3 @@ export declare type ActivationHandler = {

export declare class Activator implements ActivationHandler {
startWorkflowNextHandler(): Promise<any>;
startWorkflowNextHandler({ args }: WorkflowExecuteInput): Promise<any>;
startWorkflow(activation: coresdk.workflow_activation.IStartWorkflow): void;

@@ -27,5 +31,5 @@ cancelWorkflow(_activation: coresdk.workflow_activation.ICancelWorkflow): void;

resolveChildWorkflowExecution(activation: coresdk.workflow_activation.IResolveChildWorkflowExecution): Promise<void>;
protected queryWorkflowNextHandler(input: QueryInput): Promise<unknown>;
protected queryWorkflowNextHandler({ queryName, args }: QueryInput): Promise<unknown>;
queryWorkflow(activation: coresdk.workflow_activation.IQueryWorkflow): void;
signalWorkflowNextHandler(fn: WorkflowSignalType, input: SignalInput): Promise<void>;
signalWorkflowNextHandler({ signalName, args }: SignalInput): Promise<void>;
signalWorkflow(activation: coresdk.workflow_activation.ISignalWorkflow): void;

@@ -62,2 +66,14 @@ resolveSignalExternalWorkflow(activation: coresdk.workflow_activation.IResolveSignalExternalWorkflow): Promise<void>;

/**
* Holds buffered signal calls until a listener is registered
*/
readonly bufferedSignals: Map<string, coresdk.workflow_activation.ISignalWorkflow[]>;
/**
* Mapping of signal name to listener
*/
readonly signalListeners: Map<string, WorkflowSignalType>;
/**
* Mapping of signal name to listener
*/
readonly queryListeners: Map<string, WorkflowQueryType>;
/**
* Loaded in {@link initRuntime}

@@ -75,2 +91,6 @@ */

/**
* Stores all {@link condition}s that haven't been unblocked yet
*/
blockedConditions: Map<number, Condition>;
/**
* Is this Workflow completed

@@ -93,2 +113,3 @@ */

cancelWorkflow: number;
condition: number;
};

@@ -100,3 +121,3 @@ get now(): number;

*/
workflow?: WorkflowHandlers;
workflow?: Workflow;
/**

@@ -117,3 +138,3 @@ * Information about the current Workflow

*/
require?: (path: string | undefined, workflowType: string) => any;
require?: (path: string | undefined) => any;
dataConverter: DataConverter;

@@ -120,0 +141,0 @@ /**

@@ -49,11 +49,12 @@ "use strict";

class Activator {
async startWorkflowNextHandler() {
if (exports.state.workflow === undefined) {
async startWorkflowNextHandler({ args }) {
const { workflow } = exports.state;
if (workflow === undefined) {
throw new common_1.IllegalStateError('Workflow uninitialized');
}
return await exports.state.workflow.execute();
return await workflow(...args);
}
startWorkflow(activation) {
const { require: req, info } = exports.state;
if (req === undefined || info === undefined) {
const { info } = exports.state;
if (info === undefined) {
throw new common_1.IllegalStateError('Workflow has not been initialized');

@@ -149,9 +150,9 @@ }

}
async queryWorkflowNextHandler(input) {
const fn = exports.state.workflow?.queries?.[input.queryName];
async queryWorkflowNextHandler({ queryName, args }) {
const fn = exports.state.queryListeners.get(queryName);
if (fn === undefined) {
// Fail the query
throw new ReferenceError(`Workflow did not register a handler for ${input.queryName}`);
throw new ReferenceError(`Workflow did not register a handler for ${queryName}`);
}
const ret = fn(...input.args);
const ret = fn(...args);
if (ret instanceof Promise) {

@@ -174,4 +175,8 @@ throw new errors_1.DeterminismViolationError('Query handlers should not return a Promise');

}
async signalWorkflowNextHandler(fn, input) {
return fn(...input.args);
async signalWorkflowNextHandler({ signalName, args }) {
const fn = exports.state.signalListeners.get(signalName);
if (fn === undefined) {
throw new common_1.IllegalStateError(`No registered signal listener for signal ${signalName}`);
}
return fn(...args);
}

@@ -183,8 +188,13 @@ signalWorkflow(activation) {

}
const fn = exports.state.workflow?.signals?.[signalName];
const fn = exports.state.signalListeners.get(signalName);
if (fn === undefined) {
// Fail the activation
throw new ReferenceError(`Workflow did not register a signal handler for ${signalName}`);
let buffer = exports.state.bufferedSignals.get(signalName);
if (buffer === undefined) {
buffer = [];
exports.state.bufferedSignals.set(signalName, buffer);
}
buffer.push(activation);
return;
}
const execute = (0, common_1.composeInterceptors)(exports.state.interceptors.inbound, 'handleSignal', this.signalWorkflowNextHandler.bind(this, fn));
const execute = (0, common_1.composeInterceptors)(exports.state.interceptors.inbound, 'handleSignal', this.signalWorkflowNextHandler.bind(this));
execute({

@@ -254,2 +264,14 @@ args: (0, common_1.arrayFromPayloadsSync)(exports.state.dataConverter, activation.input),

/**
* Holds buffered signal calls until a listener is registered
*/
this.bufferedSignals = new Map();
/**
* Mapping of signal name to listener
*/
this.signalListeners = new Map();
/**
* Mapping of signal name to listener
*/
this.queryListeners = new Map();
/**
* Loaded in {@link initRuntime}

@@ -267,2 +289,6 @@ */

/**
* Stores all {@link condition}s that haven't been unblocked yet
*/
this.blockedConditions = new Map();
/**
* Is this Workflow completed

@@ -285,2 +311,3 @@ */

cancelWorkflow: 1,
condition: 1,
};

@@ -287,0 +314,0 @@ /**

@@ -13,20 +13,12 @@ /**

export declare function overrideGlobals(): void;
/** Mock DOM element for Webpack dynamic imports */
export interface MockElement {
getAttribute(name: string): unknown;
setAttribute(name: string, value: unknown): void;
}
/** Mock document object for Webpack dynamic imports */
export interface MockDocument {
head: {
appendChild(): void;
};
getElementsByTagName(): MockElement[];
createElement(): MockElement;
}
/**
* Create a mock document object with mimimal required attributes to support Webpack dynamic imports
* Initialize the isolate runtime.
*
* Sets required internal state and instantiates the workflow and interceptors.
*/
export declare function mockBrowserDocumentForWebpack(): MockDocument;
export declare function initRuntime(info: WorkflowInfo, interceptorModules: string[], randomnessSeed: number[], isolateExtension: IsolateExtension, encodedStartWorkflow: Uint8Array): Promise<void>;
export declare function initRuntime(info: WorkflowInfo, interceptorModules: string[], randomnessSeed: number[], now: number, isolateExtension: IsolateExtension): Promise<void>;
export interface ActivationResult {
externalCalls: ExternalCall[];
numBlockedConditions: number;
}
/**

@@ -36,6 +28,7 @@ * Run a chunk of activation jobs

*/
export declare function activate(encodedActivation: Uint8Array, batchIndex: number): Promise<ExternalCall[]>;
export declare function activate(encodedActivation: Uint8Array, batchIndex: number): Promise<ActivationResult>;
declare type ActivationConclusion = {
type: 'pending';
pendingExternalCalls: ExternalCall[];
numBlockedConditions: number;
} | {

@@ -68,2 +61,8 @@ type: 'complete';

export declare function resolveExternalDependencies(results: ExternalDependencyResult[]): void;
/**
* Loop through all blocked conditions, evaluate and unblock if possible.
*
* @returns number of unblocked conditions.
*/
export declare function tryUnblockConditions(): number;
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveExternalDependencies = exports.inject = exports.getAndResetPendingExternalCalls = exports.concludeActivation = exports.activate = exports.initRuntime = exports.mockBrowserDocumentForWebpack = exports.overrideGlobals = exports.setRequireFunc = void 0;
exports.tryUnblockConditions = exports.resolveExternalDependencies = exports.inject = exports.getAndResetPendingExternalCalls = exports.concludeActivation = exports.activate = exports.initRuntime = exports.overrideGlobals = exports.setRequireFunc = void 0;
const common_1 = require("@temporalio/common");

@@ -70,26 +70,7 @@ const coresdk_1 = require("@temporalio/proto/lib/coresdk");

/**
* Create a mock document object with mimimal required attributes to support Webpack dynamic imports
* Initialize the isolate runtime.
*
* Sets required internal state and instantiates the workflow and interceptors.
*/
function mockBrowserDocumentForWebpack() {
const attrs = new Map();
const el = {
getAttribute: (name) => attrs.get(name),
setAttribute: (name, value) => {
attrs.set(name, value);
},
};
return {
head: {
appendChild: () => undefined,
},
getElementsByTagName: () => {
return [el];
},
createElement: () => {
return el;
},
};
}
exports.mockBrowserDocumentForWebpack = mockBrowserDocumentForWebpack;
async function initRuntime(info, interceptorModules, randomnessSeed, isolateExtension, encodedStartWorkflow) {
async function initRuntime(info, interceptorModules, randomnessSeed, now, isolateExtension) {
// Globals are overridden while building the isolate before loading user code.

@@ -101,2 +82,3 @@ // For some reason the `WeakRef` mock is not restored properly when creating an isolate from snapshot in node 14 (at least on ubuntu), override again.

internals_1.state.info = info;
internals_1.state.now = now;
internals_1.state.random = (0, alea_1.alea)(randomnessSeed);

@@ -109,3 +91,3 @@ promise_hooks_1.HookManager.instance.setIsolateExtension(isolateExtension);

for (const mod of interceptorModules) {
const factory = req(mod, 'interceptors');
const factory = req(mod).interceptors;
if (factory !== undefined) {

@@ -121,23 +103,16 @@ if (typeof factory !== 'function') {

}
const { headers, arguments: args } = coresdk_1.coresdk.workflow_activation.StartWorkflow.decodeDelimited(encodedStartWorkflow);
const create = (0, common_1.composeInterceptors)(internals_1.state.interceptors.inbound, 'create', async ({ args }) => {
let mod;
try {
mod = req(undefined, info.workflowType);
if (typeof mod !== 'function') {
throw new TypeError(`'${info.workflowType}' is not a function`);
}
let mod;
try {
mod = req(undefined)[info.workflowType];
if (typeof mod !== 'function') {
throw new TypeError(`'${info.workflowType}' is not a function`);
}
catch (err) {
const failure = common_1.ApplicationFailure.nonRetryable((0, common_1.errorMessage)(err), 'ReferenceError');
failure.stack = failure.stack?.split('\n')[0];
throw failure;
}
return mod(...args);
});
internals_1.state.workflow =
(await create({
headers,
args: (0, common_1.arrayFromPayloadsSync)(internals_1.state.dataConverter, args),
}).catch(internals_1.handleWorkflowFailure)) ?? undefined;
}
catch (err) {
const failure = common_1.ApplicationFailure.nonRetryable((0, common_1.errorMessage)(err), 'ReferenceError');
failure.stack = failure.stack?.split('\n')[0];
(0, internals_1.handleWorkflowFailure)(failure);
return;
}
internals_1.state.workflow = mod;
}

@@ -150,2 +125,3 @@ exports.initRuntime = initRuntime;

async function activate(encodedActivation, batchIndex) {
const activation = coresdk_1.coresdk.workflow_activation.WFActivation.decodeDelimited(encodedActivation);
const intercept = (0, common_1.composeInterceptors)(internals_1.state.interceptors.internals, 'activate', async ({ activation, batchIndex }) => {

@@ -183,9 +159,13 @@ if (batchIndex === 0) {

await internals_1.state.activator[job.variant](variant /* TODO: TS is struggling with `true` and `{}` */);
tryUnblockConditions();
}));
});
await intercept({
activation: coresdk_1.coresdk.workflow_activation.WFActivation.decodeDelimited(encodedActivation),
activation,
batchIndex,
});
return internals_1.state.getAndResetPendingExternalCalls();
return {
externalCalls: internals_1.state.getAndResetPendingExternalCalls(),
numBlockedConditions: internals_1.state.blockedConditions.size,
};
}

@@ -203,3 +183,3 @@ exports.activate = activate;

if (pendingExternalCalls.length > 0) {
return { type: 'pending', pendingExternalCalls };
return { type: 'pending', pendingExternalCalls, numBlockedConditions: internals_1.state.blockedConditions.size };
}

@@ -262,2 +242,26 @@ const intercept = (0, common_1.composeInterceptors)(internals_1.state.interceptors.internals, 'concludeActivation', (input) => input);

exports.resolveExternalDependencies = resolveExternalDependencies;
/**
* Loop through all blocked conditions, evaluate and unblock if possible.
*
* @returns number of unblocked conditions.
*/
function tryUnblockConditions() {
let numUnblocked = 0;
for (;;) {
const prevUnblocked = numUnblocked;
for (const [seq, cond] of internals_1.state.blockedConditions.entries()) {
if (cond.fn()) {
cond.resolve();
numUnblocked++;
// It is safe to delete elements during map iteration
internals_1.state.blockedConditions.delete(seq);
}
}
if (prevUnblocked === numUnblocked) {
break;
}
}
return numUnblocked;
}
exports.tryUnblockConditions = tryUnblockConditions;
//# sourceMappingURL=worker-interface.js.map

@@ -1,16 +0,17 @@

import { BaseWorkflowHandle, Workflow, WorkflowHandleSignals } from '@temporalio/common';
import { BaseWorkflowHandle, SignalDefinition, Workflow } from '@temporalio/common';
/**
* Handle representing an external Workflow execution
*/
export interface ExternalWorkflowHandle<T extends Workflow> {
export interface ExternalWorkflowHandle {
/**
* A mapping of the different signals defined by Workflow interface `T` to callable functions.
* Call to signal a running Workflow.
* Signal a running Workflow.
*
* @param def a signal definition as returned from {@link defineSignal} or signal name (string)
*
* @example
* ```ts
* await workflow.signal.increment(3);
* await handle.signal(incrementSignal, 3);
* ```
*/
signal: WorkflowHandleSignals<T>;
signal<Args extends any[]>(def: SignalDefinition<Args> | string, ...args: Args): Promise<void>;
/**

@@ -32,21 +33,18 @@ * Cancel the external Workflow execution.

/**
* Transforms a workflow interface `T` into a client interface
* A client side handle to a single Workflow instance.
* It can be used to start, signal, wait for completion, and cancel a Workflow execution.
*
* Given a workflow interface such as:
* Given the following Workflow definition:
* ```ts
* export interface Counter {
* execute(initialValue?: number): number;
* signals: {
* increment(amount?: number): void;
* };
* }
* export const incrementSignal = defineSignal('increment');
* export async function counterWorkflow(initialValue: number): Promise<void>;
* ```
*
* Create a handle for running and interacting with a single workflow
* Create a handle for running and interacting with a single Workflow:
* ```ts
* // `counter` is a registered workflow file, typically found at
* // `lib/workflows/counter.js` after building the typescript project
* const workflow = Context.child<Counter>('counter');
* // start workflow `execute` function with initialValue of 2 and await its completion
* await workflow.execute(2);
* const handle = createChildWorkflowHandle(counterWorkflow);
* // Start the Workflow with initialValue of 2.
* await handle.start(2);
* await handle.signal(incrementSignal, 2);
* await handle.result(); // throws WorkflowExecutionTerminatedError
* ```

@@ -53,0 +51,0 @@ */

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

import { ActivityFunction, ActivityOptions, Workflow } from '@temporalio/common';
import { ActivityFunction, ActivityOptions, Workflow, SignalDefinition, QueryDefinition } from '@temporalio/common';
import { ChildWorkflowOptions, ChildWorkflowOptionsWithDefaults, ContinueAsNewOptions, WorkflowInfo } from './interfaces';

@@ -13,7 +13,6 @@ import { ExternalDependencies } from './dependencies';

* Schedules a timer on the Temporal service.
* The returned promise is {@link cancel | cancellable}.
*
* @param ms milliseconds to sleep for
* @param ms sleep duration - {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
*/
export declare function sleep(ms: number): Promise<void>;
export declare function sleep(ms: number | string): Promise<void>;
export interface ActivityInfo {

@@ -78,3 +77,3 @@ name: string;

*/
export declare function createExternalWorkflowHandle<T extends Workflow>(workflowId: string, runId?: string): ExternalWorkflowHandle<T>;
export declare function createExternalWorkflowHandle(workflowId: string, runId?: string): ExternalWorkflowHandle;
/**

@@ -196,1 +195,40 @@ * Returns a client-side handle that implements a child Workflow interface.

export declare function deprecatePatch(patchId: string): void;
/**
* Returns a Promise that resolves when `fn` evaluates to `true` or `timeout` expires.
*
* @param timeout {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
*
* @returns a boolean indicating whether the condition was true before the timeout expires
*/
export declare function condition(timeout: number | string, fn: () => boolean): Promise<boolean>;
/**
* Returns a Promise that resolves when `fn` evaluates to `true`.
*/
export declare function condition(fn: () => boolean): Promise<void>;
/**
* Define a signal method for a Workflow.
*
* Definitions are used to register listeners in the Workflow via {@link setListener} and to signal Workflows using a {@link WorkflowHandle}, {@link ChildWorkflowHandle} or {@link ExternalWorkflowHandle}.
* Definitions can be reused in multiple Workflows.
*/
export declare function defineSignal<Args extends any[] = []>(name: string): SignalDefinition<Args>;
/**
* Define a query method for a Workflow.
*
* Definitions are used to register listeners in the Workflow via {@link setListener} and to query Workflows using a {@link WorkflowHandle}.
* Definitions can be reused in multiple Workflows.
*/
export declare function defineQuery<Ret, Args extends any[] = []>(name: string): QueryDefinition<Ret, Args>;
/**
* A listener function capable of accepting the arguments for a given SignalDefinition or QueryDefinition.
*/
export declare type Listener<Ret, Args extends any[], T extends SignalDefinition<Args> | QueryDefinition<Ret, Args>> = T extends SignalDefinition<infer A> ? (...args: A) => void | Promise<void> : T extends QueryDefinition<infer R, infer A> ? (...args: A) => R : never;
/**
* Set a listener function for a Workflow query or signal.
*
* If this function is called multiple times for a given signal or query name the last listener will overwrite any previous calls.
*
* @param def a {@link SignalDefinition} or {@link QueryDefinition} as returned by {@link defineSignal} or {@link defineQuery} respectively.
* @param listener a compatible listener function for the given definition.
*/
export declare function setListener<Ret, Args extends any[], T extends SignalDefinition<Args> | QueryDefinition<Ret, Args>>(def: T, listener: Listener<Ret, Args, T>): void;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deprecatePatch = exports.patched = exports.uuid4 = exports.continueAsNew = exports.makeContinueAsNewFunc = exports.dependencies = exports.workflowInfo = exports.createChildWorkflowHandle = exports.createExternalWorkflowHandle = exports.createActivityHandle = exports.scheduleActivity = exports.validateActivityOptions = exports.sleep = exports.addDefaultWorkflowOptions = void 0;
exports.setListener = exports.defineQuery = exports.defineSignal = exports.condition = exports.deprecatePatch = exports.patched = exports.uuid4 = exports.continueAsNew = exports.makeContinueAsNewFunc = exports.dependencies = exports.workflowInfo = exports.createChildWorkflowHandle = exports.createExternalWorkflowHandle = exports.createActivityHandle = exports.scheduleActivity = exports.validateActivityOptions = exports.sleep = exports.addDefaultWorkflowOptions = void 0;
const common_1 = require("@temporalio/common");
const coresdk_1 = require("@temporalio/proto/lib/coresdk");
const interfaces_1 = require("./interfaces");

@@ -17,5 +16,3 @@ const internals_1 = require("./internals");

return {
taskQueue: workflowInfo().taskQueue,
workflowId: opts.workflowId ?? uuid4(),
workflowIdReusePolicy: coresdk_1.coresdk.common.WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_ALLOW_DUPLICATE_FAILED_ONLY,
cancellationType: interfaces_1.ChildWorkflowCancellationType.WAIT_CANCELLATION_COMPLETED,

@@ -65,5 +62,4 @@ ...opts,

* Schedules a timer on the Temporal service.
* The returned promise is {@link cancel | cancellable}.
*
* @param ms milliseconds to sleep for
* @param ms sleep duration - {@link https://www.npmjs.com/package/ms | ms} formatted string or number of milliseconds
*/

@@ -74,3 +70,3 @@ function sleep(ms) {

return execute({
durationMs: ms,
durationMs: (0, common_1.msToNumber)(ms),
seq,

@@ -368,20 +364,13 @@ });

},
signal: new Proxy({}, {
get(_, signalName) {
if (typeof signalName !== 'string') {
throw new TypeError(`Invalid signal type, expected string got: ${typeof signalName}`);
}
return (...args) => {
return (0, common_1.composeInterceptors)(internals_1.state.interceptors.outbound, 'signalWorkflow', signalWorkflowNextHandler)({
seq: internals_1.state.nextSeqs.signalWorkflow++,
signalName,
args,
target: {
type: 'external',
workflowExecution: { workflowId, runId },
},
});
};
},
}),
async signal(def, ...args) {
return (0, common_1.composeInterceptors)(internals_1.state.interceptors.outbound, 'signalWorkflow', signalWorkflowNextHandler)({
seq: internals_1.state.nextSeqs.signalWorkflow++,
signalName: typeof def === 'string' ? def : def.name,
args,
target: {
type: 'external',
workflowExecution: { workflowId, runId },
},
});
},
};

@@ -395,2 +384,13 @@ }

let completed = undefined;
const { info, require: req } = internals_1.state;
// These will be undefined if called outside of Workflow context.
// It's a valid case since sometimes non-workflow code imports workflow code.
if (req !== undefined && info !== undefined) {
// Require the module where Workflows are registered.
const registeredWorkflows = req(undefined);
if ((optionsWithDefaults.taskQueue === info.taskQueue || optionsWithDefaults.taskQueue === undefined) &&
!(workflowType in registeredWorkflows)) {
throw new TypeError(`Cannot create a handle for unregistered Workflow type: ${workflowType}, make sure it is exported in the Worker's workflowsPath`);
}
}
return {

@@ -422,23 +422,16 @@ workflowId: optionsWithDefaults.workflowId,

},
signal: new Proxy({}, {
get(_, signalName) {
if (typeof signalName !== 'string') {
throw new TypeError(`Invalid signal type, expected string got: ${typeof signalName}`);
}
return async (...args) => {
if (started === undefined) {
throw new common_1.IllegalStateError('Workflow execution not started');
}
return (0, common_1.composeInterceptors)(internals_1.state.interceptors.outbound, 'signalWorkflow', signalWorkflowNextHandler)({
seq: internals_1.state.nextSeqs.signalWorkflow++,
signalName,
args,
target: {
type: 'child',
childWorkflowId: optionsWithDefaults.workflowId,
},
});
};
},
}),
async signal(def, ...args) {
if (started === undefined) {
throw new common_1.IllegalStateError('Workflow execution not started');
}
return (0, common_1.composeInterceptors)(internals_1.state.interceptors.outbound, 'signalWorkflow', signalWorkflowNextHandler)({
seq: internals_1.state.nextSeqs.signalWorkflow++,
signalName: typeof def === 'string' ? def : def.name,
args,
target: {
type: 'child',
childWorkflowId: optionsWithDefaults.workflowId,
},
});
},
};

@@ -634,2 +627,84 @@ }

}
function condition(fnOrTimeout, fn) {
if ((typeof fnOrTimeout === 'number' || typeof fnOrTimeout === 'string') && fn !== undefined) {
return Promise.race([sleep(fnOrTimeout).then(() => false), conditionInner(fn).then(() => true)]);
}
return conditionInner(fnOrTimeout);
}
exports.condition = condition;
function conditionInner(fn) {
return new Promise((resolve, reject) => {
const scope = cancellation_scope_1.CancellationScope.current();
if (scope.consideredCancelled) {
scope.cancelRequested.catch(reject);
return;
}
const seq = internals_1.state.nextSeqs.condition++;
if (scope.cancellable) {
scope.cancelRequested.catch((err) => {
internals_1.state.blockedConditions.delete(seq);
reject(err);
});
}
// Eager evaluation
if (fn()) {
resolve();
return;
}
internals_1.state.blockedConditions.set(seq, { fn, resolve });
});
}
/**
* Define a signal method for a Workflow.
*
* Definitions are used to register listeners in the Workflow via {@link setListener} and to signal Workflows using a {@link WorkflowHandle}, {@link ChildWorkflowHandle} or {@link ExternalWorkflowHandle}.
* Definitions can be reused in multiple Workflows.
*/
function defineSignal(name) {
return {
type: 'signal',
name,
};
}
exports.defineSignal = defineSignal;
/**
* Define a query method for a Workflow.
*
* Definitions are used to register listeners in the Workflow via {@link setListener} and to query Workflows using a {@link WorkflowHandle}.
* Definitions can be reused in multiple Workflows.
*/
function defineQuery(name) {
return {
type: 'query',
name,
};
}
exports.defineQuery = defineQuery;
/**
* Set a listener function for a Workflow query or signal.
*
* If this function is called multiple times for a given signal or query name the last listener will overwrite any previous calls.
*
* @param def a {@link SignalDefinition} or {@link QueryDefinition} as returned by {@link defineSignal} or {@link defineQuery} respectively.
* @param listener a compatible listener function for the given definition.
*/
function setListener(def, listener) {
if (def.type === 'signal') {
internals_1.state.signalListeners.set(def.name, listener);
const bufferedSignals = internals_1.state.bufferedSignals.get(def.name);
if (bufferedSignals !== undefined) {
for (const signal of bufferedSignals) {
internals_1.state.activator.signalWorkflow(signal);
}
internals_1.state.bufferedSignals.delete(def.name);
}
}
else if (def.type === 'query') {
internals_1.state.queryListeners.set(def.name, listener);
}
else {
throw new TypeError(`Invalid definition type: ${def.type}`);
}
}
exports.setListener = setListener;
//# sourceMappingURL=workflow.js.map
{
"name": "@temporalio/workflow",
"version": "0.9.0",
"version": "0.11.0",
"description": "Temporal.io SDK Workflow sub-package",

@@ -16,4 +16,4 @@ "main": "lib/index.js",

"dependencies": {
"@temporalio/common": "^0.4.0",
"@temporalio/proto": "^0.3.3"
"@temporalio/common": "^0.11.0",
"@temporalio/proto": "^0.11.0"
},

@@ -30,3 +30,3 @@ "bugs": {

},
"gitHead": "a46c7b9ce2e78d9f615bfdb1730af0956a25eb61"
"gitHead": "df1ef24e1caff78f2b712e1f82e59d037ae9c2b4"
}

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