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

@nats-io/nats-core

Package Overview
Dependencies
Maintainers
0
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nats-io/nats-core - npm Package Compare versions

Comparing version 3.0.0-30 to 3.0.0-31

lib/errors.d.ts

8

lib/authenticator.js

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

const encoders_1 = require("./encoders");
const core_1 = require("./core");
function multiAuthenticator(authenticators) {

@@ -116,3 +115,3 @@ return (nonce) => {

if (!m) {
throw core_1.NatsError.errorForCode(core_1.ErrorCode.BadCreds);
throw new Error("unable to parse credentials");
}

@@ -123,7 +122,4 @@ const jwt = m[1].trim();

if (!m) {
throw core_1.NatsError.errorForCode(core_1.ErrorCode.BadCreds);
throw new Error("unable to parse credentials");
}
if (!m) {
throw core_1.NatsError.errorForCode(core_1.ErrorCode.BadCreds);
}
const seed = encoders_1.TE.encode(m[1].trim());

@@ -130,0 +126,0 @@ return { jwt, seed };

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

const util_1 = require("./util");
const core_1 = require("./core");
class Metric {

@@ -107,3 +106,3 @@ name;

if (err) {
throw new core_1.NatsError(`bench closed with an error: ${err.message}`, core_1.ErrorCode.Unknown, err);
throw new Error(`bench closed with an error`, { cause: err });
}

@@ -110,0 +109,0 @@ });

@@ -27,90 +27,3 @@ /**

}
export declare enum ErrorCode {
ApiError = "BAD API",
BadAuthentication = "BAD_AUTHENTICATION",
BadCreds = "BAD_CREDS",
BadHeader = "BAD_HEADER",
BadJson = "BAD_JSON",
BadPayload = "BAD_PAYLOAD",
BadSubject = "BAD_SUBJECT",
Cancelled = "CANCELLED",
ConnectionClosed = "CONNECTION_CLOSED",
ConnectionDraining = "CONNECTION_DRAINING",
ConnectionRefused = "CONNECTION_REFUSED",
ConnectionTimeout = "CONNECTION_TIMEOUT",
Disconnect = "DISCONNECT",
InvalidOption = "INVALID_OPTION",
InvalidPayload = "INVALID_PAYLOAD",
MaxPayloadExceeded = "MAX_PAYLOAD_EXCEEDED",
NoResponders = "503",
NotFunction = "NOT_FUNC",
RequestError = "REQUEST_ERROR",
ServerOptionNotAvailable = "SERVER_OPT_NA",
SubClosed = "SUB_CLOSED",
SubDraining = "SUB_DRAINING",
Timeout = "TIMEOUT",
Tls = "TLS",
Unknown = "UNKNOWN_ERROR",
WssRequired = "WSS_REQUIRED",
JetStreamInvalidAck = "JESTREAM_INVALID_ACK",
JetStream404NoMessages = "404",
JetStream408RequestTimeout = "408",
JetStream409MaxAckPendingExceeded = "409",
JetStream409 = "409",
JetStreamNotEnabled = "503",
JetStreamIdleHeartBeat = "IDLE_HEARTBEAT",
AuthorizationViolation = "AUTHORIZATION_VIOLATION",
AuthenticationExpired = "AUTHENTICATION_EXPIRED",
ProtocolError = "NATS_PROTOCOL_ERR",
PermissionsViolation = "PERMISSIONS_VIOLATION",
AuthenticationTimeout = "AUTHENTICATION_TIMEOUT",
AccountExpired = "ACCOUNT_EXPIRED"
}
export declare function isNatsError(err: NatsError | Error): err is NatsError;
export interface ApiError {
/**
* HTTP like error code in the 300 to 500 range
*/
code: number;
/**
* A human friendly description of the error
*/
description: string;
/**
* The NATS error code unique to each kind of error
*/
err_code?: number;
}
export declare class Messages {
messages: Map<string, string>;
constructor();
static getMessage(s: string): string;
getMessage(s: string): string;
}
export declare class NatsError extends Error {
code: string;
permissionContext?: {
operation: string;
subject: string;
queue?: string;
};
chainedError?: Error;
api_error?: ApiError;
/**
* @param {String} message
* @param {String} code
* @param {Error} [chainedError]
*
* @api private
*/
constructor(message: string, code: string, chainedError?: Error);
static errorForCode(code: string, chainedError?: Error): NatsError;
isAuthError(): boolean;
isAuthTimeout(): boolean;
isPermissionError(): boolean;
isProtocolError(): boolean;
isJetStreamError(): boolean;
jsError(): ApiError | null;
}
export type MsgCallback<T> = (err: NatsError | null, msg: T) => void;
export type MsgCallback<T> = (err: Error | null, msg: T) => void;
/**

@@ -151,2 +64,3 @@ * Subscription Options

data: string | ServersChanged | number;
error?: Error;
permissionContext?: {

@@ -272,6 +186,2 @@ operation: string;

}
/**
* Type alias for NATS core subscriptions
*/
export type Subscription = Sub<Msg>;
export declare enum Match {

@@ -542,3 +452,3 @@ Exact = 0,

*/
export interface Sub<T> extends AsyncIterable<T> {
export interface Subscription extends AsyncIterable<Msg> {
/** A promise that resolves when the subscription closes */

@@ -571,3 +481,3 @@ closed: Promise<void>;

*/
callback(err: NatsError | null, msg: Msg): void;
callback: MsgCallback<Msg>;
/**

@@ -638,3 +548,3 @@ * Returns the subject that was used to create the subscription.

resolver(err: Error | null, msg: Msg): void;
cancel(err?: NatsError): void;
cancel(err?: Error): void;
}

@@ -883,10 +793,2 @@ /**

export type ConnectFn = (opts: ConnectionOptions) => Promise<NatsConnection>;
export interface Base {
subject: string;
callback: (error: NatsError | null, msg: Msg) => void;
received: number;
timeout?: number | null;
max?: number | undefined;
draining: boolean;
}
export interface URLParseFn {

@@ -893,0 +795,0 @@ (u: string, encrypted?: boolean): string;

@@ -17,7 +17,7 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_HOST = exports.DEFAULT_PORT = exports.RequestStrategy = exports.Match = exports.NatsError = exports.Messages = exports.ErrorCode = exports.DebugEvents = exports.Events = void 0;
exports.isNatsError = isNatsError;
exports.DEFAULT_HOST = exports.DEFAULT_PORT = exports.RequestStrategy = exports.Match = exports.DebugEvents = exports.Events = void 0;
exports.syncIterator = syncIterator;
exports.createInbox = createInbox;
const nuid_1 = require("./nuid");
const errors_1 = require("./errors");
/**

@@ -51,116 +51,2 @@ * Events reported by the {@link NatsConnection#status} iterator.

})(DebugEvents || (exports.DebugEvents = DebugEvents = {}));
var ErrorCode;
(function (ErrorCode) {
// emitted by the client
ErrorCode["ApiError"] = "BAD API";
ErrorCode["BadAuthentication"] = "BAD_AUTHENTICATION";
ErrorCode["BadCreds"] = "BAD_CREDS";
ErrorCode["BadHeader"] = "BAD_HEADER";
ErrorCode["BadJson"] = "BAD_JSON";
ErrorCode["BadPayload"] = "BAD_PAYLOAD";
ErrorCode["BadSubject"] = "BAD_SUBJECT";
ErrorCode["Cancelled"] = "CANCELLED";
ErrorCode["ConnectionClosed"] = "CONNECTION_CLOSED";
ErrorCode["ConnectionDraining"] = "CONNECTION_DRAINING";
ErrorCode["ConnectionRefused"] = "CONNECTION_REFUSED";
ErrorCode["ConnectionTimeout"] = "CONNECTION_TIMEOUT";
ErrorCode["Disconnect"] = "DISCONNECT";
ErrorCode["InvalidOption"] = "INVALID_OPTION";
ErrorCode["InvalidPayload"] = "INVALID_PAYLOAD";
ErrorCode["MaxPayloadExceeded"] = "MAX_PAYLOAD_EXCEEDED";
ErrorCode["NoResponders"] = "503";
ErrorCode["NotFunction"] = "NOT_FUNC";
ErrorCode["RequestError"] = "REQUEST_ERROR";
ErrorCode["ServerOptionNotAvailable"] = "SERVER_OPT_NA";
ErrorCode["SubClosed"] = "SUB_CLOSED";
ErrorCode["SubDraining"] = "SUB_DRAINING";
ErrorCode["Timeout"] = "TIMEOUT";
ErrorCode["Tls"] = "TLS";
ErrorCode["Unknown"] = "UNKNOWN_ERROR";
ErrorCode["WssRequired"] = "WSS_REQUIRED";
// jetstream
ErrorCode["JetStreamInvalidAck"] = "JESTREAM_INVALID_ACK";
ErrorCode["JetStream404NoMessages"] = "404";
ErrorCode["JetStream408RequestTimeout"] = "408";
//@deprecated: use JetStream409
ErrorCode["JetStream409MaxAckPendingExceeded"] = "409";
ErrorCode["JetStream409"] = "409";
ErrorCode["JetStreamNotEnabled"] = "503";
ErrorCode["JetStreamIdleHeartBeat"] = "IDLE_HEARTBEAT";
// emitted by the server
ErrorCode["AuthorizationViolation"] = "AUTHORIZATION_VIOLATION";
ErrorCode["AuthenticationExpired"] = "AUTHENTICATION_EXPIRED";
ErrorCode["ProtocolError"] = "NATS_PROTOCOL_ERR";
ErrorCode["PermissionsViolation"] = "PERMISSIONS_VIOLATION";
ErrorCode["AuthenticationTimeout"] = "AUTHENTICATION_TIMEOUT";
ErrorCode["AccountExpired"] = "ACCOUNT_EXPIRED";
})(ErrorCode || (exports.ErrorCode = ErrorCode = {}));
function isNatsError(err) {
return typeof err.code === "string";
}
class Messages {
messages;
constructor() {
this.messages = new Map();
this.messages.set(ErrorCode.InvalidPayload, "Invalid payload type - payloads can be 'binary', 'string', or 'json'");
this.messages.set(ErrorCode.BadJson, "Bad JSON");
this.messages.set(ErrorCode.WssRequired, "TLS is required, therefore a secure websocket connection is also required");
}
static getMessage(s) {
return messages.getMessage(s);
}
getMessage(s) {
return this.messages.get(s) || s;
}
}
exports.Messages = Messages;
// safari doesn't support static class members
const messages = new Messages();
class NatsError extends Error {
// TODO: on major version this should change to a number/enum
code;
permissionContext;
chainedError;
// these are for supporting jetstream
api_error;
/**
* @param {String} message
* @param {String} code
* @param {Error} [chainedError]
*
* @api private
*/
constructor(message, code, chainedError) {
super(message);
this.name = "NatsError";
this.message = message;
this.code = code;
this.chainedError = chainedError;
}
static errorForCode(code, chainedError) {
const m = Messages.getMessage(code);
return new NatsError(m, code, chainedError);
}
isAuthError() {
return this.code === ErrorCode.AuthenticationExpired ||
this.code === ErrorCode.AuthorizationViolation ||
this.code === ErrorCode.AccountExpired;
}
isAuthTimeout() {
return this.code === ErrorCode.AuthenticationTimeout;
}
isPermissionError() {
return this.code === ErrorCode.PermissionsViolation;
}
isProtocolError() {
return this.code === ErrorCode.ProtocolError;
}
isJetStreamError() {
return this.api_error !== undefined;
}
jsError() {
return this.api_error ? this.api_error : null;
}
}
exports.NatsError = NatsError;
var Match;

@@ -208,3 +94,3 @@ (function (Match) {

if (v === "*" || v === ">") {
throw new Error(`inbox prefixes cannot have wildcards '${prefix}'`);
throw errors_1.InvalidOptionError.illegalArgument("prefix", `cannot have wildcards ('${prefix}')`);
}

@@ -211,0 +97,0 @@ });

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

const core_1 = require("./core");
const errors_1 = require("./errors");
// https://www.ietf.org/rfc/rfc822.txt

@@ -51,3 +52,3 @@ // 3.1.2. STRUCTURE OF HEADER FIELDS

if (c === colon || c < start || c > end) {
throw new core_1.NatsError(`'${k[i]}' is not a valid character for a header key`, core_1.ErrorCode.BadHeader);
throw new errors_1.InvalidHeaderError(`'${k[i]}' is not a valid character in a header name`);
}

@@ -160,3 +161,3 @@ if (upper && a <= c && c <= z) {

if (inv.test(k)) {
throw new core_1.NatsError("invalid header value - \\r and \\n are not allowed.", core_1.ErrorCode.BadHeader);
throw new errors_1.InvalidHeaderError("values cannot contain \\r or \\n");
}

@@ -163,0 +164,0 @@ return k.trim();

@@ -31,4 +31,4 @@ export { NatsConnectionImpl } from "./nats";

export { extractProtocolMessage, protoLen } from "./transport";
export type { ApiError, Auth, Authenticator, CallbackFn, ConnectionOptions, Dispatcher, JwtAuth, Msg, MsgCallback, MsgHdrs, Nanos, NatsConnection, NKeyAuth, NoAuth, Payload, Publisher, PublishOptions, QueuedIterator, Request, RequestManyOptions, RequestOptions, ReviverFn, Server, ServerInfo, ServersChanged, Stats, Status, Sub, SubOpts, Subscription, SubscriptionOptions, SyncIterator, TlsOptions, TokenAuth, UserPass, } from "./core";
export { createInbox, DebugEvents, ErrorCode, Events, isNatsError, Match, NatsError, RequestStrategy, syncIterator, } from "./core";
export type { Auth, Authenticator, CallbackFn, ConnectionOptions, Dispatcher, JwtAuth, Msg, MsgCallback, MsgHdrs, Nanos, NatsConnection, NKeyAuth, NoAuth, Payload, Publisher, PublishOptions, QueuedIterator, Request, RequestManyOptions, RequestOptions, ReviverFn, Server, ServerInfo, ServersChanged, Stats, Status, SubOpts, Subscription, SubscriptionOptions, SyncIterator, TlsOptions, TokenAuth, UserPass, } from "./core";
export { createInbox, DebugEvents, Events, Match, RequestStrategy, syncIterator, } from "./core";
export { SubscriptionImpl, Subscriptions } from "./protocol";

@@ -41,1 +41,2 @@ export type { IdleHeartbeatFn, IdleHeartbeatOptions, } from "./idleheartbeat_monitor";

export { wsconnect, wsUrlParseFn } from "./ws_transport";
export { AuthorizationError, ClosedConnectionError, ConnectionDrainingError, ConnectionError, InvalidOptionError, NoRespondersError, PermissionViolationError, ProtocolError, RequestError, ServerError, TimeoutError, UserAuthenticationExpiredError, } from "./errors";

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

exports.TE = exports.TD = exports.Metric = exports.Bench = exports.writeAll = exports.readAll = exports.MAX_SIZE = exports.DenoBuffer = exports.State = exports.Parser = exports.Kind = exports.QueuedIteratorImpl = exports.usernamePasswordAuthenticator = exports.tokenAuthenticator = exports.nkeyAuthenticator = exports.jwtAuthenticator = exports.credsAuthenticator = exports.RequestOne = exports.parseOptions = exports.defaultOptions = exports.DEFAULT_MAX_RECONNECT_ATTEMPTS = exports.checkUnsupportedOption = exports.checkOptions = exports.buildAuthenticator = exports.DataBuffer = exports.MuxSubscription = exports.Heartbeat = exports.MsgHdrsImpl = exports.headers = exports.canonicalMIMEHeaderKey = exports.timeout = exports.SimpleMutex = exports.render = exports.nanos = exports.millis = exports.extend = exports.delay = exports.deferred = exports.deadline = exports.collect = exports.backoff = exports.ProtocolHandler = exports.INFO = exports.Connect = exports.setTransportFactory = exports.getResolveFn = exports.MsgImpl = exports.nuid = exports.Nuid = exports.NatsConnectionImpl = void 0;
exports.wsUrlParseFn = exports.wsconnect = exports.SHA256 = exports.Base64UrlPaddedCodec = exports.Base64UrlCodec = exports.Base64Codec = exports.Servers = exports.isIPV4OrHostname = exports.IdleHeartbeatMonitor = exports.Subscriptions = exports.SubscriptionImpl = exports.syncIterator = exports.RequestStrategy = exports.NatsError = exports.Match = exports.isNatsError = exports.Events = exports.ErrorCode = exports.DebugEvents = exports.createInbox = exports.protoLen = exports.extractProtocolMessage = exports.Empty = exports.parseSemVer = exports.Features = exports.Feature = exports.compare = exports.parseIP = exports.isIP = exports.ipV4 = void 0;
exports.UserAuthenticationExpiredError = exports.TimeoutError = exports.ServerError = exports.RequestError = exports.ProtocolError = exports.PermissionViolationError = exports.NoRespondersError = exports.InvalidOptionError = exports.ConnectionError = exports.ConnectionDrainingError = exports.ClosedConnectionError = exports.AuthorizationError = exports.wsUrlParseFn = exports.wsconnect = exports.SHA256 = exports.Base64UrlPaddedCodec = exports.Base64UrlCodec = exports.Base64Codec = exports.Servers = exports.isIPV4OrHostname = exports.IdleHeartbeatMonitor = exports.Subscriptions = exports.SubscriptionImpl = exports.syncIterator = exports.RequestStrategy = exports.Match = exports.Events = exports.DebugEvents = exports.createInbox = exports.protoLen = exports.extractProtocolMessage = exports.Empty = exports.parseSemVer = exports.Features = exports.Feature = exports.compare = exports.parseIP = exports.isIP = exports.ipV4 = void 0;
var nats_1 = require("./nats");

@@ -120,7 +120,4 @@ Object.defineProperty(exports, "NatsConnectionImpl", { enumerable: true, get: function () { return nats_1.NatsConnectionImpl; } });

Object.defineProperty(exports, "DebugEvents", { enumerable: true, get: function () { return core_1.DebugEvents; } });
Object.defineProperty(exports, "ErrorCode", { enumerable: true, get: function () { return core_1.ErrorCode; } });
Object.defineProperty(exports, "Events", { enumerable: true, get: function () { return core_1.Events; } });
Object.defineProperty(exports, "isNatsError", { enumerable: true, get: function () { return core_1.isNatsError; } });
Object.defineProperty(exports, "Match", { enumerable: true, get: function () { return core_1.Match; } });
Object.defineProperty(exports, "NatsError", { enumerable: true, get: function () { return core_1.NatsError; } });
Object.defineProperty(exports, "RequestStrategy", { enumerable: true, get: function () { return core_1.RequestStrategy; } });

@@ -145,2 +142,15 @@ Object.defineProperty(exports, "syncIterator", { enumerable: true, get: function () { return core_1.syncIterator; } });

Object.defineProperty(exports, "wsUrlParseFn", { enumerable: true, get: function () { return ws_transport_1.wsUrlParseFn; } });
var errors_1 = require("./errors");
Object.defineProperty(exports, "AuthorizationError", { enumerable: true, get: function () { return errors_1.AuthorizationError; } });
Object.defineProperty(exports, "ClosedConnectionError", { enumerable: true, get: function () { return errors_1.ClosedConnectionError; } });
Object.defineProperty(exports, "ConnectionDrainingError", { enumerable: true, get: function () { return errors_1.ConnectionDrainingError; } });
Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function () { return errors_1.ConnectionError; } });
Object.defineProperty(exports, "InvalidOptionError", { enumerable: true, get: function () { return errors_1.InvalidOptionError; } });
Object.defineProperty(exports, "NoRespondersError", { enumerable: true, get: function () { return errors_1.NoRespondersError; } });
Object.defineProperty(exports, "PermissionViolationError", { enumerable: true, get: function () { return errors_1.PermissionViolationError; } });
Object.defineProperty(exports, "ProtocolError", { enumerable: true, get: function () { return errors_1.ProtocolError; } });
Object.defineProperty(exports, "RequestError", { enumerable: true, get: function () { return errors_1.RequestError; } });
Object.defineProperty(exports, "ServerError", { enumerable: true, get: function () { return errors_1.ServerError; } });
Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return errors_1.TimeoutError; } });
Object.defineProperty(exports, "UserAuthenticationExpiredError", { enumerable: true, get: function () { return errors_1.UserAuthenticationExpiredError; } });
//# sourceMappingURL=internal_mod.js.map

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

