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

@temporalio/common

Package Overview
Dependencies
Maintainers
8
Versions
65
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@temporalio/common - npm Package Compare versions

Comparing version 1.8.1 to 1.8.2

20

lib/converter/failure-converter.js

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

errorToFailureInner(err, payloadConverter) {
if (failure_1.TemporalFailure.is(err)) {
if (err instanceof failure_1.TemporalFailure) {
if (err.failure)

@@ -132,3 +132,3 @@ return err.failure;

};
if (failure_1.ActivityFailure.is(err)) {
if (err instanceof failure_1.ActivityFailure) {
return {

@@ -142,3 +142,3 @@ ...base,

}
if (failure_1.ChildWorkflowFailure.is(err)) {
if (err instanceof failure_1.ChildWorkflowFailure) {
return {

@@ -153,3 +153,3 @@ ...base,

}
if (failure_1.ApplicationFailure.is(err)) {
if (err instanceof failure_1.ApplicationFailure) {
return {

@@ -166,3 +166,3 @@ ...base,

}
if (failure_1.CancelledFailure.is(err)) {
if (err instanceof failure_1.CancelledFailure) {
return {

@@ -177,3 +177,3 @@ ...base,

}
if (failure_1.TimeoutFailure.is(err)) {
if (err instanceof failure_1.TimeoutFailure) {
return {

@@ -189,3 +189,3 @@ ...base,

}
if (failure_1.ServerFailure.is(err)) {
if (err instanceof failure_1.ServerFailure) {
return {

@@ -196,3 +196,3 @@ ...base,

}
if (failure_1.TerminatedFailure.is(err)) {
if (err instanceof failure_1.TerminatedFailure) {
return {

@@ -209,7 +209,7 @@ ...base,

};
if ((0, type_helpers_1.isRecord)(err) && (0, type_helpers_1.hasOwnProperties)(err, ['message', 'stack'])) {
if ((0, type_helpers_1.isError)(err)) {
return {
...base,
message: String(err.message) ?? '',
stackTrace: cutoffStackTrace(String(err.stack)),
stackTrace: cutoffStackTrace(err.stack),
cause: this.optionalErrorToOptionalFailure(err.cause, payloadConverter),

@@ -216,0 +216,0 @@ };

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

toPayload(values) {
if (!(values instanceof Array)) {
if (!Array.isArray(values)) {
throw new errors_1.ValueError(`SearchAttribute value must be an array`);

@@ -247,3 +247,3 @@ }

const value = this.jsonConverter.fromPayload(payload);
let arrayWrappedValue = value instanceof Array ? value : [value];
let arrayWrappedValue = Array.isArray(value) ? value : [value];
const searchAttributeType = (0, encoding_1.decode)(payload.metadata.type);

@@ -250,0 +250,0 @@ if (searchAttributeType === 'Datetime') {

@@ -33,2 +33,3 @@ "use strict";

const types_1 = require("./types");
const GLOBAL_BUFFER = globalThis.constructor.constructor('return globalThis.Buffer')();
class ProtobufPayloadConverter {

@@ -120,14 +121,64 @@ // Don't use type Root here because root.d.ts doesn't export Root, so users would have to type assert

}
const jsonValue = protoJsonSerializer.toProto3JSON(value);
return this.constructPayload({
messageTypeName: getNamespacedTypeName(value.$type),
message: (0, encoding_1.encode)(JSON.stringify(jsonValue)),
});
const hasBufferChanged = setBufferInGlobal();
try {
const jsonValue = protoJsonSerializer.toProto3JSON(value);
return this.constructPayload({
messageTypeName: getNamespacedTypeName(value.$type),
message: (0, encoding_1.encode)(JSON.stringify(jsonValue)),
});
}
finally {
resetBufferInGlobal(hasBufferChanged);
}
}
fromPayload(content) {
const { messageType, data } = this.validatePayload(content);
return protoJsonSerializer.fromProto3JSON(messageType, JSON.parse((0, encoding_1.decode)(data)));
const hasBufferChanged = setBufferInGlobal();
try {
const { messageType, data } = this.validatePayload(content);
const res = protoJsonSerializer.fromProto3JSON(messageType, JSON.parse((0, encoding_1.decode)(data)));
if (Buffer.isBuffer(res)) {
return new Uint8Array(res);
}
replaceBuffers(res);
return res;
}
finally {
resetBufferInGlobal(hasBufferChanged);
}
}
}
exports.ProtobufJsonPayloadConverter = ProtobufJsonPayloadConverter;
function replaceBuffers(obj) {
const replaceBuffersImpl = (value, key, target) => {
if (Buffer.isBuffer(value)) {
target[key] = new Uint8Array(value);
}
else {
replaceBuffers(value);
}
};
if (obj != null && typeof obj === 'object') {
// Performance optimization for large arrays
if (Array.isArray(obj)) {
obj.forEach(replaceBuffersImpl);
}
else {
for (const [key, value] of Object.entries(obj)) {
replaceBuffersImpl(value, key, obj);
}
}
}
}
function setBufferInGlobal() {
if (typeof globalThis.Buffer === 'undefined') {
globalThis.Buffer = GLOBAL_BUFFER;
return true;
}
return false;
}
function resetBufferInGlobal(hasChanged) {
if (hasChanged) {
delete globalThis.Buffer;
}
}
function isProtobufType(type) {

@@ -134,0 +185,0 @@ return ((0, type_helpers_1.isRecord)(type) &&

@@ -7,3 +7,2 @@ import { TemporalFailure } from './failure';

readonly cause?: unknown;
readonly name: string;
constructor(message: string | undefined, cause?: unknown);

@@ -15,3 +14,2 @@ }

export declare class PayloadConverterError extends ValueError {
readonly name: string;
}

@@ -22,5 +20,3 @@ /**

export declare class IllegalStateError extends Error {
readonly name: string;
}
declare const isWorkflowExecutionAlreadyStartedError: unique symbol;
/**

@@ -37,12 +33,3 @@ * This exception is thrown in the following cases:

readonly workflowType: string;
readonly name: string;
constructor(message: string, workflowId: string, workflowType: string);
/**
* Marker to determine whether an error is an instance of WorkflowExecutionAlreadyStartedError.
*/
protected readonly [isWorkflowExecutionAlreadyStartedError] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is WorkflowExecutionAlreadyStartedError;
}

@@ -59,3 +46,2 @@ /**

readonly runId: string | undefined;
readonly name: string;
constructor(message: string, workflowId: string, runId: string | undefined);

@@ -68,5 +54,3 @@ }

readonly namespace: string;
readonly name: string;
constructor(namespace: string);
}
export {};
"use strict";
var _a;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NamespaceNotFoundError = exports.WorkflowNotFoundError = exports.WorkflowExecutionAlreadyStartedError = exports.IllegalStateError = exports.PayloadConverterError = exports.ValueError = void 0;
const failure_1 = require("./failure");
const type_helpers_1 = require("./type-helpers");
/**
* Thrown from code that receives a value that is unexpected or that it's unable to handle.
*/
class ValueError extends Error {
let ValueError = class ValueError extends Error {
constructor(message, cause) {
super(message ?? undefined);
this.cause = cause;
this.name = 'ValueError';
}
}
};
ValueError = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('ValueError')
], ValueError);
exports.ValueError = ValueError;

@@ -20,8 +28,7 @@ /**

*/
class PayloadConverterError extends ValueError {
constructor() {
super(...arguments);
this.name = 'PayloadConverterError';
}
}
let PayloadConverterError = class PayloadConverterError extends ValueError {
};
PayloadConverterError = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('PayloadConverterError')
], PayloadConverterError);
exports.PayloadConverterError = PayloadConverterError;

@@ -31,10 +38,8 @@ /**

*/
class IllegalStateError extends Error {
constructor() {
super(...arguments);
this.name = 'IllegalStateError';
}
}
let IllegalStateError = class IllegalStateError extends Error {
};
IllegalStateError = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('IllegalStateError')
], IllegalStateError);
exports.IllegalStateError = IllegalStateError;
const isWorkflowExecutionAlreadyStartedError = Symbol.for('__temporal_isWorkflowExecutionAlreadyStartedError');
/**

@@ -48,3 +53,3 @@ * This exception is thrown in the following cases:

*/
class WorkflowExecutionAlreadyStartedError extends failure_1.TemporalFailure {
let WorkflowExecutionAlreadyStartedError = class WorkflowExecutionAlreadyStartedError extends failure_1.TemporalFailure {
constructor(message, workflowId, workflowType) {

@@ -54,18 +59,8 @@ super(message);

this.workflowType = workflowType;
this.name = 'WorkflowExecutionAlreadyStartedError';
/**
* Marker to determine whether an error is an instance of WorkflowExecutionAlreadyStartedError.
*/
this[_a] = true;
}
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error) {
return (error instanceof WorkflowExecutionAlreadyStartedError ||
(error instanceof Error && error[isWorkflowExecutionAlreadyStartedError]));
}
}
};
WorkflowExecutionAlreadyStartedError = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('WorkflowExecutionAlreadyStartedError')
], WorkflowExecutionAlreadyStartedError);
exports.WorkflowExecutionAlreadyStartedError = WorkflowExecutionAlreadyStartedError;
_a = isWorkflowExecutionAlreadyStartedError;
/**

@@ -78,3 +73,3 @@ * Thrown when a Workflow with the given Id is not known to Temporal Server.

*/
class WorkflowNotFoundError extends Error {
let WorkflowNotFoundError = class WorkflowNotFoundError extends Error {
constructor(message, workflowId, runId) {

@@ -84,5 +79,7 @@ super(message);

this.runId = runId;
this.name = 'WorkflowNotFoundError';
}
}
};
WorkflowNotFoundError = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('WorkflowNotFoundError')
], WorkflowNotFoundError);
exports.WorkflowNotFoundError = WorkflowNotFoundError;

@@ -92,10 +89,12 @@ /**

*/
class NamespaceNotFoundError extends Error {
let NamespaceNotFoundError = class NamespaceNotFoundError extends Error {
constructor(namespace) {
super(`Namespace not found: '${namespace}'`);
this.namespace = namespace;
this.name = 'NamespaceNotFoundError';
}
}
};
NamespaceNotFoundError = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('NamespaceNotFoundError')
], NamespaceNotFoundError);
exports.NamespaceNotFoundError = NamespaceNotFoundError;
//# sourceMappingURL=errors.js.map

@@ -22,3 +22,2 @@ import type { temporal } from '@temporalio/proto';

export type WorkflowExecution = temporal.api.common.v1.IWorkflowExecution;
declare const isTemporalFailure: unique symbol;
/**

@@ -33,3 +32,2 @@ * Represents failures that can cross Workflow and Activity boundaries.

readonly cause?: Error | undefined;
readonly name: string;
/**

@@ -42,27 +40,8 @@ * The original failure that constructed this error.

constructor(message?: string | undefined | null, cause?: Error | undefined);
/**
* Marker to determine whether an error is an instance of TemporalFailure.
*/
protected readonly [isTemporalFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is TemporalFailure;
}
declare const isServerFailure: unique symbol;
/** Exceptions originated at the Temporal service. */
export declare class ServerFailure extends TemporalFailure {
readonly nonRetryable: boolean;
readonly name: string;
constructor(message: string | undefined, nonRetryable: boolean, cause?: Error);
/**
* Marker to determine whether an error is an instance of ServerFailure.
*/
protected readonly [isServerFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is ServerFailure;
}
declare const isApplicationFailure: unique symbol;
/**

@@ -94,3 +73,2 @@ * `ApplicationFailure`s are used to communicate application-specific failures in Workflows and Activities.

readonly details?: unknown[] | null | undefined;
readonly name: string;
/**

@@ -101,10 +79,2 @@ * Alternatively, use {@link fromError} or {@link create}.

/**
* Marker to determine whether an error is an instance of ApplicationFailure.
*/
protected readonly [isApplicationFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is ApplicationFailure;
/**
* Create a new `ApplicationFailure` from an Error object.

@@ -167,3 +137,2 @@ *

}
declare const isCancelledFailure: unique symbol;
/**

@@ -178,14 +147,4 @@ * This error is thrown when Cancellation has been requested. To allow Cancellation to happen, let it propagate. To

readonly details: unknown[];
readonly name: string;
constructor(message: string | undefined, details?: unknown[], cause?: Error);
/**
* Marker to determine whether an error is an instance of CancelledFailure.
*/
protected readonly [isCancelledFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is CancelledFailure;
}
declare const isTerminatedFailure: unique symbol;
/**

@@ -195,14 +154,4 @@ * Used as the `cause` when a Workflow has been terminated

export declare class TerminatedFailure extends TemporalFailure {
readonly name: string;
constructor(message: string | undefined, cause?: Error);
/**
* Marker to determine whether an error is an instance of TerminatedFailure.
*/
protected readonly [isTerminatedFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is TerminatedFailure;
}
declare const isTimeoutFailure: unique symbol;
/**

@@ -214,14 +163,4 @@ * Used to represent timeouts of Activities and Workflows

readonly timeoutType: TimeoutType;
readonly name: string;
constructor(message: string | undefined, lastHeartbeatDetails: unknown, timeoutType: TimeoutType);
/**
* Marker to determine whether an error is an instance of TimeoutFailure.
*/
protected readonly [isTimeoutFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is TimeoutFailure;
}
declare const isActivityFailure: unique symbol;
/**

@@ -238,14 +177,4 @@ * Contains information about an Activity failure. Always contains the original reason for the failure as its `cause`.

readonly identity: string | undefined;
readonly name: string;
constructor(message: string | undefined, activityType: string, activityId: string | undefined, retryState: RetryState, identity: string | undefined, cause?: Error);
/**
* Marker to determine whether an error is an instance of ActivityFailure.
*/
protected readonly [isActivityFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is ActivityFailure;
}
declare const isChildWorkflowFailure: unique symbol;
/**

@@ -262,12 +191,3 @@ * Contains information about a Child Workflow failure. Always contains the reason for the failure as its {@link cause}.

readonly retryState: RetryState;
readonly name: string;
constructor(namespace: string | undefined, execution: WorkflowExecution, workflowType: string, retryState: RetryState, cause?: Error);
/**
* Marker to determine whether an error is an instance of ChildWorkflowFailure.
*/
protected readonly [isChildWorkflowFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is ChildWorkflowFailure;
}

@@ -299,2 +219,1 @@ /**

export declare function rootCause(error: unknown): string | undefined;
export {};
"use strict";
var _a, _b, _c, _d, _e, _f, _g, _h;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -34,3 +39,2 @@ exports.rootCause = exports.ensureTemporalFailure = exports.ensureApplicationFailure = exports.ChildWorkflowFailure = exports.ActivityFailure = exports.TimeoutFailure = exports.TerminatedFailure = exports.CancelledFailure = exports.ApplicationFailure = exports.ServerFailure = exports.TemporalFailure = exports.RetryState = exports.TimeoutType = exports.FAILURE_SOURCE = void 0;

(0, type_helpers_1.checkExtends)();
const isTemporalFailure = Symbol.for('__temporal_isTemporalFailure');
/**

@@ -43,43 +47,23 @@ * Represents failures that can cross Workflow and Activity boundaries.

*/
class TemporalFailure extends Error {
let TemporalFailure = class TemporalFailure extends Error {
constructor(message, cause) {
super(message ?? undefined);
this.cause = cause;
this.name = 'TemporalFailure';
/**
* Marker to determine whether an error is an instance of TemporalFailure.
*/
this[_a] = true;
}
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error) {
return error instanceof TemporalFailure || error?.[isTemporalFailure] === true;
}
}
};
TemporalFailure = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('TemporalFailure')
], TemporalFailure);
exports.TemporalFailure = TemporalFailure;
_a = isTemporalFailure;
const isServerFailure = Symbol.for('__temporal_isServerFailure');
/** Exceptions originated at the Temporal service. */
class ServerFailure extends TemporalFailure {
let ServerFailure = class ServerFailure extends TemporalFailure {
constructor(message, nonRetryable, cause) {
super(message, cause);
this.nonRetryable = nonRetryable;
this.name = 'ServerFailure';
/**
* Marker to determine whether an error is an instance of ServerFailure.
*/
this[_b] = true;
}
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error) {
return error instanceof ServerFailure || error?.[isServerFailure] === true;
}
}
};
ServerFailure = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('ServerFailure')
], ServerFailure);
exports.ServerFailure = ServerFailure;
_b = isServerFailure;
const isApplicationFailure = Symbol.for('__temporal_isApplicationFailure');
/**

@@ -107,3 +91,3 @@ * `ApplicationFailure`s are used to communicate application-specific failures in Workflows and Activities.

*/
class ApplicationFailure extends TemporalFailure {
let ApplicationFailure = class ApplicationFailure extends TemporalFailure {
/**

@@ -117,15 +101,4 @@ * Alternatively, use {@link fromError} or {@link create}.

this.details = details;
this.name = 'ApplicationFailure';
/**
* Marker to determine whether an error is an instance of ApplicationFailure.
*/
this[_c] = true;
}
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error) {
return error instanceof ApplicationFailure || error?.[isApplicationFailure] === true;
}
/**
* Create a new `ApplicationFailure` from an Error object.

@@ -174,6 +147,7 @@ *

}
}
};
ApplicationFailure = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('ApplicationFailure')
], ApplicationFailure);
exports.ApplicationFailure = ApplicationFailure;
_c = isApplicationFailure;
const isCancelledFailure = Symbol.for('__temporal_isCancelledFailure');
/**

@@ -186,48 +160,28 @@ * This error is thrown when Cancellation has been requested. To allow Cancellation to happen, let it propagate. To

*/
class CancelledFailure extends TemporalFailure {
let CancelledFailure = class CancelledFailure extends TemporalFailure {
constructor(message, details = [], cause) {
super(message, cause);
this.details = details;
this.name = 'CancelledFailure';
/**
* Marker to determine whether an error is an instance of CancelledFailure.
*/
this[_d] = true;
}
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error) {
return error instanceof CancelledFailure || error?.[isCancelledFailure] === true;
}
}
};
CancelledFailure = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('CancelledFailure')
], CancelledFailure);
exports.CancelledFailure = CancelledFailure;
_d = isCancelledFailure;
const isTerminatedFailure = Symbol.for('__temporal_isTerminatedFailure');
/**
* Used as the `cause` when a Workflow has been terminated
*/
class TerminatedFailure extends TemporalFailure {
let TerminatedFailure = class TerminatedFailure extends TemporalFailure {
constructor(message, cause) {
super(message, cause);
this.name = 'TerminatedFailure';
/**
* Marker to determine whether an error is an instance of TerminatedFailure.
*/
this[_e] = true;
}
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error) {
return error instanceof TerminatedFailure || error?.[isTerminatedFailure] === true;
}
}
};
TerminatedFailure = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('TerminatedFailure')
], TerminatedFailure);
exports.TerminatedFailure = TerminatedFailure;
_e = isTerminatedFailure;
const isTimeoutFailure = Symbol.for('__temporal_isTimeoutFailure');
/**
* Used to represent timeouts of Activities and Workflows
*/
class TimeoutFailure extends TemporalFailure {
let TimeoutFailure = class TimeoutFailure extends TemporalFailure {
constructor(message, lastHeartbeatDetails, timeoutType) {

@@ -237,18 +191,8 @@ super(message);

this.timeoutType = timeoutType;
this.name = 'TimeoutFailure';
/**
* Marker to determine whether an error is an instance of TimeoutFailure.
*/
this[_f] = true;
}
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error) {
return error instanceof TimeoutFailure || error?.[isTimeoutFailure] === true;
}
}
};
TimeoutFailure = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('TimeoutFailure')
], TimeoutFailure);
exports.TimeoutFailure = TimeoutFailure;
_f = isTimeoutFailure;
const isActivityFailure = Symbol.for('__temporal_isActivityFailure');
/**

@@ -260,3 +204,3 @@ * Contains information about an Activity failure. Always contains the original reason for the failure as its `cause`.

*/
class ActivityFailure extends TemporalFailure {
let ActivityFailure = class ActivityFailure extends TemporalFailure {
constructor(message, activityType, activityId, retryState, identity, cause) {

@@ -268,18 +212,8 @@ super(message, cause);

this.identity = identity;
this.name = 'ActivityFailure';
/**
* Marker to determine whether an error is an instance of ActivityFailure.
*/
this[_g] = true;
}
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error) {
return error instanceof ActivityFailure || error?.[isActivityFailure] === true;
}
}
};
ActivityFailure = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('ActivityFailure')
], ActivityFailure);
exports.ActivityFailure = ActivityFailure;
_g = isActivityFailure;
const isChildWorkflowFailure = Symbol.for('__temporal_isChildWorkflowFailure');
/**

@@ -291,3 +225,3 @@ * Contains information about a Child Workflow failure. Always contains the reason for the failure as its {@link cause}.

*/
class ChildWorkflowFailure extends TemporalFailure {
let ChildWorkflowFailure = class ChildWorkflowFailure extends TemporalFailure {
constructor(namespace, execution, workflowType, retryState, cause) {

@@ -299,17 +233,8 @@ super('Child Workflow execution failed', cause);

this.retryState = retryState;
this.name = 'ChildWorkflowFailure';
/**
* Marker to determine whether an error is an instance of ChildWorkflowFailure.
*/
this[_h] = true;
}
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error) {
return error instanceof ChildWorkflowFailure || error?.[isChildWorkflowFailure] === true;
}
}
};
ChildWorkflowFailure = __decorate([
(0, type_helpers_1.SymbolBasedInstanceOfError)('ChildWorkflowFailure')
], ChildWorkflowFailure);
exports.ChildWorkflowFailure = ChildWorkflowFailure;
_h = isChildWorkflowFailure;
/**

@@ -325,3 +250,3 @@ * If `error` is already an `ApplicationFailure`, returns `error`.

function ensureApplicationFailure(error) {
if (ApplicationFailure.is(error)) {
if (error instanceof ApplicationFailure) {
return error;

@@ -344,3 +269,3 @@ }

function ensureTemporalFailure(err) {
if (TemporalFailure.is(err)) {
if (err instanceof TemporalFailure) {
return err;

@@ -358,14 +283,8 @@ }

function rootCause(error) {
if (TemporalFailure.is(error)) {
if (error instanceof TemporalFailure) {
return error.cause ? rootCause(error.cause) : error.message;
}
if (error instanceof Error) {
return error.message;
}
if (typeof error === 'string') {
return error;
}
return undefined;
return (0, type_helpers_1.errorMessage)(error);
}
exports.rootCause = rootCause;
//# sourceMappingURL=failure.js.map

@@ -17,2 +17,6 @@ /** Shorthand alias */

