@triveria/wallet 0.0.309 → 0.0.314

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/api.d.ts CHANGED
@@ -1191,6 +1191,10 @@ export interface WalletNotification {
1191
1191
  * Timestamp in milliseconds
1192
1192
  */
1193
1193
  'createdTs': string;
1194
+ /**
1195
+ * State associated with the notification. Only populated in state-aware events
1196
+ */
1197
+ 'state'?: string;
1194
1198
  'time': string;
1195
1199
  }
1196
1200
  /**
@@ -1856,12 +1860,15 @@ export declare const DefaultApiAxiosParamCreator: (configuration?: Configuration
1856
1860
  */
1857
1861
  walletNotificationHistory: (walletId: string, limit?: number, nextMarker?: string, type?: Array<WalletNotificationEventType>, sort?: ListSort, newerThan?: number, options?: RawAxiosRequestConfig) => Promise<RequestArgs>;
1858
1862
  /**
1859
- * Provides first-in-first-out queue of notifications for a specific wallet.
1863
+ * Provides SSE stream of notifications for a specific wallet. Supports replay of queued notifications via `Last-Event-Id` header parameter.
1860
1864
  * @param {string} walletId Wallet ID
1865
+ * @param {string} [eventType] Event type
1866
+ * @param {string} [state] Event state
1867
+ * @param {string} [lastEventID] SSE last event ID
1861
1868
  * @param {*} [options] Override http request option.
1862
1869
  * @throws {RequiredError}
1863
1870
  */
1864
- walletNotifications: (walletId: string, options?: RawAxiosRequestConfig) => Promise<RequestArgs>;
1871
+ walletNotifications: (walletId: string, eventType?: string, state?: string, lastEventID?: string, options?: RawAxiosRequestConfig) => Promise<RequestArgs>;
1865
1872
  /**
1866
1873
  * Update wallet metadata and configuration.
1867
1874
  * @param {string} walletId
@@ -2466,12 +2473,15 @@ export declare const DefaultApiFp: (configuration?: Configuration) => {
2466
2473
  */
