wampy
Version:
Amazingly fast, feature-rich, lightweight WAMP Javascript client (for browser and node.js)
499 lines (493 loc) • 20.9 kB
TypeScript
import { S as Serializer } from './serializer-BBXXJ2B8.js';
export { e as Errors } from './errors-C_o2yEYd.js';
/**
* Core type definitions for Wampy.js
*
* Contains all interfaces, types, and enums used by the Wampy class
* and its internal structures.
*/
/** Status of the last Wampy operation */
interface WampyOpStatus {
/** 0 if operation was successful, > 0 if error occurred */
code: number;
/** Error instance containing details, or null on success */
error: Error | null;
/** Request ID of the last successfully sent operation */
reqId: number;
}
/** Data received in a subscription event callback */
interface EventData {
details: Record<string, unknown>;
argsList?: unknown[];
argsDict?: Record<string, unknown>;
}
/** Data received in a call result callback */
interface CallResult {
details: Record<string, unknown>;
argsList?: unknown[];
argsDict?: Record<string, unknown>;
}
/** Data received by a registered RPC invocation handler */
interface InvocationData {
details: Record<string, unknown>;
argsList?: unknown[];
argsDict?: Record<string, unknown>;
result_handler: (result?: InvocationResult | null) => void;
error_handler: (error: InvocationErrorData) => void;
}
/** Data returned/thrown by an RPC invocation handler */
interface InvocationResult {
argsList?: unknown[];
argsDict?: Record<string, unknown>;
options?: InvocationResultOptions;
}
/** Options that can be included in an invocation result */
interface InvocationResultOptions {
progress?: boolean;
ppt_scheme?: string;
ppt_serializer?: string;
ppt_cipher?: string;
ppt_keyid?: string;
[key: string]: unknown;
}
/** Error data for invocation error handler */
interface InvocationErrorData {
error?: string;
details?: Record<string, unknown>;
argsList?: unknown[];
argsDict?: Record<string, unknown>;
}
/** Callback for subscription events */
type EventCallback = (data: EventData) => void | Promise<void>;
/** Callback for RPC invocations */
type RPCCallback = (data: InvocationData) => InvocationResult | null | void | Promise<InvocationResult | null | void>;
/** Callback for challenge authentication (manual mode) */
type OnChallengeCallback = (authMethod: string, extra: Record<string, unknown>) => string | Promise<string>;
/** Auth plugin function (auto mode) */
type AuthPlugin = (authMethod: string, extra: Record<string, unknown>) => string | Promise<string>;
/** Callback for successful subscribe result */
interface SubscribeSuccessResult {
topic: string;
requestId: number;
subscriptionId: number;
subscriptionKey: string;
}
/** Callback for successful unsubscribe result */
interface UnsubscribeSuccessResult {
topic: string;
requestId: number;
}
/** Callback for successful publish result */
interface PublishSuccessResult {
topic: string;
requestId: number;
publicationId: number;
}
/** Callback for successful register result */
interface RegisterSuccessResult {
topic: string;
requestId: number;
registrationId: number;
}
/** Callback for successful unregister result */
interface UnregisterSuccessResult {
topic: string;
requestId: number;
}
/** Payload that can be passed to publish, call, or yielded from an RPC */
type Payload = unknown[] | Record<string, unknown> | PayloadWithArgsKwargs | string | number | boolean | null;
/** Payload with explicit argsList and argsDict */
interface PayloadWithArgsKwargs {
argsList?: unknown[];
argsDict?: Record<string, unknown>;
[key: string]: unknown;
}
/** Advanced options for subscribe() */
interface SubscribeAdvancedOptions {
/** Matching policy */
match?: 'exact' | 'prefix' | 'wildcard';
/** Request access to the Retained Event */
get_retained?: boolean;
/** Custom WAMP attributes (must match `_[a-z0-9_]{3,}` pattern) */
[key: string]: unknown;
}
/** Advanced options for publish() */
interface PublishAdvancedOptions {
/** WAMP session ID(s) that won't receive a published event */
exclude?: number | number[];
/** Authentication ID(s) that won't receive a published event */
exclude_authid?: string | string[];
/** Authentication role(s) that won't receive a published event */
exclude_authrole?: string | string[];
/** WAMP session ID(s) that are allowed to receive a published event */
eligible?: number | number[];
/** Authentication ID(s) that are allowed to receive a published event */
eligible_authid?: string | string[];
/** Authentication role(s) that are allowed to receive a published event */
eligible_authrole?: string | string[];
/** Flag of receiving publishing event by initiator */
exclude_me?: boolean;
/** Flag of disclosure of publisher identity to receivers */
disclose_me?: boolean;
/** Identifies the Payload Schema */
ppt_scheme?: string;
/** Specifies what serializer was used to encode the payload */
ppt_serializer?: string;
/** Specifies the cryptographic algorithm that was used to encrypt the payload */
ppt_cipher?: string;
/** Contains the encryption key id that was used to encrypt the payload */
ppt_keyid?: string;
/** Ask broker to mark this event as retained */
retain?: boolean;
/** Custom WAMP attributes (must match `_[a-z0-9_]{3,}` pattern) */
[key: string]: unknown;
}
/** Advanced options for call() */
interface CallAdvancedOptions {
/** Flag of disclosure of Caller identity to endpoints of a routed call */
disclose_me?: boolean;
/** Function for handling progressive call results */
progress_callback?: (data: CallResult) => void | Promise<void>;
/** Timeout (in ms) for the call to finish */
timeout?: number;
/** Identifies the Payload Schema */
ppt_scheme?: string;
/** Specifies what serializer was used to encode the payload */
ppt_serializer?: string;
/** Specifies the cryptographic algorithm that was used to encrypt the payload */
ppt_cipher?: string;
/** Contains the encryption key id that was used to encrypt the payload */
ppt_keyid?: string;
/** Custom WAMP attributes (must match `_[a-z0-9_]{3,}` pattern) */
[key: string]: unknown;
}
/** Advanced options for progressiveCall sendData() */
interface ProgressiveCallSendDataOptions {
/**
* Flag indicating the ongoing (true) or final (false) call invocation.
* If omitted, treated as true (ongoing). For the final call, set to false.
*/
progress?: boolean;
/** Custom WAMP attributes (must match `_[a-z0-9_]{3,}` pattern) */
[key: string]: unknown;
}
/** Advanced options for cancel() */
interface CancelAdvancedOptions {
/** Cancellation mode */
mode?: 'skip' | 'kill' | 'killnowait';
/** Custom WAMP attributes (must match `_[a-z0-9_]{3,}` pattern) */
[key: string]: unknown;
}
/** Advanced options for register() */
interface RegisterAdvancedOptions {
/** Matching policy */
match?: 'exact' | 'prefix' | 'wildcard';
/** Invocation policy for shared registrations */
invoke?: 'single' | 'roundrobin' | 'random' | 'first' | 'last';
/** Custom WAMP attributes (must match `_[a-z0-9_]{3,}` pattern) */
[key: string]: unknown;
}
/** Function to send additional data in a progressive call */
type ProgressiveCallSendData = (payload?: Payload, advancedOptions?: ProgressiveCallSendDataOptions) => void;
/** Return value of progressiveCall() */
interface ProgressiveCallReturn {
/** A promise that resolves to the result of the RPC call */
result: Promise<CallResult>;
/** A function to send additional data to the ongoing RPC call */
sendData: ProgressiveCallSendData;
}
/** User-provided WebSocket constructor type */
type WebSocketConstructor = {
new (url: string, protocols?: string[], origin?: null, headers?: Record<string, string>, requestOptions?: Record<string, unknown>): WebSocket;
};
/** Configuration options for the Wampy class */
interface WampyOptions {
/** Enable debug logging */
debug?: boolean;
/** Custom logger function */
logger?: ((...args: unknown[]) => void) | null;
/** Automatically reconnect on connection loss */
autoReconnect?: boolean;
/** Reconnection interval in milliseconds */
reconnectInterval?: number;
/** Maximum number of reconnection retries (0 = unlimited) */
maxRetries?: number;
/** WAMP Realm to join */
realm?: string | null;
/** Custom attributes to send to router on hello */
helloCustomDetails?: Record<string, unknown> | null;
/** Validation of the topic URI structure */
uriValidation?: 'strict' | 'loose';
/** Authentication ID to use in challenge */
authid?: string | null;
/** Supported authentication methods */
authmethods?: string[];
/** Additional authentication options (e.g., used in WAMP CryptoSign) */
authextra?: Record<string, unknown>;
/** Authentication helpers for processing different authmethods challenge flows */
authPlugins?: Record<string, AuthPlugin>;
/** Mode of authorization flow */
authMode?: 'manual' | 'auto';
/** Callback for challenge-based authentication */
onChallenge?: OnChallengeCallback | null;
/** Callback when connection closes */
onClose?: (() => void) | null;
/** Callback when an error occurs */
onError?: ((error: Error) => void | Promise<void>) | null;
/** Callback when reconnecting */
onReconnect?: (() => void) | null;
/** Callback when reconnection succeeds */
onReconnectSuccess?: ((details: Record<string, unknown>) => void | Promise<void>) | null;
/** User-provided WebSocket class */
ws?: WebSocketConstructor | null;
/** Additional HTTP headers (for use in Node.js environment) */
additionalHeaders?: Record<string, string> | null;
/** WS Client Config Options (for use in Node.js environment) */
wsRequestOptions?: Record<string, unknown> | null;
/** Serializer to use for WAMP messages */
serializer?: Serializer;
/** Serializers for Payload Passthru Mode, keyed by serializer name */
payloadSerializers?: Record<string, Serializer>;
}
/** Server WAMP features as returned in the WELCOME message */
interface ServerWampFeatures {
roles: Record<string, ServerWampRole>;
[key: string]: unknown;
}
/** A single WAMP server role with its features */
interface ServerWampRole {
features: Record<string, boolean>;
}
/**
* Project: wampy.js
*
* https://github.com/KSDaemon/wampy.js
*
* A lightweight client-side implementation of
* WAMP (The WebSocket Application Messaging Protocol v2)
* https://wamp-proto.org
*
* Provides asynchronous RPC/PubSub over WebSocket.
*
* Copyright 2014 KSDaemon. Licensed under the MIT License.
* See @license text at http://www.opensource.org/licenses/mit-license.php
*
*/
/**
* WAMP Client Class
*/
declare class Wampy {
/** Wampy version */
version: string;
/** WS Url */
private _url;
/** WS protocols */
private _protocols;
/** WAMP features, supported by Wampy */
private readonly _wamp_features;
/** Internal cache for object lifetime */
private _cache;
/** WebSocket object */
private _ws;
/** Internal queue for websocket requests, for case of disconnect */
private _wsQueue;
/** Internal queue for wamp requests */
private _requests;
/** Stored RPC */
private _calls;
/** Stored Pub/Subs to access by ID */
private readonly _subscriptionsById;
/** Stored Pub/Subs to access by Key */
private _subscriptionsByKey;
/** Stored RPC Registrations */
private _rpcRegs;
/** Stored RPC names */
private _rpcNames;
/** Options hash-table */
private _options;
constructor();
constructor(url: string);
constructor(options: WampyOptions);
constructor(url: string, options: WampyOptions);
/** Internal logger */
private _log;
/** Get the new unique request id */
private _getReqId;
/** Check if input is an object literal */
private _isPlainObject;
/** Set websocket protocol based on options */
private _setWsProtocols;
/** Fill instance operation status */
private _fillOpStatusByError;
/** Prerequisite checks for any wampy api call */
private _preReqChecks;
/** Check for specified feature in a role of connected WAMP Router */
private _checkRouterFeature;
/** Check for PPT mode options correctness */
private _checkPPTOptions;
/** Validate uri */
private _validateURI;
/** Prepares PPT/E2EE payload for adding to WAMP message */
private _packPPTPayload;
/** Unpack PPT/E2EE payload to common */
private _unpackPPTPayload;
/** Encode WAMP message */
private _encode;
/** Decode WAMP message */
private _decode;
/** Hard close of connection due to protocol violations */
private _hardClose;
/** Send encoded message to server */
private _send;
/** Reject (fail) all ongoing promises on connection closing */
private _reject_ongoing_promises;
/** Reset internal state and cache */
private _resetState;
/** Initialize internal websocket callbacks */
private _initWsCallbacks;
/** Internal websocket on open callback */
private _wsOnOpen;
/** Internal websocket on close callback */
_wsOnClose(event: CloseEvent): Promise<void>;
/** Internal websocket on event callback */
_wsOnMessage(event: MessageEvent): Promise<void>;
/** Validates the requestId for message types that need this kind of validation */
_isRequestIdValid([messageType, requestId]: unknown[]): boolean;
/**
* Handles websocket welcome message event
* WAMP SPEC: [WELCOME, Session|id, Details|dict]
*/
_onWelcomeMessage([, sessionId, details]: [unknown, number, ServerWampFeatures]): Promise<void>;
/**
* Handles websocket abort message event
* WAMP SPEC: [ABORT, Details|dict, Error|uri]
*/
_onAbortMessage([, details, error]: [unknown, Record<string, unknown>, string]): Promise<void>;
/**
* Handles websocket challenge message event
* WAMP SPEC: [CHALLENGE, AuthMethod|string, Extra|dict]
*/
_onChallengeMessage([, authMethod, extra]: [unknown, string, Record<string, unknown>]): Promise<void>;
/**
* Handles websocket goodbye message event
* WAMP SPEC: [GOODBYE, Details|dict, Reason|uri]
*/
_onGoodbyeMessage(): Promise<void>;
/**
* Handles websocket error message event
* WAMP SPEC: [ERROR, REQUEST.Type|int, REQUEST.Request|id, Details|dict,
* Error|uri, (Arguments|list, ArgumentsKw|dict)]
*/
_onErrorMessage([, requestType, requestId, details, error, argsList, argsDict]: [unknown, number, number, Record<string, unknown>, string, unknown[]?, Record<string, unknown>?]): Promise<void>;
/**
* Handles websocket subscribed message event
* WAMP SPEC: [SUBSCRIBED, SUBSCRIBE.Request|id, Subscription|id]
*/
_onSubscribedMessage([, requestId, subscriptionId]: [unknown, number, number]): Promise<void>;
/**
* Handles websocket unsubscribed message event
* WAMP SPEC: [UNSUBSCRIBED, UNSUBSCRIBE.Request|id]
*/
_onUnsubscribedMessage([, requestId]: [unknown, number]): Promise<void>;
/**
* Handles websocket published message event
* WAMP SPEC: [PUBLISHED, PUBLISH.Request|id, Publication|id]
*/
_onPublishedMessage([, requestId, publicationId]: [unknown, number, number]): Promise<void>;
/**
* Handles websocket event message event
* WAMP SPEC: [EVENT, SUBSCRIBED.Subscription|id, PUBLISHED.Publication|id,
* Details|dict, PUBLISH.Arguments|list, PUBLISH.ArgumentKw|dict]
*/
_onEventMessage([, subscriptionId, publicationId, details, argsList, argsDict]: [unknown, number, number, Record<string, unknown>, unknown[]?, Record<string, unknown>?]): Promise<void>;
/**
* Handles websocket result message event
* WAMP SPEC: [RESULT, CALL.Request|id, Details|dict,
* YIELD.Arguments|list, YIELD.ArgumentsKw|dict]
*/
_onResultMessage([, requestId, details, argsList, argsDict]: [unknown, number, Record<string, unknown>, unknown[]?, Record<string, unknown>?]): Promise<void>;
/**
* Handles websocket registered message event
* WAMP SPEC: [REGISTERED, REGISTER.Request|id, Registration|id]
*/
_onRegisteredMessage([, requestId, registrationId]: [unknown, number, number]): Promise<void>;
/**
* Handles websocket unregistered message event
* WAMP SPEC: [UNREGISTERED, UNREGISTER.Request|id]
*/
_onUnregisteredMessage([, requestId]: [unknown, number]): Promise<void>;
/**
* Handles websocket invocation message event
* WAMP SPEC: [INVOCATION, Request|id, REGISTERED.Registration|id, Details|dict,
* CALL.Arguments|list, CALL.ArgumentsKw|dict]
*/
_onInvocationMessage([, requestId, registrationId, details, argsList, argsDict]: [unknown, number, number, Record<string, unknown>, unknown[]?, Record<string, unknown>?]): Promise<void>;
/** Internal websocket on error callback */
_wsOnError(error: Event): Promise<void>;
/** Reconnect to server in case of websocket error */
_wsReconnect(): void;
/** Resubscribe to topics in case of communication error */
_renewSubscriptions(): Promise<void>;
/** ReRegister RPCs in case of communication error */
_renewRegistrations(): Promise<void>;
/**
* Generate a unique key for combination of topic and options
*
* This is needed to allow subscriptions to the same topic URI but with different options
*/
_getSubscriptionKey(topic: string, options?: SubscribeAdvancedOptions): string;
/*************************************************************************
* Wampy public API
*************************************************************************/
/** Wampy options getter */
getOptions(): Required<WampyOptions>;
/** Wampy options setter */
setOptions(newOptions: WampyOptions): Wampy | undefined;
/**
* Get the status of last operation
*
* Returns an object with 3 fields: code, error, reqId
* code: 0 - if operation was successful
* code > 0 - if error occurred
* error: error instance containing details
* reqId: last successfully sent request ID
*/
getOpStatus(): WampyOpStatus;
/** Get the WAMP Session ID */
getSessionId(): number | null;
/** Connect to server */
connect(url?: string): Promise<Record<string, unknown>>;
/** Disconnect from server */
disconnect(): Promise<unknown>;
/** Abort WAMP session establishment */
abort(): Wampy;
/** Subscribe to a topic on a broker */
subscribe(topic: string, onEvent: EventCallback, advancedOptions?: SubscribeAdvancedOptions): Promise<SubscribeSuccessResult>;
/** Unsubscribe from topic */
unsubscribe(subscriptionIdOrKey: number | string, onEvent?: EventCallback): Promise<UnsubscribeSuccessResult | true>;
/** Publish an event to the topic */
publish(topic: string, payload?: Payload, advancedOptions?: PublishAdvancedOptions): Promise<PublishSuccessResult>;
/** Extract custom options from advanced options as per WAMP spec 3.1 */
_extractCustomOptions(advancedOptions?: Record<string, unknown>): Record<string, unknown>;
/** Process CALL advanced options and transform them for the WAMP CALL message Options */
_getCallMessageOptionsFromAdvancedOptions(advancedOptions?: CallAdvancedOptions): Record<string, unknown>;
/** Remote Procedure Call Internal Implementation */
_callInternal(topic: string, payload?: Payload, advancedOptions?: CallAdvancedOptions): number;
/** Remote Procedure Call */
call(topic: string, payload?: Payload, advancedOptions?: CallAdvancedOptions): Promise<CallResult>;
/**
* Remote Procedure Progressive Call
*
* You can send additional input data which won't be treated as a new independent but instead
* will be transferred as another input data chunk to the same remote procedure call. Of course
* Callee and Dealer should support the "progressive_call_invocations" feature as well.
*/
progressiveCall(topic: string, payload?: Payload, advancedOptions?: CallAdvancedOptions): ProgressiveCallReturn;
/** RPC invocation cancelling */
cancel(reqId: number, advancedOptions?: CancelAdvancedOptions): boolean;
/** RPC registration for invocation */
register(topic: string, rpc: RPCCallback, advancedOptions?: RegisterAdvancedOptions): Promise<RegisterSuccessResult>;
/** RPC unregistration for invocation */
unregister(topic: string): Promise<UnregisterSuccessResult>;
}
export { Wampy, Wampy as default };