export declare function hasOwnProperties<X extends Record<string, unknown>, Y extends PropertyKey>(record: X, props: Y[]): record is X & Record<Y, unknown>;
export declare function isError(error: unknown): error is Error;
export declare function isAbortError(error: unknown): error is Error & {
name: 'AbortError';
};
/**

@@ -30,1 +34,30 @@ * Get `error.message` (or `undefined` if not present)

export declare function assertNever(msg: string, x: never): never;
export type Class<E extends Error> = {
new (...args: any[]): E;
prototype: E;
};
/**
* A decorator to be used on error classes. It adds the 'name' property AND provides a custom
* 'instanceof' handler that works correctly across execution contexts.
*
* ### Details ###
*
* According to the EcmaScript's spec, the default behavior of JavaScript's `x instanceof Y` operator is to walk up the
* prototype chain of object 'x', checking if any constructor in that hierarchy is _exactly the same object_ as the
* constructor function 'Y'.
*
* Unfortunately, it happens in various situations that different constructor function objects get created for what
* appears to be the very same class. This leads to surprising behavior where `instanceof` returns false though it is
* known that the object is indeed an instance of that class. One particular case where this happens is when constructor
* 'Y' belongs to a different realm than the constuctor with which 'x' was instantiated. Another case is when two copies
* of the same library gets loaded in the same realm.
*
* In practice, this tends to cause issues when crossing the workflow-sandboxing boundary (since Node's vm module
* really creates new execution realms), as well as when running tests using Jest (see https://github.com/jestjs/jest/issues/2549
* for some details on that one).
*
* This function injects a custom 'instanceof' handler into the prototype of 'clazz', which is both cross-realm safe and
* cross-copies-of-the-same-lib safe. It works by adding a special symbol property to the prototype of 'clazz', and then
* checking for the presence of that symbol.
*/
export declare function SymbolBasedInstanceOfError<E extends Error>(markerName: string): (clazz: Class<E>) => void;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertNever = exports.errorCode = exports.errorMessage = exports.hasOwnProperties = exports.hasOwnProperty = exports.isRecord = exports.checkExtends = void 0;
exports.SymbolBasedInstanceOfError = exports.assertNever = exports.errorCode = exports.errorMessage = exports.isAbortError = exports.isError = exports.hasOwnProperties = exports.hasOwnProperty = exports.isRecord = exports.checkExtends = void 0;
/** Verify that an type _Copy extends _Orig */