export { backoff, Bench, buildAuthenticator, canonicalMIMEHeaderKey, createInbox, credsAuthenticator, deadline, DebugEvents, deferred, delay, Empty, ErrorCode, Events, headers, jwtAuthenticator, Match, Metric, millis, MsgHdrsImpl, nanos, NatsError, nkeyAuthenticator, nkeys, Nuid, nuid, RequestStrategy, syncIterator, tokenAuthenticator, usernamePasswordAuthenticator, wsconnect, } from "./internal_mod";
export type { ApiError, Auth, Authenticator, Backoff, BenchOpts, Codec, ConnectionOptions, Deferred, Delay, JwtAuth, Msg, MsgCallback, MsgHdrs, Nanos, NatsConnection, NKeyAuth, NoAuth, Payload, Perf, Publisher, PublishOptions, QueuedIterator, RequestManyOptions, RequestOptions, ReviverFn, ServerInfo, ServersChanged, Stats, Status, Sub, SubOpts, Subscription, SubscriptionOptions, SyncIterator, Timeout, TlsOptions, TokenAuth, UserPass, } from "./internal_mod";
export { AuthorizationError, backoff, Bench, buildAuthenticator, canonicalMIMEHeaderKey, ClosedConnectionError, ConnectionDrainingError, ConnectionError, createInbox, credsAuthenticator, deadline, DebugEvents, deferred, delay, Empty, Events, headers, InvalidOptionError, jwtAuthenticator, Match, Metric, millis, MsgHdrsImpl, nanos, nkeyAuthenticator, nkeys, NoRespondersError, Nuid, nuid, PermissionViolationError, ProtocolError, RequestError, RequestStrategy, ServerError, syncIterator, TimeoutError, tokenAuthenticator, UserAuthenticationExpiredError, usernamePasswordAuthenticator, wsconnect, } from "./internal_mod";
export type { Auth, Authenticator, Backoff, BenchOpts, Codec, ConnectionOptions, Deferred, Delay, JwtAuth, Msg, MsgCallback, MsgHdrs, Nanos, NatsConnection, NKeyAuth, NoAuth, Payload, Perf, Publisher, PublishOptions, QueuedIterator, RequestManyOptions, RequestOptions, ReviverFn, ServerInfo, ServersChanged, Stats, Status, SubOpts, Subscription, SubscriptionOptions, SyncIterator, Timeout, TlsOptions, TokenAuth, UserPass, } from "./internal_mod";