2467
2474
  walletNotificationHistory(walletId: string, limit?: number, nextMarker?: string, type?: Array<WalletNotificationEventType>, sort?: ListSort, newerThan?: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<WalletNotificationHistory>>;
2468
2475
  /**
2469
- * Provides first-in-first-out queue of notifications for a specific wallet.
2476
+ * Provides SSE stream of notifications for a specific wallet. Supports replay of queued notifications via `Last-Event-Id` header parameter.
2470
2477
  * @param {string} walletId Wallet ID
2478
+ * @param {string} [eventType] Event type
2479
+ * @param {string} [state] Event state
2480
+ * @param {string} [lastEventID] SSE last event ID
2471
2481
  * @param {*} [options] Override http request option.
2472
2482
  * @throws {RequiredError}
2473
2483
  */
2474
- walletNotifications(walletId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<WalletNotification>>>;
2484
+ walletNotifications(walletId: string, eventType?: string, state?: string, lastEventID?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<File>>;
2475
2485
  /**
2476
2486
  * Update wallet metadata and configuration.
2477
2487
  * @param {string} walletId
@@ -3076,12 +3086,15 @@ export declare const DefaultApiFactory: (configuration?: Configuration, basePath
3076
3086
  */
3077
3087
  walletNotificationHistory(walletId: string, limit?: number, nextMarker?: string, type?: Array<WalletNotificationEventType>, sort?: ListSort, newerThan?: number, options?: RawAxiosRequestConfig): AxiosPromise<WalletNotificationHistory>;
3078
3088
  /**
3079
- * Provides first-in-first-out queue of notifications for a specific wallet.
3089
+ * Provides SSE stream of notifications for a specific wallet. Supports replay of queued notifications via `Last-Event-Id` header parameter.
3080
3090
  * @param {string} walletId Wallet ID
3091
+ * @param {string} [eventType] Event type
3092
+ * @param {string} [state] Event state
3093
+ * @param {string} [lastEventID] SSE last event ID
3081
3094
  * @param {*} [options] Override http request option.
3082
3095
  * @throws {RequiredError}
3083
3096
  */
3084
- walletNotifications(walletId: string, options?: RawAxiosRequestConfig): AxiosPromise<Array<WalletNotification>>;
3097
+ walletNotifications(walletId: string, eventType?: string, state?: string, lastEventID?: string, options?: RawAxiosRequestConfig): AxiosPromise<File>;
3085
3098
  /**
3086
3099
  * Update wallet metadata and configuration.
3087
3100
  * @param {string} walletId
@@ -3686,12 +3699,15 @@ export declare class DefaultApi extends BaseAPI {
3686
3699
  */
3687
3700
  walletNotificationHistory(walletId: string, limit?: number, nextMarker?: string, type?: Array<WalletNotificationEventType>, sort?: ListSort, newerThan?: number, options?: RawAxiosRequestConfig): Promise<import("axios").AxiosResponse<WalletNotificationHistory, any, {}>>;
3688
3701
  /**
3689
- * Provides first-in-first-out queue of notifications for a specific wallet.
3702
+ * Provides SSE stream of notifications for a specific wallet. Supports replay of queued notifications via `Last-Event-Id` header parameter.
3690
3703
  * @param {string} walletId Wallet ID
3704
+ * @param {string} [eventType] Event type
3705
+ * @param {string} [state] Event state
3706
+ * @param {string} [lastEventID] SSE last event ID
3691
3707
  * @param {*} [options] Override http request option.
3692
3708
  * @throws {RequiredError}
3693
3709
  */
3694
- walletNotifications(walletId: string, options?: RawAxiosRequestConfig): Promise<import("axios").AxiosResponse<WalletNotification[], any, {}>>;
3710
+ walletNotifications(walletId: string, eventType?: string, state?: string, lastEventID?: string, options?: RawAxiosRequestConfig): Promise<import("axios").AxiosResponse<File, any, {}>>;
3695
3711
  /**
3696
3712
  * Update wallet metadata and configuration.
3697
3713
  * @param {string} walletId
package/api.js CHANGED
@@ -2320,12 +2320,15 @@ const DefaultApiAxiosParamCreator = function (configuration) {
2320
2320
  };
2321
2321
  }),
2322
2322
  /**
2323
- * Provides first-in-first-out queue of notifications for a specific wallet.
2323
+ * Provides SSE stream of notifications for a specific wallet. Supports replay of queued notifications via `Last-Event-Id` header parameter.
2324
2324
  * @param {string} walletId Wallet ID
2325
+ * @param {string} [eventType] Event type
2326
+ * @param {string} [state] Event state
2327
+ * @param {string} [lastEventID] SSE last event ID
2325
2328
  * @param {*} [options] Override http request option.
2326
2329
  * @throws {RequiredError}
2327
2330
  */
2328
- walletNotifications: (walletId_1, ...args_1) => __awaiter(this, [walletId_1, ...args_1], void 0, function* (walletId, options = {}) {
2331
+ walletNotifications: (walletId_1, eventType_1, state_1, lastEventID_1, ...args_1) => __awaiter(this, [walletId_1, eventType_1, state_1, lastEventID_1, ...args_1], void 0, function* (walletId, eventType, state, lastEventID, options = {}) {
2329
2332
  // verify required parameter 'walletId' is not null or undefined
2330
2333
  (0, common_1.assertParamExists)('walletNotifications', 'walletId', walletId);
2331
2334
  const localVarPath = `/wallets/{wallet_id}/notifications`
@@ -2342,7 +2345,16 @@ const DefaultApiAxiosParamCreator = function (configuration) {
2342
2345
  // authentication accessToken required
2343
2346
  // http bearer authentication required
2344
2347
  yield (0, common_1.setBearerAuthToObject)(localVarHeaderParameter, configuration);
2345
- localVarHeaderParameter['Accept'] = 'application/json';
2348
+ if (eventType !== undefined) {
2349
+ localVarQueryParameter['eventType'] = eventType;
2350
+ }
2351
+ if (state !== undefined) {
2352
+ localVarQueryParameter['state'] = state;
2353
+ }
2354
+ localVarHeaderParameter['Accept'] = 'text/event-stream,application/json';
2355
+ if (lastEventID != null) {
2356
+ localVarHeaderParameter['Last-Event-ID'] = String(lastEventID);
2357
+ }
2346
2358
  (0, common_1.setSearchParams)(localVarUrlObj, localVarQueryParameter);
2347
2359
  let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
2348
2360
  localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers);
@@ -3937,15 +3949,18 @@ const DefaultApiFp = function (configuration) {
3937
3949
  });
3938
3950
  },
3939
3951
  /**
3940
- * Provides first-in-first-out queue of notifications for a specific wallet.
3952
+ * Provides SSE stream of notifications for a specific wallet. Supports replay of queued notifications via `Last-Event-Id` header parameter.
3941
3953
  * @param {string} walletId Wallet ID
3954
+ * @param {string} [eventType] Event type
3955
+ * @param {string} [state] Event state
3956
+ * @param {string} [lastEventID] SSE last event ID
3942
3957
  * @param {*} [options] Override http request option.
3943
3958
  * @throws {RequiredError}
3944
3959
  */
3945
- walletNotifications(walletId, options) {
3960
+ walletNotifications(walletId, eventType, state, lastEventID, options) {
3946
3961
  return __awaiter(this, void 0, void 0, function* () {
3947
3962
  var _a, _b, _c;
3948
- const localVarAxiosArgs = yield localVarAxiosParamCreator.walletNotifications(walletId, options);
3963
+ const localVarAxiosArgs = yield localVarAxiosParamCreator.walletNotifications(walletId, eventType, state, lastEventID, options);
3949
3964
  const localVarOperationServerIndex = (_a = configuration === null || configuration === void 0 ? void 0 : configuration.serverIndex) !== null && _a !== void 0 ? _a : 0;
3950
3965
  const localVarOperationServerBasePath = (_c = (_b = base_1.operationServerMap['DefaultApi.walletNotifications']) === null || _b === void 0 ? void 0 : _b[localVarOperationServerIndex]) === null || _c === void 0 ? void 0 : _c.url;
3951
3966
  return (axios, basePath) => (0, common_1.createRequestFunction)(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration)(axios, localVarOperationServerBasePath || basePath);
@@ -4819,13 +4834,16 @@ const DefaultApiFactory = function (configuration, basePath, axios) {
4819
4834
  return localVarFp.walletNotificationHistory(walletId, limit, nextMarker, type, sort, newerThan, options).then((request) => request(axios, basePath));
4820
4835
  },
4821
4836
  /**
4822
- * Provides first-in-first-out queue of notifications for a specific wallet.
4837
+ * Provides SSE stream of notifications for a specific wallet. Supports replay of queued notifications via `Last-Event-Id` header parameter.
4823
4838
  * @param {string} walletId Wallet ID
4839
+ * @param {string} [eventType] Event type
4840
+ * @param {string} [state] Event state
4841
+ * @param {string} [lastEventID] SSE last event ID
4824
4842
  * @param {*} [options] Override http request option.
4825
4843
  * @throws {RequiredError}
4826
4844
  */
4827
- walletNotifications(walletId, options) {
4828
- return localVarFp.walletNotifications(walletId, options).then((request) => request(axios, basePath));
4845
+ walletNotifications(walletId, eventType, state, lastEventID, options) {
4846
+ return localVarFp.walletNotifications(walletId, eventType, state, lastEventID, options).then((request) => request(axios, basePath));
4829
4847
  },
4830
4848
  /**
4831
4849
  * Update wallet metadata and configuration.
@@ -5579,13 +5597,16 @@ class DefaultApi extends base_1.BaseAPI {
5579
5597
  return (0, exports.DefaultApiFp)(this.configuration).walletNotificationHistory(walletId, limit, nextMarker, type, sort, newerThan, options).then((request) => request(this.axios, this.basePath));
5580
5598
  }
5581
5599
  /**
5582
- * Provides first-in-first-out queue of notifications for a specific wallet.
5600
+ * Provides SSE stream of notifications for a specific wallet. Supports replay of queued notifications via `Last-Event-Id` header parameter.
5583
5601
  * @param {string} walletId Wallet ID
5602
+ * @param {string} [eventType] Event type
5603
+ * @param {string} [state] Event state
5604
+ * @param {string} [lastEventID] SSE last event ID
5584
5605
  * @param {*} [options] Override http request option.
5585
5606
  * @throws {RequiredError}
5586
5607
  */
5587
- walletNotifications(walletId, options) {
5588
- return (0, exports.DefaultApiFp)(this.configuration).walletNotifications(walletId, options).then((request) => request(this.axios, this.basePath));
5608
+ walletNotifications(walletId, eventType, state, lastEventID, options) {
5609
+ return (0, exports.DefaultApiFp)(this.configuration).walletNotifications(walletId, eventType, state, lastEventID, options).then((request) => request(this.axios, this.basePath));
5589
5610
  }
5590
5611
  /**
5591
5612
  * Update wallet metadata and configuration.
package/client.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { AxiosInstance } from "axios";
2
2
  import { DefaultApi } from "./api";
3
+ import { WalletNotificationStream, WalletNotificationStreamOptions } from "./notifications";
3
4
  export type ClientConfiguration = {
4
5
  clientId: string;
5
6
  clientSecret: string;
@@ -14,4 +15,10 @@ export declare class Client extends DefaultApi {
14
15
  protected baseURL: string;
15
16
  protected axios: AxiosInstance;
16
17
  constructor(tokenUrl: string, audience: string, clientId: string, clientSecret: string, baseURL: string, axios?: AxiosInstance);
18
+ /**
19
+ * Opens a live stream of notifications for a wallet over SSE.
20
+ * @param walletId Wallet ID
21
+ * @param options Stream filtering/reconnect options
22
+ */
23
+ streamWalletNotifications(walletId: string, options?: WalletNotificationStreamOptions): WalletNotificationStream;
17
24
  }
package/client.js CHANGED
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Client = void 0;
7
7
  const api_1 = require("./api");
8
+ const notifications_1 = require("./notifications");
8
9
  const axios_1 = __importDefault(require("axios"));
9
10
  const auth_1 = require("./auth");
10
11
  /**
@@ -23,6 +24,14 @@ class Client extends api_1.DefaultApi {
23
24
  this.baseURL = baseURL;
24
25
  this.axios = axios;
25
26
  }
27
+ /**
28
+ * Opens a live stream of notifications for a wallet over SSE.
29
+ * @param walletId Wallet ID
30
+ * @param options Stream filtering/reconnect options
31
+ */
32
+ streamWalletNotifications(walletId, options = {}) {
33
+ return new notifications_1.WalletNotificationStream(this.configuration, walletId, Object.assign({ axios: this.axios, basePath: this.basePath }, options));
34
+ }
26
35
  }
27
36
  exports.Client = Client;
28
37
  function isJsonMime(mime) {
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Hand-written client for the `walletNotifications` SSE endpoint.
3
+ *
4
+ * This file is NOT managed by the OpenAPI generator (see .openapi-generator/FILES) -
5
+ * it builds on top of the generated request builder in `api.ts` to provide an
6
+ * ergonomic Node.js client for the `GET /wallets/{wallet_id}/notifications`
7
+ * `text/event-stream` endpoint, including reconnect-with-replay via `Last-Event-ID`.
8
+ */
9
+ import { EventEmitter } from 'events';
10
+ import type { AxiosInstance } from 'axios';
11
+ import { Configuration } from './configuration';
12
+ import { WalletNotification } from './api';
13
+ export interface WalletNotificationStreamOptions {
14
+ /** Filter the stream to a single notification event type. */
15
+ eventType?: string;
16
+ /** Filter the stream to a single notification state. */
17
+ state?: string;
18
+ /** Resume the stream after this event ID (queued notification replay). */
19
+ lastEventId?: string;
20
+ /** Axios instance to use for the underlying request. Defaults to the global axios instance. */
21
+ axios?: AxiosInstance;
22
+ /** Overrides the base path used to reach the API. */
23
+ basePath?: string;
24
+ /** Automatically reconnect (with replay via Last-Event-ID) when the stream drops. Defaults to true. */
25
+ reconnect?: boolean;
26
+ /** Delay before reconnecting when the server hasn't sent an SSE `retry:` field. Defaults to 3000ms. */
27
+ retryDelayMs?: number;
28
+ /** Upper bound for the reconnect delay, including any server-provided `retry:` value. Defaults to 30000ms. */
29
+ maxRetryDelayMs?: number;
30
+ }
31
+ export declare interface WalletNotificationStream {
32
+ on(event: 'open', listener: () => void): this;
33
+ on(event: 'notification', listener: (notification: WalletNotification) => void): this;
34
+ on(event: 'error', listener: (error: Error) => void): this;
35
+ on(event: 'close', listener: () => void): this;
36
+ once(event: 'open', listener: () => void): this;
37
+ once(event: 'notification', listener: (notification: WalletNotification) => void): this;
38
+ once(event: 'error', listener: (error: Error) => void): this;
39
+ once(event: 'close', listener: () => void): this;
40
+ }
41
+ /**
42
+ * Live stream of wallet notifications over `GET /wallets/{wallet_id}/notifications`.
43
+ *
44
+ * Emits `open`, `notification`, `error` and `close` events, and is itself an
45
+ * async iterable of {@link WalletNotification}:
46
+ *
47
+ * ```ts
48
+ * const stream = new WalletNotificationStream(configuration, walletId);
49
+ * for await (const notification of stream) {
50
+ * console.log(notification);
51
+ * }
52
+ * ```
53
+ *
54
+ * Drops are reconnected automatically (replaying queued notifications via
55
+ * `Last-Event-ID`) unless `options.reconnect` is set to `false`.
56
+ */
57
+ export declare class WalletNotificationStream extends EventEmitter implements AsyncIterable<WalletNotification> {
58
+ private readonly configuration;
59
+ private readonly walletId;
60
+ private readonly axiosInstance;
61
+ private readonly basePath;
62
+ private readonly eventType?;
63
+ private readonly state?;
64
+ private readonly reconnect;
65
+ private readonly retryDelayMs;
66
+ private readonly maxRetryDelayMs;
67
+ private lastEventId?;
68
+ private nextRetryDelayMs?;
69
+ private abortController?;
70
+ private retryTimer?;
71
+ private closed;
72
+ private readonly queue;
73
+ private readonly waiters;
74
+ constructor(configuration: Configuration, walletId: string, options?: WalletNotificationStreamOptions);
75
+ /** Stops the stream and prevents further reconnection attempts. */
76
+ close(): void;
77
+ get isClosed(): boolean;
78
+ private connect;
79
+ private scheduleReconnect;
80
+ private dispatchToQueue;
81
+ private settleWaiters;
82
+ [Symbol.asyncIterator](): AsyncIterator<WalletNotification>;
83
+ }
@@ -0,0 +1,284 @@
1
+ "use strict";
2
+ /**
3
+ * Hand-written client for the `walletNotifications` SSE endpoint.
4
+ *
5
+ * This file is NOT managed by the OpenAPI generator (see .openapi-generator/FILES) -
6
+ * it builds on top of the generated request builder in `api.ts` to provide an
7
+ * ergonomic Node.js client for the `GET /wallets/{wallet_id}/notifications`
8
+ * `text/event-stream` endpoint, including reconnect-with-replay via `Last-Event-ID`.
9
+ */
10
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
12
+ return new (P || (P = Promise))(function (resolve, reject) {
13
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
14
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
15
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
16
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
17
+ });
18
+ };
19
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
20
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
21
+ var m = o[Symbol.asyncIterator], i;
22
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
23
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
24
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
25
+ };
26
+ var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
27
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
28
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
29
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
30
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
31
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
32
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
33
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
34
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
35
+ function fulfill(value) { resume("next", value); }
36
+ function reject(value) { resume("throw", value); }
37
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
38
+ };
39
+ var __importDefault = (this && this.__importDefault) || function (mod) {
40
+ return (mod && mod.__esModule) ? mod : { "default": mod };
41
+ };
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.WalletNotificationStream = void 0;
44
+ const events_1 = require("events");
45
+ const axios_1 = __importDefault(require("axios"));
46
+ const base_1 = require("./base");
47
+ const common_1 = require("./common");
48
+ const api_1 = require("./api");
49
+ /**
50
+ * Parses a raw byte/text stream into Server-Sent Events per the WHATWG spec
51
+ * (https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation).
52
+ */
53
+ function parseSseStream(source) {
54
+ return __asyncGenerator(this, arguments, function* parseSseStream_1() {
55
+ var _a, e_1, _b, _c;
56
+ let buffer = '';
57
+ let eventType;
58
+ let dataLines = [];
59
+ let id;
60
+ let sawData = false;
61
+ function takeEvent() {
62
+ const event = sawData
63
+ ? { kind: 'event', id, event: eventType, data: dataLines.join('\n') }
64
+ : undefined;
65
+ eventType = undefined;
66
+ dataLines = [];
67
+ sawData = false;
68
+ return event;
69
+ }
70
+ try {
71
+ for (var _d = true, source_1 = __asyncValues(source), source_1_1; source_1_1 = yield __await(source_1.next()), _a = source_1_1.done, !_a; _d = true) {
72
+ _c = source_1_1.value;
73
+ _d = false;
74
+ const chunk = _c;
75
+ buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
76
+ let newlineIndex;
77
+ while ((newlineIndex = buffer.indexOf('\n')) >= 0) {
78
+ let line = buffer.slice(0, newlineIndex);
79
+ buffer = buffer.slice(newlineIndex + 1);
80
+ if (line.endsWith('\r')) {
81
+ line = line.slice(0, -1);
82
+ }
83
+ if (line === '') {
84
+ const event = takeEvent();
85
+ if (event)
86
+ yield yield __await(event);
87
+ continue;
88
+ }
89
+ if (line.startsWith(':')) {
90
+ continue;
91
+ }
92
+ const colonIndex = line.indexOf(':');
93
+ const field = colonIndex === -1 ? line : line.slice(0, colonIndex);
94
+ let value = colonIndex === -1 ? '' : line.slice(colonIndex + 1);
95
+ if (value.startsWith(' '))
96
+ value = value.slice(1);
97
+ switch (field) {
98
+ case 'event':
99
+ eventType = value;
100
+ break;
101
+ case 'data':
102
+ dataLines.push(value);
103
+ sawData = true;
104
+ break;
105
+ case 'id':
106
+ // Per spec, an id field containing a NUL character is ignored.
107
+ if (!value.includes('\u0000'))
108
+ id = value;
109
+ break;
110
+ case 'retry':
111
+ // Unlike `data`/`id`, `retry` is not part of a dispatched event - it
112
+ // just updates the reconnection delay for future reconnects.
113
+ if (/^\d+$/.test(value))
114
+ yield yield __await({ kind: 'retry', delayMs: parseInt(value, 10) });
115
+ break;
116
+ }
117
+ }
118
+ }
119
+ }
120
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
121
+ finally {
122
+ try {
123
+ if (!_d && !_a && (_b = source_1.return)) yield __await(_b.call(source_1));
124
+ }
125
+ finally { if (e_1) throw e_1.error; }
126
+ }
127
+ });
128
+ }
129
+ /**
130
+ * Live stream of wallet notifications over `GET /wallets/{wallet_id}/notifications`.
131
+ *
132
+ * Emits `open`, `notification`, `error` and `close` events, and is itself an
133
+ * async iterable of {@link WalletNotification}:
134
+ *
135
+ * ```ts
136
+ * const stream = new WalletNotificationStream(configuration, walletId);
137
+ * for await (const notification of stream) {
138
+ * console.log(notification);
139
+ * }
140
+ * ```
141
+ *
142
+ * Drops are reconnected automatically (replaying queued notifications via
143
+ * `Last-Event-ID`) unless `options.reconnect` is set to `false`.
144
+ */
145
+ class WalletNotificationStream extends events_1.EventEmitter {
146
+ constructor(configuration, walletId, options = {}) {
147
+ var _a, _b, _c, _d, _e, _f;
148
+ super();
149
+ this.configuration = configuration;
150
+ this.walletId = walletId;
151
+ this.closed = false;
152
+ this.queue = [];
153
+ this.waiters = [];
154
+ this.axiosInstance = (_a = options.axios) !== null && _a !== void 0 ? _a : axios_1.default;
155
+ this.basePath = (_c = (_b = options.basePath) !== null && _b !== void 0 ? _b : configuration.basePath) !== null && _c !== void 0 ? _c : base_1.BASE_PATH;
156
+ this.eventType = options.eventType;
157
+ this.state = options.state;
158
+ this.lastEventId = options.lastEventId;
159
+ this.reconnect = (_d = options.reconnect) !== null && _d !== void 0 ? _d : true;
160
+ this.retryDelayMs = (_e = options.retryDelayMs) !== null && _e !== void 0 ? _e : 3000;
161
+ this.maxRetryDelayMs = (_f = options.maxRetryDelayMs) !== null && _f !== void 0 ? _f : 30000;
162
+ void this.connect();
163
+ }
164
+ /** Stops the stream and prevents further reconnection attempts. */
165
+ close() {
166
+ var _a;
167
+ if (this.closed)
168
+ return;
169
+ this.closed = true;
170
+ if (this.retryTimer)
171
+ clearTimeout(this.retryTimer);
172
+ (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
173
+ this.settleWaiters();
174
+ this.emit('close');
175
+ }
176
+ get isClosed() {
177
+ return this.closed;
178
+ }
179
+ connect() {
180
+ return __awaiter(this, void 0, void 0, function* () {
181
+ var _a, e_2, _b, _c;
182
+ var _d;
183
+ if (this.closed)
184
+ return;
185
+ this.abortController = new AbortController();
186
+ try {
187
+ const requestArgs = yield (0, api_1.DefaultApiAxiosParamCreator)(this.configuration).walletNotifications(this.walletId, this.eventType, this.state, this.lastEventId, { signal: this.abortController.signal, responseType: 'stream' });
188
+ const request = (0, common_1.createRequestFunction)(requestArgs, this.axiosInstance, this.basePath, this.configuration);
189
+ const response = yield request(this.axiosInstance, this.basePath);
190
+ this.emit('open');
191
+ try {
192
+ for (var _e = true, _f = __asyncValues(parseSseStream(response.data)), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) {
193
+ _c = _g.value;
194
+ _e = false;
195
+ const message = _c;
196
+ if (this.closed)
197
+ break;
198
+ if (message.kind === 'retry') {
199
+ this.nextRetryDelayMs = message.delayMs;
200
+ continue;
201
+ }
202
+ if (message.id !== undefined)
203
+ this.lastEventId = message.id;
204
+ if (!message.data)
205
+ continue;
206
+ let notification;
207
+ try {
208
+ notification = JSON.parse(message.data);
209
+ }
210
+ catch (_h) {
211
+ this.emit('error', new Error(`Failed to parse wallet notification payload: ${message.data}`));
212
+ continue;
213
+ }
214
+ this.emit('notification', notification);
215
+ this.dispatchToQueue(notification);
216
+ }
217
+ }
218
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
219
+ finally {
220
+ try {
221
+ if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);
222
+ }
223
+ finally { if (e_2) throw e_2.error; }
224
+ }
225
+ if (this.closed)
226
+ return;
227
+ this.scheduleReconnect();
228
+ }
229
+ catch (err) {
230
+ if (this.closed)
231
+ return;
232
+ this.emit('error', err instanceof Error ? err : new Error(String(err)));
233
+ const status = (_d = err === null || err === void 0 ? void 0 : err.response) === null || _d === void 0 ? void 0 : _d.status;
234
+ if (status !== undefined && status >= 400 && status < 500) {
235
+ // Client errors (bad wallet ID, invalid/expired token, ...) won't be fixed by retrying.
236
+ this.close();
237
+ return;
238
+ }
239
+ this.scheduleReconnect();
240
+ }
241
+ });
242
+ }
243
+ scheduleReconnect() {
244
+ var _a;
245
+ if (this.closed || !this.reconnect) {
246
+ this.close();
247
+ return;
248
+ }
249
+ const delay = Math.min((_a = this.nextRetryDelayMs) !== null && _a !== void 0 ? _a : this.retryDelayMs, this.maxRetryDelayMs);
250
+ this.retryTimer = setTimeout(() => void this.connect(), delay);
251
+ }
252
+ dispatchToQueue(notification) {
253
+ const waiter = this.waiters.shift();
254
+ if (waiter) {
255
+ waiter({ value: notification, done: false });
256
+ }
257
+ else {
258
+ this.queue.push(notification);
259
+ }
260
+ }
261
+ settleWaiters() {
262
+ while (this.waiters.length) {
263
+ this.waiters.shift()({ value: undefined, done: true });
264
+ }
265
+ }
266
+ [Symbol.asyncIterator]() {
267
+ return {
268
+ next: () => {
269
+ if (this.queue.length) {
270
+ return Promise.resolve({ value: this.queue.shift(), done: false });
271
+ }
272
+ if (this.closed) {
273
+ return Promise.resolve({ value: undefined, done: true });
274
+ }
275
+ return new Promise((resolve) => this.waiters.push(resolve));
276
+ },
277
+ return: () => {
278
+ this.close();
279
+ return Promise.resolve({ value: undefined, done: true });
280
+ },
281
+ };
282
+ }
283
+ }
284
+ exports.WalletNotificationStream = WalletNotificationStream;
package/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "@triveria/wallet",
3
3
  "private": false,
4
- "version": "0.0.309",
4
+ "version": "0.0.314",
5
5
  "description": "",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/triveria-com/wallet-sdk-ts.git"
9
+ },
6
10
  "main": "index.js",
7
11
  "scripts": {
8
12
  "test": "echo \"Error: no test specified\" && exit 1",