@@ -13,3 +13,2 @@ function checkExtends() {

exports.isRecord = isRecord;
// ts-prune-ignore-next
function hasOwnProperty(record, prop) {

@@ -23,2 +22,13 @@ return prop in record;

exports.hasOwnProperties = hasOwnProperties;
function isError(error) {
return (isRecord(error) &&
typeof error.name === 'string' &&
typeof error.message === 'string' &&
(error.stack == null || typeof error.stack === 'string'));
}
exports.isError = isError;
function isAbortError(error) {
return isError(error) && error.name === 'AbortError';
}
exports.isAbortError = isAbortError;
/**

@@ -28,11 +38,14 @@ * Get `error.message` (or `undefined` if not present)

function errorMessage(error) {
if (typeof error === 'string') {
if (isError(error)) {
return error.message;
}
else if (typeof error === 'string') {
return error;
}
if (error instanceof Error) {
return error.message;
}
return undefined;
}
exports.errorMessage = errorMessage;
function isErrorWithCode(error) {
return isRecord(error) && typeof error.code === 'string';
}
/**

@@ -42,5 +55,3 @@ * Get `error.code` (or `undefined` if not present)

function errorCode(error) {
if (typeof error === 'object' &&
error.code !== undefined &&
typeof error.code === 'string') {
if (isErrorWithCode(error)) {
return error.code;

@@ -58,2 +69,52 @@ }

exports.assertNever = assertNever;
/**
* A decorator to be used on error classes. It adds the 'name' property AND provides a custom
* 'instanceof' handler that works correctly across execution contexts.
*
* ### Details ###
*
* According to the EcmaScript's spec, the default behavior of JavaScript's `x instanceof Y` operator is to walk up the
* prototype chain of object 'x', checking if any constructor in that hierarchy is _exactly the same object_ as the
* constructor function 'Y'.
*
* Unfortunately, it happens in various situations that different constructor function objects get created for what
* appears to be the very same class. This leads to surprising behavior where `instanceof` returns false though it is
* known that the object is indeed an instance of that class. One particular case where this happens is when constructor
* 'Y' belongs to a different realm than the constuctor with which 'x' was instantiated. Another case is when two copies
* of the same library gets loaded in the same realm.
*
* In practice, this tends to cause issues when crossing the workflow-sandboxing boundary (since Node's vm module
* really creates new execution realms), as well as when running tests using Jest (see https://github.com/jestjs/jest/issues/2549
* for some details on that one).
*
* This function injects a custom 'instanceof' handler into the prototype of 'clazz', which is both cross-realm safe and
* cross-copies-of-the-same-lib safe. It works by adding a special symbol property to the prototype of 'clazz', and then
* checking for the presence of that symbol.
*/
function SymbolBasedInstanceOfError(markerName) {
return (clazz) => {
const marker = Symbol.for(`__temporal_is${markerName}`);
Object.defineProperty(clazz.prototype, 'name', { value: markerName, enumerable: true });
Object.defineProperty(clazz.prototype, marker, { value: true, enumerable: false });
Object.defineProperty(clazz, Symbol.hasInstance, {
// eslint-disable-next-line object-shorthand
value: function (error) {
if (this === clazz) {
return isRecord(error) && error[marker] === true;
}
else {
// 'this' must be a _subclass_ of clazz that doesn't redefined [Symbol.hasInstance], so that it inherited
// from clazz's [Symbol.hasInstance]. If we don't handle this particular situation, then
// `x instanceof SubclassOfParent` would return true for any instance of 'Parent', which is clearly wrong.
//
// Ideally, it'd be preferable to avoid this case entirely, by making sure that all subclasses of 'clazz'
// redefine [Symbol.hasInstance], but we can't enforce that. We therefore fallback to the default instanceof
// behavior (which is NOT cross-realm safe).
return this.prototype.isPrototypeOf(error); // eslint-disable-line no-prototype-builtins
}
},
});
};
}
exports.SymbolBasedInstanceOfError = SymbolBasedInstanceOfError;
//# sourceMappingURL=type-helpers.js.map
{
"name": "@temporalio/common",
"version": "1.8.1",
"version": "1.8.2",
"description": "Common library for code that's used across the Client, Worker, and/or Workflow",

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

"@opentelemetry/api": "^1.4.1",
"@temporalio/proto": "1.8.1",
"@temporalio/proto": "1.8.2",
"long": "^5.2.0",

@@ -39,3 +39,3 @@ "ms": "^3.0.0-canary.1",

],
"gitHead": "97808111bbec478260e915726bb9730a489f8fa4"
"gitHead": "d85bf54da757741b438f8d39a0e7265b80d4f0d6"
}

@@ -15,3 +15,3 @@ import {

} from '../failure';
import { hasOwnProperties, isRecord } from '../type-helpers';
import { isError } from '../type-helpers';
import { arrayFromPayloads, fromPayloadsAtIndex, PayloadConverter, toPayloads } from './payload-converter';

@@ -223,3 +223,3 @@

errorToFailureInner(err: unknown, payloadConverter: PayloadConverter): ProtoFailure {
if (TemporalFailure.is(err)) {
if (err instanceof TemporalFailure) {
if (err.failure) return err.failure;

@@ -233,3 +233,3 @@ const base = {

if (ActivityFailure.is(err)) {
if (err instanceof ActivityFailure) {
return {

@@ -243,3 +243,3 @@ ...base,

}
if (ChildWorkflowFailure.is(err)) {
if (err instanceof ChildWorkflowFailure) {
return {

@@ -254,3 +254,3 @@ ...base,

}
if (ApplicationFailure.is(err)) {
if (err instanceof ApplicationFailure) {
return {

@@ -268,3 +268,3 @@ ...base,

}
if (CancelledFailure.is(err)) {
if (err instanceof CancelledFailure) {
return {

@@ -280,3 +280,3 @@ ...base,

}
if (TimeoutFailure.is(err)) {
if (err instanceof TimeoutFailure) {
return {

@@ -292,3 +292,3 @@ ...base,

}
if (ServerFailure.is(err)) {
if (err instanceof ServerFailure) {
return {

@@ -299,3 +299,3 @@ ...base,

}
if (TerminatedFailure.is(err)) {
if (err instanceof TerminatedFailure) {
return {

@@ -314,8 +314,8 @@ ...base,

if (isRecord(err) && hasOwnProperties(err, ['message', 'stack'])) {
if (isError(err)) {
return {
...base,
message: String(err.message) ?? '',
stackTrace: cutoffStackTrace(String(err.stack)),
cause: this.optionalErrorToOptionalFailure(err.cause, payloadConverter),
stackTrace: cutoffStackTrace(err.stack),
cause: this.optionalErrorToOptionalFailure((err as any).cause, payloadConverter),
};

@@ -322,0 +322,0 @@ }

@@ -263,3 +263,3 @@ import { decode, encode } from '../encoding';

public toPayload(values: unknown): Payload {
if (!(values instanceof Array)) {
if (!Array.isArray(values)) {
throw new ValueError(`SearchAttribute value must be an array`);

@@ -313,3 +313,3 @@ }

const value = this.jsonConverter.fromPayload(payload);
let arrayWrappedValue = value instanceof Array ? value : [value];
let arrayWrappedValue = Array.isArray(value) ? value : [value];

@@ -316,0 +316,0 @@ const searchAttributeType = decode(payload.metadata.type);

@@ -17,2 +17,4 @@ import * as protoJsonSerializer from 'proto3-json-serializer';

const GLOBAL_BUFFER = globalThis.constructor.constructor('return globalThis.Buffer')();
abstract class ProtobufPayloadConverter implements PayloadConverterWithEncoding {

@@ -125,16 +127,68 @@ protected readonly root: Root | undefined;

const jsonValue = protoJsonSerializer.toProto3JSON(value);
const hasBufferChanged = setBufferInGlobal();
try {
const jsonValue = protoJsonSerializer.toProto3JSON(value);
return this.constructPayload({
messageTypeName: getNamespacedTypeName(value.$type),
message: encode(JSON.stringify(jsonValue)),
});
return this.constructPayload({
messageTypeName: getNamespacedTypeName(value.$type),
message: encode(JSON.stringify(jsonValue)),
});
} finally {
resetBufferInGlobal(hasBufferChanged);
}
}
public fromPayload<T>(content: Payload): T {
const { messageType, data } = this.validatePayload(content);
return protoJsonSerializer.fromProto3JSON(messageType, JSON.parse(decode(data))) as unknown as T;
const hasBufferChanged = setBufferInGlobal();
try {
const { messageType, data } = this.validatePayload(content);
const res = protoJsonSerializer.fromProto3JSON(messageType, JSON.parse(decode(data))) as unknown as T;
if (Buffer.isBuffer(res)) {
return new Uint8Array(res) as any;
}
replaceBuffers(res);
return res;
} finally {
resetBufferInGlobal(hasBufferChanged);
}
}
}
function replaceBuffers<X>(obj: X) {
const replaceBuffersImpl = <Y>(value: any, key: string | number, target: Y) => {
if (Buffer.isBuffer(value)) {
// Need to copy. `Buffer` manages a pool slab, internally reused when Buffer objects are GC.
type T = keyof typeof target;
target[key as T] = new Uint8Array(value) as any;
} else {
replaceBuffers(value);
}
};
if (obj != null && typeof obj === 'object') {
// Performance optimization for large arrays
if (Array.isArray(obj)) {
obj.forEach(replaceBuffersImpl);
} else {
for (const [key, value] of Object.entries(obj)) {
replaceBuffersImpl(value, key, obj);
}
}
}
}
function setBufferInGlobal(): boolean {
if (typeof globalThis.Buffer === 'undefined') {
globalThis.Buffer = GLOBAL_BUFFER;
return true;
}
return false;
}
function resetBufferInGlobal(hasChanged: boolean): void {
if (hasChanged) {
delete (globalThis as any).Buffer;
}
}
function isProtobufType(type: unknown): type is Type {

@@ -141,0 +195,0 @@ return (

import { TemporalFailure } from './failure';
import { SymbolBasedInstanceOfError } from './type-helpers';

@@ -6,5 +7,4 @@ /**

*/
@SymbolBasedInstanceOfError('ValueError')
export class ValueError extends Error {
public readonly name: string = 'ValueError';
constructor(message: string | undefined, public readonly cause?: unknown) {

@@ -18,5 +18,4 @@ super(message ?? undefined);

*/
export class PayloadConverterError extends ValueError {
public readonly name: string = 'PayloadConverterError';
}
@SymbolBasedInstanceOfError('PayloadConverterError')
export class PayloadConverterError extends ValueError {}

@@ -26,8 +25,5 @@ /**

*/
export class IllegalStateError extends Error {
public readonly name: string = 'IllegalStateError';
}
@SymbolBasedInstanceOfError('IllegalStateError')
export class IllegalStateError extends Error {}
const isWorkflowExecutionAlreadyStartedError = Symbol.for('__temporal_isWorkflowExecutionAlreadyStartedError');
/**

@@ -41,23 +37,7 @@ * This exception is thrown in the following cases:

*/
@SymbolBasedInstanceOfError('WorkflowExecutionAlreadyStartedError')
export class WorkflowExecutionAlreadyStartedError extends TemporalFailure {
public readonly name: string = 'WorkflowExecutionAlreadyStartedError';
constructor(message: string, public readonly workflowId: string, public readonly workflowType: string) {
super(message);
}
/**
* Marker to determine whether an error is an instance of WorkflowExecutionAlreadyStartedError.
*/
protected readonly [isWorkflowExecutionAlreadyStartedError] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is WorkflowExecutionAlreadyStartedError {
return (
error instanceof WorkflowExecutionAlreadyStartedError ||
(error instanceof Error && (error as any)[isWorkflowExecutionAlreadyStartedError])
);
}
}

@@ -72,5 +52,4 @@

*/
@SymbolBasedInstanceOfError('WorkflowNotFoundError')
export class WorkflowNotFoundError extends Error {
public readonly name: string = 'WorkflowNotFoundError';
constructor(message: string, public readonly workflowId: string, public readonly runId: string | undefined) {

@@ -84,5 +63,4 @@ super(message);

*/
@SymbolBasedInstanceOfError('NamespaceNotFoundError')
export class NamespaceNotFoundError extends Error {
public readonly name: string = 'NamespaceNotFoundError';
constructor(public readonly namespace: string) {

@@ -89,0 +67,0 @@ super(`Namespace not found: '${namespace}'`);

import type { temporal } from '@temporalio/proto';
import { checkExtends, isRecord } from './type-helpers';
import { checkExtends, errorMessage, isRecord, SymbolBasedInstanceOfError } from './type-helpers';

@@ -38,4 +38,2 @@ export const FAILURE_SOURCE = 'TypeScriptSDK';

const isTemporalFailure = Symbol.for('__temporal_isTemporalFailure');
/**

@@ -48,4 +46,4 @@ * Represents failures that can cross Workflow and Activity boundaries.

*/
@SymbolBasedInstanceOfError('TemporalFailure')
export class TemporalFailure extends Error {
public readonly name: string = 'TemporalFailure';
/**

@@ -61,41 +59,12 @@ * The original failure that constructed this error.

}
/**
* Marker to determine whether an error is an instance of TemporalFailure.
*/
protected readonly [isTemporalFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is TemporalFailure {
return error instanceof TemporalFailure || (error as any)?.[isTemporalFailure] === true;
}
}
const isServerFailure = Symbol.for('__temporal_isServerFailure');
/** Exceptions originated at the Temporal service. */
@SymbolBasedInstanceOfError('ServerFailure')
export class ServerFailure extends TemporalFailure {
public readonly name: string = 'ServerFailure';
constructor(message: string | undefined, public readonly nonRetryable: boolean, cause?: Error) {
super(message, cause);
}
/**
* Marker to determine whether an error is an instance of ServerFailure.
*/
protected readonly [isServerFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is ServerFailure {
return error instanceof ServerFailure || (error as any)?.[isServerFailure] === true;
}
}
const isApplicationFailure = Symbol.for('__temporal_isApplicationFailure');
/**

@@ -123,5 +92,4 @@ * `ApplicationFailure`s are used to communicate application-specific failures in Workflows and Activities.

*/
@SymbolBasedInstanceOfError('ApplicationFailure')
export class ApplicationFailure extends TemporalFailure {
public readonly name: string = 'ApplicationFailure';
/**

@@ -141,14 +109,2 @@ * Alternatively, use {@link fromError} or {@link create}.

/**
* Marker to determine whether an error is an instance of ApplicationFailure.
*/
protected readonly [isApplicationFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is ApplicationFailure {
return error instanceof ApplicationFailure || (error as any)?.[isApplicationFailure] === true;
}
/**
* Create a new `ApplicationFailure` from an Error object.

@@ -231,4 +187,2 @@ *

const isCancelledFailure = Symbol.for('__temporal_isCancelledFailure');
/**

@@ -241,55 +195,24 @@ * This error is thrown when Cancellation has been requested. To allow Cancellation to happen, let it propagate. To

*/
@SymbolBasedInstanceOfError('CancelledFailure')
export class CancelledFailure extends TemporalFailure {
public readonly name: string = 'CancelledFailure';
constructor(message: string | undefined, public readonly details: unknown[] = [], cause?: Error) {
super(message, cause);
}
/**
* Marker to determine whether an error is an instance of CancelledFailure.
*/
protected readonly [isCancelledFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is CancelledFailure {
return error instanceof CancelledFailure || (error as any)?.[isCancelledFailure] === true;
}
}
const isTerminatedFailure = Symbol.for('__temporal_isTerminatedFailure');
/**
* Used as the `cause` when a Workflow has been terminated
*/
@SymbolBasedInstanceOfError('TerminatedFailure')
export class TerminatedFailure extends TemporalFailure {
public readonly name: string = 'TerminatedFailure';
constructor(message: string | undefined, cause?: Error) {
super(message, cause);
}
/**
* Marker to determine whether an error is an instance of TerminatedFailure.
*/
protected readonly [isTerminatedFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is TerminatedFailure {
return error instanceof TerminatedFailure || (error as any)?.[isTerminatedFailure] === true;
}
}
const isTimeoutFailure = Symbol.for('__temporal_isTimeoutFailure');
/**
* Used to represent timeouts of Activities and Workflows
*/
@SymbolBasedInstanceOfError('TimeoutFailure')
export class TimeoutFailure extends TemporalFailure {
public readonly name: string = 'TimeoutFailure';
constructor(

@@ -302,18 +225,4 @@ message: string | undefined,

}
/**
* Marker to determine whether an error is an instance of TimeoutFailure.
*/
protected readonly [isTimeoutFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is TimeoutFailure {
return error instanceof TimeoutFailure || (error as any)?.[isTimeoutFailure] === true;
}
}
const isActivityFailure = Symbol.for('__temporal_isActivityFailure');
/**

@@ -325,5 +234,4 @@ * Contains information about an Activity failure. Always contains the original reason for the failure as its `cause`.

*/
@SymbolBasedInstanceOfError('ActivityFailure')
export class ActivityFailure extends TemporalFailure {
public readonly name: string = 'ActivityFailure';
public constructor(

@@ -339,18 +247,4 @@ message: string | undefined,

}
/**
* Marker to determine whether an error is an instance of ActivityFailure.
*/
protected readonly [isActivityFailure] = true;
/**
* Instanceof check that works when multiple versions of @temporalio/common are installed.
*/
static is(error: unknown): error is ActivityFailure {
return error instanceof ActivityFailure || (error as any)?.[isActivityFailure] === true;
}
}
const isChildWorkflowFailure = Symbol.for('__temporal_isChildWorkflowFailure');
/**

@@ -362,5 +256,4 @@ * Contains information about a Child Workflow failure. Always contains the reason for the failure as its {@link cause}.

*/
@SymbolBasedInstanceOfError('ChildWorkflowFailure')
export class ChildWorkflowFailure extends TemporalFailure {
public readonly name: string = 'ChildWorkflowFailure';
public constructor(

@@ -375,14 +268,2 @@ public readonly namespace: string | undefined,

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

@@ -400,3 +281,3 @@

export function ensureApplicationFailure(error: unknown): ApplicationFailure {
if (ApplicationFailure.is(error)) {
if (error instanceof ApplicationFailure) {
return error;

@@ -420,3 +301,3 @@ }

export function ensureTemporalFailure(err: unknown): TemporalFailure {
if (TemporalFailure.is(err)) {
if (err instanceof TemporalFailure) {
return err;

@@ -434,12 +315,6 @@ }

export function rootCause(error: unknown): string | undefined {
if (TemporalFailure.is(error)) {
if (error instanceof TemporalFailure) {
return error.cause ? rootCause(error.cause) : error.message;
}
if (error instanceof Error) {
return error.message;
}
if (typeof error === 'string') {
return error;
}
return undefined;
return errorMessage(error);
}

@@ -24,3 +24,2 @@ /** Shorthand alias */

// ts-prune-ignore-next
export function hasOwnProperty<X extends Record<string, unknown>, Y extends PropertyKey>(

@@ -40,2 +39,15 @@ record: X,

export function isError(error: unknown): error is Error {
return (
isRecord(error) &&
typeof error.name === 'string' &&
typeof error.message === 'string' &&
(error.stack == null || typeof error.stack === 'string')
);
}
export function isAbortError(error: unknown): error is Error & { name: 'AbortError' } {
return isError(error) && error.name === 'AbortError';
}
/**

@@ -45,8 +57,7 @@ * Get `error.message` (or `undefined` if not present)

export function errorMessage(error: unknown): string | undefined {
if (typeof error === 'string') {
if (isError(error)) {
return error.message;
} else if (typeof error === 'string') {
return error;
}
if (error instanceof Error) {
return error.message;
}
return undefined;

@@ -58,2 +69,7 @@ }

}
function isErrorWithCode(error: unknown): error is ErrorWithCode {
return isRecord(error) && typeof error.code === 'string';
}
/**

@@ -63,8 +79,4 @@ * Get `error.code` (or `undefined` if not present)

export function errorCode(error: unknown): string | undefined {
if (
typeof error === 'object' &&
(error as ErrorWithCode).code !== undefined &&
typeof (error as ErrorWithCode).code === 'string'
) {
return (error as ErrorWithCode).code;
if (isErrorWithCode(error)) {
return error.code;
}

@@ -81,1 +93,56 @@

}
export type Class<E extends Error> = {
new (...args: any[]): E;
prototype: E;
};
/**
* A decorator to be used on error classes. It adds the 'name' property AND provides a custom
* 'instanceof' handler that works correctly across execution contexts.
*
* ### Details ###
*
* According to the EcmaScript's spec, the default behavior of JavaScript's `x instanceof Y` operator is to walk up the
* prototype chain of object 'x', checking if any constructor in that hierarchy is _exactly the same object_ as the
* constructor function 'Y'.
*
* Unfortunately, it happens in various situations that different constructor function objects get created for what
* appears to be the very same class. This leads to surprising behavior where `instanceof` returns false though it is
* known that the object is indeed an instance of that class. One particular case where this happens is when constructor
* 'Y' belongs to a different realm than the constuctor with which 'x' was instantiated. Another case is when two copies
* of the same library gets loaded in the same realm.
*
* In practice, this tends to cause issues when crossing the workflow-sandboxing boundary (since Node's vm module
* really creates new execution realms), as well as when running tests using Jest (see https://github.com/jestjs/jest/issues/2549
* for some details on that one).
*
* This function injects a custom 'instanceof' handler into the prototype of 'clazz', which is both cross-realm safe and
* cross-copies-of-the-same-lib safe. It works by adding a special symbol property to the prototype of 'clazz', and then
* checking for the presence of that symbol.
*/
export function SymbolBasedInstanceOfError<E extends Error>(markerName: string): (clazz: Class<E>) => void {
return (clazz: Class<E>): void => {
const marker = Symbol.for(`__temporal_is${markerName}`);
Object.defineProperty(clazz.prototype, 'name', { value: markerName, enumerable: true });
Object.defineProperty(clazz.prototype, marker, { value: true, enumerable: false });
Object.defineProperty(clazz, Symbol.hasInstance, {
// eslint-disable-next-line object-shorthand
value: function (this: any, error: object): boolean {
if (this === clazz) {
return isRecord(error) && (error as any)[marker] === true;
} else {
// 'this' must be a _subclass_ of clazz that doesn't redefined [Symbol.hasInstance], so that it inherited
// from clazz's [Symbol.hasInstance]. If we don't handle this particular situation, then
// `x instanceof SubclassOfParent` would return true for any instance of 'Parent', which is clearly wrong.
//
// Ideally, it'd be preferable to avoid this case entirely, by making sure that all subclasses of 'clazz'
// redefine [Symbol.hasInstance], but we can't enforce that. We therefore fallback to the default instanceof
// behavior (which is NOT cross-realm safe).
return this.prototype.isPrototypeOf(error); // eslint-disable-line no-prototype-builtins
}
},
});
};
}

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