@@ -17,4 +17,5 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.wsconnect = exports.usernamePasswordAuthenticator = exports.tokenAuthenticator = exports.syncIterator = exports.RequestStrategy = exports.nuid = exports.Nuid = exports.nkeys = exports.nkeyAuthenticator = exports.NatsError = exports.nanos = exports.MsgHdrsImpl = exports.millis = exports.Metric = exports.Match = exports.jwtAuthenticator = exports.headers = exports.Events = exports.ErrorCode = exports.Empty = exports.delay = exports.deferred = exports.DebugEvents = exports.deadline = exports.credsAuthenticator = exports.createInbox = exports.canonicalMIMEHeaderKey = exports.buildAuthenticator = exports.Bench = exports.backoff = void 0;
exports.wsconnect = exports.usernamePasswordAuthenticator = exports.UserAuthenticationExpiredError = exports.tokenAuthenticator = exports.TimeoutError = exports.syncIterator = exports.ServerError = exports.RequestStrategy = exports.RequestError = exports.ProtocolError = exports.PermissionViolationError = exports.nuid = exports.Nuid = exports.NoRespondersError = exports.nkeys = exports.nkeyAuthenticator = exports.nanos = exports.MsgHdrsImpl = exports.millis = exports.Metric = exports.Match = exports.jwtAuthenticator = exports.InvalidOptionError = exports.headers = exports.Events = exports.Empty = exports.delay = exports.deferred = exports.DebugEvents = exports.deadline = exports.credsAuthenticator = exports.createInbox = exports.ConnectionError = exports.ConnectionDrainingError = exports.ClosedConnectionError = exports.canonicalMIMEHeaderKey = exports.buildAuthenticator = exports.Bench = exports.backoff = exports.AuthorizationError = void 0;
var internal_mod_1 = require("./internal_mod");
Object.defineProperty(exports, "AuthorizationError", { enumerable: true, get: function () { return internal_mod_1.AuthorizationError; } });
Object.defineProperty(exports, "backoff", { enumerable: true, get: function () { return internal_mod_1.backoff; } });

@@ -24,2 +25,5 @@ Object.defineProperty(exports, "Bench", { enumerable: true, get: function () { return internal_mod_1.Bench; } });

Object.defineProperty(exports, "canonicalMIMEHeaderKey", { enumerable: true, get: function () { return internal_mod_1.canonicalMIMEHeaderKey; } });
Object.defineProperty(exports, "ClosedConnectionError", { enumerable: true, get: function () { return internal_mod_1.ClosedConnectionError; } });
Object.defineProperty(exports, "ConnectionDrainingError", { enumerable: true, get: function () { return internal_mod_1.ConnectionDrainingError; } });
Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function () { return internal_mod_1.ConnectionError; } });
Object.defineProperty(exports, "createInbox", { enumerable: true, get: function () { return internal_mod_1.createInbox; } });

@@ -32,5 +36,5 @@ Object.defineProperty(exports, "credsAuthenticator", { enumerable: true, get: function () { return internal_mod_1.credsAuthenticator; } });

Object.defineProperty(exports, "Empty", { enumerable: true, get: function () { return internal_mod_1.Empty; } });
Object.defineProperty(exports, "ErrorCode", { enumerable: true, get: function () { return internal_mod_1.ErrorCode; } });
Object.defineProperty(exports, "Events", { enumerable: true, get: function () { return internal_mod_1.Events; } });
Object.defineProperty(exports, "headers", { enumerable: true, get: function () { return internal_mod_1.headers; } });
Object.defineProperty(exports, "InvalidOptionError", { enumerable: true, get: function () { return internal_mod_1.InvalidOptionError; } });
Object.defineProperty(exports, "jwtAuthenticator", { enumerable: true, get: function () { return internal_mod_1.jwtAuthenticator; } });

@@ -42,12 +46,18 @@ Object.defineProperty(exports, "Match", { enumerable: true, get: function () { return internal_mod_1.Match; } });

Object.defineProperty(exports, "nanos", { enumerable: true, get: function () { return internal_mod_1.nanos; } });
Object.defineProperty(exports, "NatsError", { enumerable: true, get: function () { return internal_mod_1.NatsError; } });
Object.defineProperty(exports, "nkeyAuthenticator", { enumerable: true, get: function () { return internal_mod_1.nkeyAuthenticator; } });
Object.defineProperty(exports, "nkeys", { enumerable: true, get: function () { return internal_mod_1.nkeys; } });
Object.defineProperty(exports, "NoRespondersError", { enumerable: true, get: function () { return internal_mod_1.NoRespondersError; } });
Object.defineProperty(exports, "Nuid", { enumerable: true, get: function () { return internal_mod_1.Nuid; } });
Object.defineProperty(exports, "nuid", { enumerable: true, get: function () { return internal_mod_1.nuid; } });
Object.defineProperty(exports, "PermissionViolationError", { enumerable: true, get: function () { return internal_mod_1.PermissionViolationError; } });
Object.defineProperty(exports, "ProtocolError", { enumerable: true, get: function () { return internal_mod_1.ProtocolError; } });
Object.defineProperty(exports, "RequestError", { enumerable: true, get: function () { return internal_mod_1.RequestError; } });
Object.defineProperty(exports, "RequestStrategy", { enumerable: true, get: function () { return internal_mod_1.RequestStrategy; } });
Object.defineProperty(exports, "ServerError", { enumerable: true, get: function () { return internal_mod_1.ServerError; } });
Object.defineProperty(exports, "syncIterator", { enumerable: true, get: function () { return internal_mod_1.syncIterator; } });
Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return internal_mod_1.TimeoutError; } });
Object.defineProperty(exports, "tokenAuthenticator", { enumerable: true, get: function () { return internal_mod_1.tokenAuthenticator; } });
Object.defineProperty(exports, "UserAuthenticationExpiredError", { enumerable: true, get: function () { return internal_mod_1.UserAuthenticationExpiredError; } });
Object.defineProperty(exports, "usernamePasswordAuthenticator", { enumerable: true, get: function () { return internal_mod_1.usernamePasswordAuthenticator; } });
Object.defineProperty(exports, "wsconnect", { enumerable: true, get: function () { return internal_mod_1.wsconnect; } });
//# sourceMappingURL=mod.js.map
import type { MsgArg } from "./parser";
import type { Msg, MsgHdrs, Payload, Publisher, RequestInfo, ReviverFn } from "./core";
import { NatsError } from "./core";
export declare function isRequestError(msg: Msg): NatsError | null;
export declare class MsgImpl implements Msg {

@@ -6,0 +4,0 @@ _headers?: MsgHdrs;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MsgImpl = void 0;
exports.isRequestError = isRequestError;
/*

@@ -21,12 +20,2 @@ * Copyright 2020-2024 The NATS Authors

const encoders_1 = require("./encoders");
const core_1 = require("./core");
function isRequestError(msg) {
// NATS core only considers errors 503s on messages that have no payload
// everything else simply forwarded as part of the message and is considered
// application level information
if (msg && msg.data.length === 0 && msg.headers?.code === 503) {
return core_1.NatsError.errorForCode(core_1.ErrorCode.NoResponders);
}
return null;
}
class MsgImpl {

@@ -33,0 +22,0 @@ _headers;

import type { Msg, MsgCallback, Request } from "./core";
import { NatsError } from "./core";
import type { PermissionViolationError } from "./errors";
export declare class MuxSubscription {

@@ -14,5 +14,5 @@ baseInbox: string;

all(): Request[];
handleError(isMuxPermissionError: boolean, err?: NatsError): boolean;
handleError(isMuxPermissionError: boolean, err: PermissionViolationError): boolean;
dispatcher(): MsgCallback<Msg>;
close(): void;
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MuxSubscription = void 0;
/*
* Copyright 2020-2021 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const msg_1 = require("./msg");
const core_1 = require("./core");
const errors_1 = require("./errors");
class MuxSubscription {

@@ -56,20 +42,17 @@ baseInbox;

handleError(isMuxPermissionError, err) {
if (err && err.permissionContext) {
if (isMuxPermissionError) {
// one or more requests queued but mux cannot process them
this.all().forEach((r) => {
r.resolver(err, {});
});
if (isMuxPermissionError) {
// one or more requests queued but mux cannot process them
this.all().forEach((r) => {
r.resolver(err, {});
});
return true;
}
if (err.operation === "publish") {
const req = this.all().find((s) => {
return s.requestSubject === err.subject;
});
if (req) {
req.resolver(err, {});
return true;
}
const ctx = err.permissionContext;
if (ctx.operation === "publish") {
const req = this.all().find((s) => {
return s.requestSubject === ctx.subject;
});
if (req) {
req.resolver(err, {});
return true;
}
}
}

@@ -84,4 +67,6 @@ return false;

if (r) {
if (err === null && m.headers) {
err = (0, msg_1.isRequestError)(m);
if (err === null) {
err = (m?.data?.length === 0 && m.headers?.code === 503)
? new errors_1.NoRespondersError(r.requestSubject)
: null;
}

@@ -94,3 +79,3 @@ r.resolver(err, m);

close() {
const err = core_1.NatsError.errorForCode(core_1.ErrorCode.Timeout);
const err = new errors_1.RequestError("connection closed");
this.reqs.forEach((req) => {

@@ -97,0 +82,0 @@ req.resolver(err, {});

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

const encoders_1 = require("./encoders");
const types_1 = require("./types");
const semver_1 = require("./semver");

@@ -27,4 +26,4 @@ const options_1 = require("./options");

const request_1 = require("./request");
const msg_1 = require("./msg");
const core_1 = require("./core");
const errors_1 = require("./errors");
class NatsConnectionImpl {

@@ -68,13 +67,13 @@ options;

if (this.isClosed()) {
throw types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionClosed);
throw new errors_1.ClosedConnectionError();
}
if (sub && this.isDraining()) {
throw types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionDraining);
throw new errors_1.ConnectionDrainingError();
}
if (pub && this.protocol.noMorePublishing) {
throw types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionDraining);
throw new errors_1.ConnectionDrainingError();
}
subject = subject || "";
if (subject.length === 0) {
throw types_1.NatsError.errorForCode(core_1.ErrorCode.BadSubject);
throw new errors_1.InvalidSubjectError(subject);
}

@@ -145,3 +144,3 @@ }

if (opts.maxWait < 1) {
return Promise.reject(new types_1.NatsError("timeout", core_1.ErrorCode.InvalidOption));
return Promise.reject(errors_1.InvalidOptionError.illegalOption("timeout", "should be greater than 0"));
}

@@ -175,4 +174,4 @@ // the iterator for user results

if (msg?.data?.length === 0 &&
msg?.headers?.status === core_1.ErrorCode.NoResponders) {
err = types_1.NatsError.errorForCode(core_1.ErrorCode.NoResponders);
msg?.headers?.status === "503") {
err = new errors_1.NoRespondersError(subject);
}

@@ -290,6 +289,6 @@ // augment any error with the current stack to provide context

if (opts.timeout < 1) {
return Promise.reject(new types_1.NatsError("timeout", core_1.ErrorCode.InvalidOption));
return Promise.reject(errors_1.InvalidOptionError.illegalOption("timeout", `must be greater than 0`));
}
if (!opts.noMux && opts.reply) {
return Promise.reject(new types_1.NatsError("reply can only be used with noMux", core_1.ErrorCode.InvalidOption));
return Promise.reject(errors_1.InvalidOptionError.exclusiveOptions(["reply", "noMux"]));
}

@@ -301,3 +300,3 @@ if (opts.noMux) {

const d = (0, util_1.deferred)();
const errCtx = asyncTraces ? new Error() : null;
const errCtx = asyncTraces ? new errors_1.RequestError("") : null;
const sub = this.subscribe(inbox, {

@@ -307,22 +306,21 @@ max: 1,

callback: (err, msg) => {
// check for no responders
if (msg && msg.data?.length === 0 && msg.headers?.code === 503) {
err = new errors_1.NoRespondersError(subject);
}
if (err) {
// timeouts from `timeout()` will have the proper stack
if (errCtx && err.code !== core_1.ErrorCode.Timeout) {
err.stack += `\n\n${errCtx.stack}`;
// if we have a context, use that as the wrapper
if (errCtx) {
errCtx.message = err.message;
errCtx.cause = err;
err = errCtx;
}
else {
err = new errors_1.RequestError(err.message, { cause: err });
}
d.reject(err);
sub.unsubscribe();
d.reject(err);
}
else {
err = (0, msg_1.isRequestError)(msg);
if (err) {
// if we failed here, help the developer by showing what failed
if (errCtx) {
err.stack += `\n\n${errCtx.stack}`;
}
d.reject(err);
}
else {
d.resolve(msg);
}
d.resolve(msg);
}

@@ -363,3 +361,3 @@ },

if (this.isClosed()) {
return Promise.reject(types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionClosed));
return Promise.reject(new errors_1.ClosedConnectionError());
}

@@ -370,6 +368,6 @@ return this.protocol.flush();

if (this.isClosed()) {
return Promise.reject(types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionClosed));
return Promise.reject(new errors_1.ClosedConnectionError());
}
if (this.isDraining()) {
return Promise.reject(types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionDraining));
return Promise.reject(new errors_1.ConnectionDrainingError());
}

@@ -423,5 +421,8 @@ this.draining = true;

async rtt() {
if (!this.protocol._closed && !this.protocol.connected) {
throw types_1.NatsError.errorForCode(core_1.ErrorCode.Disconnect);
if (this.isClosed()) {
throw new errors_1.ClosedConnectionError();
}
if (!this.protocol.connected) {
throw new errors_1.RequestError("connection disconnected");
}
const start = Date.now();

@@ -436,6 +437,6 @@ await this.flush();

if (this.isClosed()) {
return Promise.reject(types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionClosed));
return Promise.reject(new errors_1.ClosedConnectionError());
}
if (this.isDraining()) {
return Promise.reject(types_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionDraining));
return Promise.reject(new errors_1.ConnectionDrainingError());
}

@@ -442,0 +443,0 @@ return this.protocol.reconnect();

@@ -12,2 +12,2 @@ import type { Authenticator, ConnectionOptions, ServerInfo } from "./core";

export declare function checkOptions(info: ServerInfo, options: ConnectionOptions): void;
export declare function checkUnsupportedOption(prop: string, v?: string): void;
export declare function checkUnsupportedOption(prop: string, v?: unknown): void;

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

const authenticator_1 = require("./authenticator");
const errors_1 = require("./errors");
exports.DEFAULT_MAX_RECONNECT_ATTEMPTS = 10;

@@ -80,3 +81,3 @@ exports.DEFAULT_JITTER = 100;

if (opts.servers.length > 0 && opts.port) {
throw new core_1.NatsError("port and servers options are mutually exclusive", core_1.ErrorCode.InvalidOption);
throw errors_1.InvalidOptionError.exclusiveOptions(["servers", "port"]);
}

@@ -93,3 +94,3 @@ if (opts.servers.length === 0 && opts.port) {

if (options[n] && typeof options[n] !== "function") {
throw new core_1.NatsError(`${n} option should be a function`, core_1.ErrorCode.NotFunction);
throw errors_1.InvalidOptionError.illegalOption(n, "must be a function");
}

@@ -110,8 +111,3 @@ });

if (options.inboxPrefix) {
try {
(0, core_1.createInbox)(options.inboxPrefix);
}
catch (err) {
throw new core_1.NatsError(err.message, core_1.ErrorCode.ApiError);
}
(0, core_1.createInbox)(options.inboxPrefix);
}

@@ -125,3 +121,3 @@ // if not set - we set it

if (typeof (0, transport_1.getResolveFn)() !== "function") {
throw new core_1.NatsError(`'resolve' is not supported on this client`, core_1.ErrorCode.InvalidOption);
throw errors_1.InvalidOptionError.illegalOption("resolve", "not supported by this client implementation");
}

@@ -134,7 +130,7 @@ }

if ((proto === undefined || proto < 1) && options.noEcho) {
throw new core_1.NatsError("noEcho", core_1.ErrorCode.ServerOptionNotAvailable);
throw new errors_1.ConnectionError(`option 'noEcho' is not available`);
}
const tls = tlsRequired || tlsAvailable || false;
if (options.tls && !tls) {
throw new core_1.NatsError("tls", core_1.ErrorCode.ServerOptionNotAvailable);
throw new errors_1.ConnectionError(`option 'tls' is not available`);
}

@@ -144,5 +140,5 @@ }

if (v) {
throw new core_1.NatsError(prop, core_1.ErrorCode.InvalidOption);
throw errors_1.InvalidOptionError.illegalOption(prop, "is not supported");
}
}
//# sourceMappingURL=options.js.map
import type { Transport } from "./transport";
import type { Deferred, Timeout } from "./util";
import { DataBuffer } from "./databuffer";
import type { ServerImpl } from "./servers";
import { Servers } from "./servers";
import type { ServerImpl } from "./servers";
import { QueuedIteratorImpl } from "./queued_iterator";

@@ -12,4 +12,4 @@ import { MuxSubscription } from "./muxsubscription";

import { Features } from "./semver";
import { NatsError } from "./core";
import type { Base, ConnectionOptions, Dispatcher, Msg, Payload, Publisher, PublishOptions, Request, Server, ServerInfo, Status, Subscription, SubscriptionOptions } from "./core";
import type { ConnectionOptions, Dispatcher, Msg, Payload, Publisher, PublishOptions, Request, Server, ServerInfo, Status, Subscription, SubscriptionOptions } from "./core";
import { AuthorizationError, PermissionViolationError, UserAuthenticationExpiredError } from "./errors";
export declare const INFO: RegExp;

@@ -38,3 +38,3 @@ export declare class Connect {

}
export declare class SubscriptionImpl extends QueuedIteratorImpl<Msg> implements Base, Subscription {
export declare class SubscriptionImpl extends QueuedIteratorImpl<Msg> implements Subscription {
sid: number;

@@ -53,3 +53,3 @@ queue?: string;

constructor(protocol: ProtocolHandler, subject: string, opts?: SubscriptionOptions);
callback(err: NatsError | null, msg: Msg): void;
callback(err: Error | null, msg: Msg): void;
close(): void;

@@ -78,3 +78,3 @@ unsubscribe(max?: number): void;

cancel(s: SubscriptionImpl): void;
handleError(err?: NatsError): boolean;
handleError(err: PermissionViolationError): boolean;
close(): void;

@@ -106,3 +106,3 @@ }

pendingLimit: number;
lastError?: NatsError;
lastError?: Error;
abortReconnect: boolean;

@@ -127,7 +127,7 @@ whyClosed: string;

static connect(options: ConnectionOptions, publisher: Publisher): Promise<ProtocolHandler>;
static toError(s: string): NatsError;
static toError(s: string): Error;
processMsg(msg: MsgArg, data: Uint8Array): void;
processError(m: Uint8Array): void;
handleError(err: NatsError): void;
handleAuthError(err: NatsError): void;
handleError(err: Error): void;
handleAuthError(err: UserAuthenticationExpiredError | AuthorizationError): void;
processPing(): void;

@@ -134,0 +134,0 @@ processPong(): void;

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

const options_1 = require("./options");
const errors_1 = require("./errors");
const FLUSH_THRESHOLD = 1024 * 32;

@@ -153,6 +154,6 @@ exports.INFO = /^INFO\s+([^\r\n]+)\r\n/i;

if (this.protocol.isClosed()) {
return Promise.reject(core_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionClosed));
return Promise.reject(new errors_1.ClosedConnectionError());
}
if (this.isClosed()) {
return Promise.reject(core_1.NatsError.errorForCode(core_1.ErrorCode.SubClosed));
return Promise.reject(new errors_1.InvalidOperationError("subscription is already closed"));
}

@@ -234,24 +235,21 @@ if (!this.drained) {

handleError(err) {
if (err && err.permissionContext) {
const ctx = err.permissionContext;
const subs = this.all();
let sub;
if (ctx.operation === "subscription") {
sub = subs.find((s) => {
return s.subject === ctx.subject && s.queue === ctx.queue;
});
}
else if (ctx.operation === "publish") {
// we have a no mux subscription
sub = subs.find((s) => {
return s.requestSubject === ctx.subject;
});
}
if (sub) {
sub.callback(err, {});
sub.close();
this.subs.delete(sub.sid);
return sub !== this.mux;
}
const subs = this.all();
let sub;
if (err.operation === "subscription") {
sub = subs.find((s) => {
return s.subject === err.subject && s.queue === err.queue;
});
}
else if (err.operation === "publish") {
// we have a no mux subscription
sub = subs.find((s) => {
return s.requestSubject === err.subject;
});
}
if (sub) {
sub.callback(err, {});
sub.close();
this.subs.delete(sub.sid);
return sub !== this.mux;
}
return false;

@@ -337,3 +335,3 @@ }

// because that confuses API consumers
const err = core_1.NatsError.errorForCode(core_1.ErrorCode.Disconnect);
const err = new errors_1.RequestError("connection disconnected");
err.stack = "";

@@ -414,3 +412,3 @@ pongs.forEach((p) => {

// authenticator that dynamically updates
if (this.lastError?.code === core_1.ErrorCode.AuthenticationExpired) {
if (this.lastError instanceof errors_1.UserAuthenticationExpiredError) {
this.lastError = undefined;

@@ -529,3 +527,3 @@ }

else {
throw core_1.NatsError.errorForCode(core_1.ErrorCode.ConnectionRefused);
throw new errors_1.ConnectionError("connection refused");
}

@@ -567,39 +565,15 @@ }

static toError(s) {
const t = s ? s.toLowerCase() : "";
if (t.indexOf("permissions violation") !== -1) {
const err = new core_1.NatsError(s, core_1.ErrorCode.PermissionsViolation);
const m = s.match(/(Publish|Subscription) to "(\S+)"/);
if (m) {
const operation = m[1].toLowerCase();
const subject = m[2];
let queue = undefined;
if (operation === "subscription") {
const qm = s.match(/using queue "(\S+)"/);
if (qm) {
queue = qm[1];
}
}
err.permissionContext = {
operation,
subject,
queue,
};
}
let err = errors_1.PermissionViolationError.parse(s);
if (err) {
return err;
}
else if (t.indexOf("authorization violation") !== -1) {
return new core_1.NatsError(s, core_1.ErrorCode.AuthorizationViolation);
err = errors_1.UserAuthenticationExpiredError.parse(s);
if (err) {
return err;
}
else if (t.indexOf("user authentication expired") !== -1) {
return new core_1.NatsError(s, core_1.ErrorCode.AuthenticationExpired);
err = errors_1.AuthorizationError.parse(s);
if (err) {
return err;
}
else if (t.indexOf("account authentication expired") != -1) {
return new core_1.NatsError(s, core_1.ErrorCode.AccountExpired);
}
else if (t.indexOf("authentication timeout") !== -1) {
return new core_1.NatsError(s, core_1.ErrorCode.AuthenticationTimeout);
}
else {
return new core_1.NatsError(s, core_1.ErrorCode.ProtocolError);
}
return new errors_1.ProtocolError(s);
}

@@ -625,39 +599,36 @@ processMsg(msg, data) {

processError(m) {
const s = (0, encoders_1.decode)(m);
let s = (0, encoders_1.decode)(m);
if (s.startsWith("'") && s.endsWith("'")) {
s = s.slice(1, s.length - 1);
}
const err = ProtocolHandler.toError(s);
const status = { type: core_1.Events.Error, data: err.code };
if (err.isPermissionError()) {
let isMuxPermissionError = false;
if (err.permissionContext) {
status.permissionContext = err.permissionContext;
switch (err.constructor) {
case errors_1.PermissionViolationError: {
const pe = err;
const mux = this.subscriptions.getMux();
isMuxPermissionError = mux?.subject === err.permissionContext.subject;
const isMuxPermission = mux ? pe.subject === mux.subject : false;
this.subscriptions.handleError(pe);
this.muxSubscriptions.handleError(isMuxPermission, pe);
if (isMuxPermission) {
// remove the permission - enable it to be recreated
this.subscriptions.setMux(null);
}
break;
}
this.subscriptions.handleError(err);
this.muxSubscriptions.handleError(isMuxPermissionError, err);
if (isMuxPermissionError) {
// remove the permission - enable it to be recreated
this.subscriptions.setMux(null);
}
}
this.dispatchStatus(status);
this.dispatchStatus({ type: core_1.Events.Error, error: err, data: err.message });
this.handleError(err);
}
handleError(err) {
if (err.isAuthError()) {
if (err instanceof errors_1.UserAuthenticationExpiredError ||
err instanceof errors_1.AuthorizationError) {
this.handleAuthError(err);
}
else if (err.isProtocolError()) {
if (!(err instanceof errors_1.PermissionViolationError)) {
this.lastError = err;
}
else if (err.isAuthTimeout()) {
this.lastError = err;
}
// fallthrough here
if (!err.isPermissionError()) {
this.lastError = err;
}
}
handleAuthError(err) {
if ((this.lastError && err.code === this.lastError.code) &&
if ((this.lastError instanceof errors_1.UserAuthenticationExpiredError ||
this.lastError instanceof errors_1.AuthorizationError) &&
this.options.ignoreAuthErrorAbort === false) {

@@ -774,3 +745,3 @@ this.abortReconnect = true;

else {
throw core_1.NatsError.errorForCode(core_1.ErrorCode.BadPayload);
throw errors_1.InvalidOptionError.illegalArgument("payload", "supported payloads types are strings or Uint8Array");
}

@@ -784,3 +755,3 @@ let len = data.length;

if (this.info && !this.info.headers) {
throw new core_1.NatsError("headers", core_1.ErrorCode.ServerOptionNotAvailable);
throw errors_1.InvalidOptionError.illegalOption("headers", "are not supported by the current server");
}

@@ -793,3 +764,3 @@ const hdrs = options.headers;

if (this.info && len > this.info.max_payload) {
throw core_1.NatsError.errorForCode(core_1.ErrorCode.MaxPayloadExceeded);
throw new errors_1.ServerError(`server 'max_payload' exceeded`);
}

@@ -921,3 +892,3 @@ this.outBytes += len;

}
drain() {
async drain() {
const subs = this.subscriptions.all();

@@ -928,11 +899,13 @@ const promises = [];

});
return Promise.all(promises)
.then(async () => {
try {
await Promise.allSettled(promises);
}
catch {
// nothing we can do here
}
finally {
this.noMorePublishing = true;
await this.flush();
return this.close();
})
.catch(() => {
// cannot happen
});
}
return this.close();
}

@@ -939,0 +912,0 @@ flushPending() {

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

const util_1 = require("./util");
const core_1 = require("./core");
const errors_1 = require("./errors");
class QueuedIteratorImpl {

@@ -69,6 +69,6 @@ inflight;

if (this.noIterator) {
throw new core_1.NatsError("unsupported iterator", core_1.ErrorCode.ApiError);
throw new errors_1.InvalidOperationError("iterator cannot be used when a callback is registered");
}
if (this.yielding) {
throw new core_1.NatsError("already yielding", core_1.ErrorCode.ApiError);
throw new errors_1.InvalidOperationError("iterator is already yielding");
}

@@ -75,0 +75,0 @@ this.yielding = true;

import type { Deferred, Timeout } from "./util";
import type { MuxSubscription } from "./muxsubscription";
import type { Msg, Request, RequestManyOptions, RequestOptions } from "./core";
import { NatsError } from "./core";
import { RequestError } from "./errors";
export declare class BaseRequest {
token: string;
received: number;
ctx?: Error;
ctx?: RequestError;
requestSubject: string;

@@ -29,3 +29,3 @@ mux: MuxSubscription;

constructor(mux: MuxSubscription, requestSubject: string, opts?: Partial<RequestManyOptions>);
cancel(err?: NatsError): void;
cancel(err?: Error): void;
resolver(err: Error | null, msg: Msg): void;

@@ -38,3 +38,3 @@ }

resolver(err: Error | null, msg: Msg): void;
cancel(err?: NatsError): void;
cancel(err?: Error): void;
}

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

const core_1 = require("./core");
const errors_1 = require("./errors");
class BaseRequest {

@@ -20,3 +21,3 @@ token;

if (asyncTraces) {
this.ctx = new Error();
this.ctx = new errors_1.RequestError();
}

@@ -111,4 +112,9 @@ }

if (this.ctx) {
err.stack += `\n\n${this.ctx.stack}`;
this.ctx.message = err.message;
this.ctx.cause = err;
err = this.ctx;
}
else {
err = new errors_1.RequestError(err.message, { cause: err });
}
this.deferred.reject(err);

@@ -126,3 +132,3 @@ }

this.mux.cancel(this);
this.deferred.reject(err ? err : core_1.NatsError.errorForCode(core_1.ErrorCode.Cancelled));
this.deferred.reject(err ? err : new errors_1.RequestError("cancelled"));
}

@@ -129,0 +135,0 @@ }

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

export type { ApiError, Dispatcher, MsgHdrs, QueuedIterator } from "./core";
export { NatsError } from "./core";
export type { Dispatcher, MsgHdrs, QueuedIterator } from "./core";
export { Empty } from "./encoders";
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Empty = exports.NatsError = void 0;
var core_1 = require("./core");
Object.defineProperty(exports, "NatsError", { enumerable: true, get: function () { return core_1.NatsError; } });
exports.Empty = void 0;
var encoders_1 = require("./encoders");
Object.defineProperty(exports, "Empty", { enumerable: true, get: function () { return encoders_1.Empty; } });
//# sourceMappingURL=types.js.map

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

const encoders_1 = require("./encoders");
const core_1 = require("./core");
const errors_1 = require("./errors");
function extend(a, ...b) {

@@ -53,3 +53,3 @@ for (let i = 0; i < b.length; i++) {

// by generating the stack here to help identify what timed out
const err = asyncTraces ? core_1.NatsError.errorForCode(core_1.ErrorCode.Timeout) : null;
const err = asyncTraces ? new errors_1.TimeoutError() : null;
let methods;

@@ -67,3 +67,3 @@ let timer;

if (err === null) {
reject(core_1.NatsError.errorForCode(core_1.ErrorCode.Timeout));
reject(new errors_1.TimeoutError());
}

@@ -70,0 +70,0 @@ else {

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

export declare const version = "3.0.0-30";
export declare const version = "3.0.0-31";

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

// This file is generated - do not edit
exports.version = "3.0.0-30";
exports.version = "3.0.0-31";
//# sourceMappingURL=version.js.map

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

import type { ConnectionOptions, Deferred, NatsConnection, Server, Transport } from "./internal_mod";
import type { ConnectionOptions, NatsConnection, Server } from "./core";
import type { Deferred } from "./util";
import type { Transport } from "./transport";
export type WsSocketFactory = (u: string, opts: ConnectionOptions) => Promise<{

@@ -3,0 +5,0 @@ socket: WebSocket;

@@ -20,4 +20,10 @@ "use strict";

exports.wsconnect = wsconnect;
const internal_mod_1 = require("./internal_mod");
const util_1 = require("./util");
const transport_1 = require("./transport");
const options_1 = require("./options");
const databuffer_1 = require("./databuffer");
const protocol_1 = require("./protocol");
const nats_1 = require("./nats");
const version_1 = require("./version");
const errors_1 = require("./errors");
const VERSION = version_1.version;

@@ -49,8 +55,8 @@ const LANG = "nats.ws";

this.yields = [];
this.signal = (0, internal_mod_1.deferred)();
this.closedNotification = (0, internal_mod_1.deferred)();
this.signal = (0, util_1.deferred)();
this.closedNotification = (0, util_1.deferred)();
}
async connect(server, options) {
const connected = false;
const ok = (0, internal_mod_1.deferred)();
const ok = (0, util_1.deferred)();
this.options = options;

@@ -83,9 +89,9 @@ const u = server.src;

}
const t = internal_mod_1.DataBuffer.concat(...this.yields);
const pm = (0, internal_mod_1.extractProtocolMessage)(t);
const t = databuffer_1.DataBuffer.concat(...this.yields);
const pm = (0, transport_1.extractProtocolMessage)(t);
if (pm !== "") {
const m = internal_mod_1.INFO.exec(pm);
const m = protocol_1.INFO.exec(pm);
if (!m) {
if (options.debug) {
console.error("!!!", (0, internal_mod_1.render)(t));
console.error("!!!", (0, util_1.render)(t));
}

@@ -97,3 +103,3 @@ ok.reject(new Error("unexpected response from server"));

const info = JSON.parse(m[1]);
(0, internal_mod_1.checkOptions)(info, this.options);
(0, options_1.checkOptions)(info, this.options);
this.peeked = true;

@@ -130,3 +136,3 @@ this.connected = true;

const evt = e;
const err = new internal_mod_1.NatsError(evt.message, internal_mod_1.ErrorCode.Unknown, new Error(evt.error));
const err = new errors_1.ConnectionError(evt.message);
if (!connected) {

@@ -157,3 +163,3 @@ ok.reject(err);

while (!this.socketClosed && this.socket.bufferedAmount > 0) {
await (0, internal_mod_1.delay)(100);
await (0, util_1.delay)(100);
}

@@ -188,3 +194,3 @@ }

if (this.options.debug) {
console.info(`> ${(0, internal_mod_1.render)(yields[i])}`);
console.info(`> ${(0, util_1.render)(yields[i])}`);
}

@@ -202,3 +208,3 @@ yield yields[i];

this.yields = yields;
this.signal = (0, internal_mod_1.deferred)();
this.signal = (0, util_1.deferred)();
}

@@ -217,3 +223,3 @@ }

if (this.options.debug) {
console.info(`< ${(0, internal_mod_1.render)(frame)}`);
console.info(`< ${(0, util_1.render)(frame)}`);
}

@@ -227,3 +233,3 @@ return;

if (this.options.debug) {
console.error(`!!! ${(0, internal_mod_1.render)(frame)}: ${err}`);
console.error(`!!! ${(0, util_1.render)(frame)}: ${err}`);
}

@@ -298,3 +304,3 @@ }

function wsconnect(opts = {}) {
(0, internal_mod_1.setTransportFactory)({
(0, transport_1.setTransportFactory)({
defaultPort: 443,

@@ -304,3 +310,3 @@ urlParseFn: wsUrlParseFn,

if (opts.tls) {
throw new internal_mod_1.NatsError("tls", internal_mod_1.ErrorCode.InvalidOption);
throw errors_1.InvalidOptionError.illegalOption("tls", "is not configurable on w3c websocket connections");
}

@@ -310,4 +316,4 @@ return new WsTransport();

});
return internal_mod_1.NatsConnectionImpl.connect(opts);
return nats_1.NatsConnectionImpl.connect(opts);
}
//# sourceMappingURL=ws_transport.js.map
{
"name": "@nats-io/nats-core",
"version": "3.0.0-30",
"version": "3.0.0-31",
"files": [

@@ -5,0 +5,0 @@ "lib/",

@@ -704,3 +704,3 @@ # Core

})().catch((err) => {
if (err.code === ErrorCode.Timeout) {
if (err instanceof TimeoutError) {
console.log(`sub timed out!`);

@@ -707,0 +707,0 @@ } else {

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

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

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