@brokerize/client 1.11.0 → 1.12.1
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/README.md +45 -0
- package/dist/apiCtx.d.ts +10 -2
- package/dist/apiCtx.js +4 -4
- package/dist/authorizedApiContext.d.ts +20 -0
- package/dist/authorizedApiContext.js +47 -5
- package/dist/cjs/apiCtx.d.ts +10 -2
- package/dist/cjs/apiCtx.js +4 -4
- package/dist/cjs/authorizedApiContext.d.ts +20 -0
- package/dist/cjs/authorizedApiContext.js +46 -4
- package/dist/cjs/errors.d.ts +60 -0
- package/dist/cjs/errors.js +48 -1
- package/dist/cjs/index.d.ts +4 -4
- package/dist/cjs/index.js +4 -1
- package/dist/cjs/modelExports.d.ts +2 -0
- package/dist/cjs/modelExports.js +3 -1
- package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfo.d.ts +60 -0
- package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfo.js +51 -0
- package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfoStatus.d.ts +22 -0
- package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfoStatus.js +35 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoComplete.d.ts +7 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoComplete.js +6 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoCompleteSpecifics.d.ts +7 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoCompleteSpecifics.js +5 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoIncomplete.d.ts +7 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoIncomplete.js +6 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoIncompleteSpecifics.d.ts +7 -0
- package/dist/cjs/swagger/models/PortfolioSyncInfoIncompleteSpecifics.js +5 -0
- package/dist/cjs/swagger/models/TradeWarningReason.d.ts +1 -0
- package/dist/cjs/swagger/models/TradeWarningReason.js +1 -0
- package/dist/cjs/swagger/models/index.d.ts +2 -0
- package/dist/cjs/swagger/models/index.js +2 -0
- package/dist/cjs/websocketClient.d.ts +118 -3
- package/dist/cjs/websocketClient.js +426 -74
- package/dist/cjs/websocketTypes.d.ts +10 -0
- package/dist/client.d.ts +262 -46
- package/dist/errors.d.ts +60 -0
- package/dist/errors.js +44 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/modelExports.d.ts +2 -0
- package/dist/modelExports.js +1 -0
- package/dist/swagger/models/PortfolioOrderDetailsSyncInfo.d.ts +60 -0
- package/dist/swagger/models/PortfolioOrderDetailsSyncInfo.js +45 -0
- package/dist/swagger/models/PortfolioOrderDetailsSyncInfoStatus.d.ts +22 -0
- package/dist/swagger/models/PortfolioOrderDetailsSyncInfoStatus.js +29 -0
- package/dist/swagger/models/PortfolioSyncInfoComplete.d.ts +7 -0
- package/dist/swagger/models/PortfolioSyncInfoComplete.js +6 -0
- package/dist/swagger/models/PortfolioSyncInfoCompleteSpecifics.d.ts +7 -0
- package/dist/swagger/models/PortfolioSyncInfoCompleteSpecifics.js +5 -0
- package/dist/swagger/models/PortfolioSyncInfoIncomplete.d.ts +7 -0
- package/dist/swagger/models/PortfolioSyncInfoIncomplete.js +6 -0
- package/dist/swagger/models/PortfolioSyncInfoIncompleteSpecifics.d.ts +7 -0
- package/dist/swagger/models/PortfolioSyncInfoIncompleteSpecifics.js +5 -0
- package/dist/swagger/models/TradeWarningReason.d.ts +1 -0
- package/dist/swagger/models/TradeWarningReason.js +1 -0
- package/dist/swagger/models/index.d.ts +2 -0
- package/dist/swagger/models/index.js +2 -0
- package/dist/tsdoc-metadata.json +1 -1
- package/dist/websocketClient.d.ts +118 -3
- package/dist/websocketClient.js +426 -74
- package/dist/websocketTypes.d.ts +10 -0
- package/package.json +10 -9
package/README.md
CHANGED
|
@@ -63,6 +63,51 @@ async function someBrokerizeActions() {
|
|
|
63
63
|
someBrokerizeActions().then(console.log, console.error)
|
|
64
64
|
```
|
|
65
65
|
|
|
66
|
+
# websocket error handling
|
|
67
|
+
|
|
68
|
+
Every error reported by the websocket client is a `BrokerizeWebSocketError`, a subclass of
|
|
69
|
+
`BrokerizeError`, so it can be handled like any other error of this library. Errors reach an
|
|
70
|
+
application through two separate channels:
|
|
71
|
+
|
|
72
|
+
- **Subscription callbacks** only receive _terminal_ errors: the subscription is over and will not
|
|
73
|
+
receive any further data. This maps directly onto e.g. an RxJS `subscriber.error()`.
|
|
74
|
+
- **`subscribeConnectionState`** reports the state of the underlying connection, including the
|
|
75
|
+
errors that the client recovers from on its own. Use it to tell the user that live updates are
|
|
76
|
+
currently unavailable, instead of tearing down subscriptions on every connection hiccup.
|
|
77
|
+
|
|
78
|
+
```js
|
|
79
|
+
const client = ctx.createWebSocketClient();
|
|
80
|
+
|
|
81
|
+
client.subscribeConnectionState(({ status, error }) => {
|
|
82
|
+
/* 'closed' | 'connecting' | 'open' | 'reconnecting' | 'fatal' */
|
|
83
|
+
if (status == "fatal") {
|
|
84
|
+
/* the client is unusable, all subscriptions were terminated with `error`. */
|
|
85
|
+
console.error("live updates stopped", error);
|
|
86
|
+
client.reconnect(); /* ... and subscribe again */
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
client.subscribeInvalidate({ entity: "sessions" }, (err) => {
|
|
91
|
+
if (err) {
|
|
92
|
+
/* err is a BrokerizeWebSocketError with err.terminal === true. */
|
|
93
|
+
console.error("subscription ended", err.code, err.message);
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
reloadSessions();
|
|
97
|
+
});
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
A connection that cannot be authenticated is not a special case: the client refreshes the token
|
|
101
|
+
and keeps retrying with a wide backoff, staying in `reconnecting` with the rejection as `error`.
|
|
102
|
+
The usual cause is an id token that expired in flight, and the first retry fixes it without the
|
|
103
|
+
application noticing more than a short gap - the subscriptions stay alive throughout. Only a token
|
|
104
|
+
that is still being rejected after several minutes makes the client `fatal`, because by then the
|
|
105
|
+
session is gone rather than stale.
|
|
106
|
+
|
|
107
|
+
This means an application does not need its own retry: it only has to decide what to show while
|
|
108
|
+
`status` is `reconnecting`, and how to react to `fatal` - usually the same way it reacts to a `401`
|
|
109
|
+
on the REST API, which it will have seen by then anyway.
|
|
110
|
+
|
|
66
111
|
# development & maintenance
|
|
67
112
|
|
|
68
113
|
The code in `src/swagger` is generated by the npm script `npm run generate` from the OpenAPI spec and will be regenerated whenever API changes are made. No manual changes should be made in the `src/swagger` directory. `npm run download-spec` will download the current spec from `api-preview.brokerize.com`.
|
package/dist/apiCtx.d.ts
CHANGED
|
@@ -64,8 +64,16 @@ export interface GuestAuthContextConfiguration {
|
|
|
64
64
|
response: Models.CreateGuestUserResponse;
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
|
+
export type GetTokenOptions = {
|
|
68
|
+
/**
|
|
69
|
+
* Request a fresh token even if the currently known one is not expired yet. Used by the
|
|
70
|
+
* websocket client to retry once after the server rejected a token, before giving up.
|
|
71
|
+
* Implementations that cannot refresh on demand may ignore this.
|
|
72
|
+
*/
|
|
73
|
+
forceRefresh?: boolean;
|
|
74
|
+
};
|
|
67
75
|
export interface Auth {
|
|
68
|
-
getToken: () => Promise<{
|
|
76
|
+
getToken: (opts?: GetTokenOptions) => Promise<{
|
|
69
77
|
idToken: string;
|
|
70
78
|
}>;
|
|
71
79
|
}
|
|
@@ -87,7 +95,7 @@ export type CognitoPoolConfig = {
|
|
|
87
95
|
};
|
|
88
96
|
export type CognitoFacade = {
|
|
89
97
|
createSession: (cognitoPoolConfig: CognitoPoolConfig, authCfg: RegisteredUserAuthContextConfiguration) => {
|
|
90
|
-
getToken: () => Promise<{
|
|
98
|
+
getToken: (opts?: GetTokenOptions) => Promise<{
|
|
91
99
|
idToken: string;
|
|
92
100
|
}>;
|
|
93
101
|
};
|
package/dist/apiCtx.js
CHANGED
|
@@ -39,7 +39,7 @@ export function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
|
|
|
39
39
|
if (authCfg.type == "guest") {
|
|
40
40
|
const guestAuthCfg = JSON.parse(JSON.stringify(authCfg)); // clone it
|
|
41
41
|
return {
|
|
42
|
-
async getToken() {
|
|
42
|
+
async getToken(opts) {
|
|
43
43
|
if (guestAuthCfg.tokens) {
|
|
44
44
|
let expiresIn = guestAuthCfg.tokens.response.expiresIn;
|
|
45
45
|
if (expiresIn == null) {
|
|
@@ -49,7 +49,7 @@ export function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
|
|
|
49
49
|
}
|
|
50
50
|
/* modern tokens */
|
|
51
51
|
const tokenExpiresAt = guestAuthCfg.tokens.updatedAt + expiresIn * 1000 - 10000;
|
|
52
|
-
const needsRefresh = Date.now() > tokenExpiresAt;
|
|
52
|
+
const needsRefresh = (opts === null || opts === void 0 ? void 0 : opts.forceRefresh) || Date.now() > tokenExpiresAt;
|
|
53
53
|
if (needsRefresh && guestAuthCfg.tokens.response.refreshToken) {
|
|
54
54
|
if (!cfg.fetch) {
|
|
55
55
|
throw new Error("Invalid cfg: fetch is required for refreshing tokens.");
|
|
@@ -104,8 +104,8 @@ export function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
|
|
|
104
104
|
}
|
|
105
105
|
const session = options.cognitoFacade.createSession((_a = cfg.cognito) === null || _a === void 0 ? void 0 : _a.poolConfig, authCfg);
|
|
106
106
|
return {
|
|
107
|
-
async getToken() {
|
|
108
|
-
return session.getToken();
|
|
107
|
+
async getToken(opts) {
|
|
108
|
+
return session.getToken(opts);
|
|
109
109
|
},
|
|
110
110
|
};
|
|
111
111
|
}
|
|
@@ -18,6 +18,11 @@ export declare class AuthorizedApiContext {
|
|
|
18
18
|
private readonly _orderApiCryptoService;
|
|
19
19
|
private readonly _logoutSubject;
|
|
20
20
|
private readonly _wsClient;
|
|
21
|
+
/**
|
|
22
|
+
* `true` if this context created the websocket client itself and therefore has to destroy it.
|
|
23
|
+
* A client passed in by the application is owned by the application.
|
|
24
|
+
*/
|
|
25
|
+
private readonly _ownsWsClient;
|
|
21
26
|
private readonly _cache;
|
|
22
27
|
private readonly _exportApi;
|
|
23
28
|
private readonly _adminApi;
|
|
@@ -27,6 +32,21 @@ export declare class AuthorizedApiContext {
|
|
|
27
32
|
private readonly _syncApi;
|
|
28
33
|
private readonly _decoupledOperationsApi;
|
|
29
34
|
constructor(cfg: BrokerizeConfig, auth: Auth, wsClient?: BrokerizeWebSocketClient);
|
|
35
|
+
/**
|
|
36
|
+
* The websocket client keeps one context around to refetch the status of a decoupled operation
|
|
37
|
+
* with after an interrupted connection. That context has to outlive the connection, so it must
|
|
38
|
+
* not simply be whichever one was constructed last: child contexts are commonly created per
|
|
39
|
+
* request and destroyed again, and a destroyed context cannot perform that request.
|
|
40
|
+
*
|
|
41
|
+
* The first context attaches and keeps the client - that is the one that created it, and the
|
|
42
|
+
* children, which are handed the very same client, leave it alone.
|
|
43
|
+
*/
|
|
44
|
+
private _attachToWsClient;
|
|
45
|
+
/**
|
|
46
|
+
* Counterpart of `_attachToWsClient`: leave no destroyed context behind, so that a context
|
|
47
|
+
* created later can take over.
|
|
48
|
+
*/
|
|
49
|
+
private _detachFromWsClient;
|
|
30
50
|
createChildContext(): AuthorizedApiContext;
|
|
31
51
|
private _initRequestInit;
|
|
32
52
|
getBrokers(): Promise<openApiClient.GetBrokersResponse>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Subject } from "rxjs";
|
|
2
2
|
import { createConfiguration, withAcceptLanguage, } from "./apiCtx.js";
|
|
3
|
-
import { createErrorFromResponse } from "./errors.js";
|
|
3
|
+
import { BrokerizeAbortError, createErrorFromResponse } from "./errors.js";
|
|
4
4
|
import { createPollingSubscription } from "./pollingSubscription.js";
|
|
5
5
|
import * as openApiClient from "./swagger/index.js";
|
|
6
6
|
import { BrokerizeWebSocketClientImpl, } from "./websocketClient.js";
|
|
@@ -51,12 +51,45 @@ export class AuthorizedApiContext {
|
|
|
51
51
|
throw new Error("createAbortController not provided. This should not happen as there should be a default implementation.");
|
|
52
52
|
}
|
|
53
53
|
this._abortController = cfg.createAbortController();
|
|
54
|
+
this._ownsWsClient = !wsClient;
|
|
54
55
|
this._wsClient = wsClient || this._initInternalWebSocketClient();
|
|
55
|
-
|
|
56
|
-
this._wsClient._setAuthorizedApiContext(this);
|
|
57
|
-
}
|
|
56
|
+
this._attachToWsClient();
|
|
58
57
|
this._cache = {};
|
|
59
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* The websocket client keeps one context around to refetch the status of a decoupled operation
|
|
61
|
+
* with after an interrupted connection. That context has to outlive the connection, so it must
|
|
62
|
+
* not simply be whichever one was constructed last: child contexts are commonly created per
|
|
63
|
+
* request and destroyed again, and a destroyed context cannot perform that request.
|
|
64
|
+
*
|
|
65
|
+
* The first context attaches and keeps the client - that is the one that created it, and the
|
|
66
|
+
* children, which are handed the very same client, leave it alone.
|
|
67
|
+
*/
|
|
68
|
+
_attachToWsClient() {
|
|
69
|
+
const wsClient = this._wsClient;
|
|
70
|
+
/* an application may pass in its own implementation of the interface. */
|
|
71
|
+
if (!wsClient._setAuthorizedApiContext ||
|
|
72
|
+
!wsClient._getAuthorizedApiContext) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (!wsClient._getAuthorizedApiContext()) {
|
|
76
|
+
wsClient._setAuthorizedApiContext(this);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Counterpart of `_attachToWsClient`: leave no destroyed context behind, so that a context
|
|
81
|
+
* created later can take over.
|
|
82
|
+
*/
|
|
83
|
+
_detachFromWsClient() {
|
|
84
|
+
const wsClient = this._wsClient;
|
|
85
|
+
if (!wsClient._setAuthorizedApiContext ||
|
|
86
|
+
!wsClient._getAuthorizedApiContext) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (wsClient._getAuthorizedApiContext() === this) {
|
|
90
|
+
wsClient._setAuthorizedApiContext(null);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
60
93
|
createChildContext() {
|
|
61
94
|
const result = new AuthorizedApiContext(this._cfg, this._auth, this._wsClient);
|
|
62
95
|
const childContexts = this._childContexts;
|
|
@@ -70,7 +103,7 @@ export class AuthorizedApiContext {
|
|
|
70
103
|
}
|
|
71
104
|
async _initRequestInit() {
|
|
72
105
|
if (this._isDestroyed) {
|
|
73
|
-
throw new
|
|
106
|
+
throw new BrokerizeAbortError("AuthorizedApiContext is destroyed");
|
|
74
107
|
}
|
|
75
108
|
const tok = await this._auth.getToken();
|
|
76
109
|
const headers = await withAcceptLanguage(this._cfg, {
|
|
@@ -434,12 +467,21 @@ export class AuthorizedApiContext {
|
|
|
434
467
|
const wrappedClient = {
|
|
435
468
|
subscribeDecoupledOperation: this._wsClient.subscribeDecoupledOperation.bind(this._wsClient),
|
|
436
469
|
subscribeInvalidate: this._wsClient.subscribeInvalidate.bind(this._wsClient),
|
|
470
|
+
subscribeConnectionState: this._wsClient.subscribeConnectionState.bind(this._wsClient),
|
|
471
|
+
getConnectionState: this._wsClient.getConnectionState.bind(this._wsClient),
|
|
472
|
+
reconnect: this._wsClient.reconnect.bind(this._wsClient),
|
|
437
473
|
};
|
|
438
474
|
return wrappedClient;
|
|
439
475
|
}
|
|
440
476
|
destroy() {
|
|
441
477
|
this._isDestroyed = true;
|
|
442
478
|
this._abortController.abort();
|
|
479
|
+
this._detachFromWsClient();
|
|
480
|
+
if (this._ownsWsClient) {
|
|
481
|
+
/* otherwise its reconnect timer would keep running and keep reconnecting with the
|
|
482
|
+
tokens of a context that is gone. */
|
|
483
|
+
this._wsClient.destroy();
|
|
484
|
+
}
|
|
443
485
|
}
|
|
444
486
|
subscribeLogout(callback) {
|
|
445
487
|
const s = this._logoutSubject.subscribe({
|
package/dist/cjs/apiCtx.d.ts
CHANGED
|
@@ -64,8 +64,16 @@ export interface GuestAuthContextConfiguration {
|
|
|
64
64
|
response: Models.CreateGuestUserResponse;
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
|
+
export type GetTokenOptions = {
|
|
68
|
+
/**
|
|
69
|
+
* Request a fresh token even if the currently known one is not expired yet. Used by the
|
|
70
|
+
* websocket client to retry once after the server rejected a token, before giving up.
|
|
71
|
+
* Implementations that cannot refresh on demand may ignore this.
|
|
72
|
+
*/
|
|
73
|
+
forceRefresh?: boolean;
|
|
74
|
+
};
|
|
67
75
|
export interface Auth {
|
|
68
|
-
getToken: () => Promise<{
|
|
76
|
+
getToken: (opts?: GetTokenOptions) => Promise<{
|
|
69
77
|
idToken: string;
|
|
70
78
|
}>;
|
|
71
79
|
}
|
|
@@ -87,7 +95,7 @@ export type CognitoPoolConfig = {
|
|
|
87
95
|
};
|
|
88
96
|
export type CognitoFacade = {
|
|
89
97
|
createSession: (cognitoPoolConfig: CognitoPoolConfig, authCfg: RegisteredUserAuthContextConfiguration) => {
|
|
90
|
-
getToken: () => Promise<{
|
|
98
|
+
getToken: (opts?: GetTokenOptions) => Promise<{
|
|
91
99
|
idToken: string;
|
|
92
100
|
}>;
|
|
93
101
|
};
|
package/dist/cjs/apiCtx.js
CHANGED
|
@@ -45,7 +45,7 @@ function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
|
|
|
45
45
|
if (authCfg.type == "guest") {
|
|
46
46
|
const guestAuthCfg = JSON.parse(JSON.stringify(authCfg)); // clone it
|
|
47
47
|
return {
|
|
48
|
-
async getToken() {
|
|
48
|
+
async getToken(opts) {
|
|
49
49
|
if (guestAuthCfg.tokens) {
|
|
50
50
|
let expiresIn = guestAuthCfg.tokens.response.expiresIn;
|
|
51
51
|
if (expiresIn == null) {
|
|
@@ -55,7 +55,7 @@ function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
|
|
|
55
55
|
}
|
|
56
56
|
/* modern tokens */
|
|
57
57
|
const tokenExpiresAt = guestAuthCfg.tokens.updatedAt + expiresIn * 1000 - 10000;
|
|
58
|
-
const needsRefresh = Date.now() > tokenExpiresAt;
|
|
58
|
+
const needsRefresh = (opts === null || opts === void 0 ? void 0 : opts.forceRefresh) || Date.now() > tokenExpiresAt;
|
|
59
59
|
if (needsRefresh && guestAuthCfg.tokens.response.refreshToken) {
|
|
60
60
|
if (!cfg.fetch) {
|
|
61
61
|
throw new Error("Invalid cfg: fetch is required for refreshing tokens.");
|
|
@@ -110,8 +110,8 @@ function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
|
|
|
110
110
|
}
|
|
111
111
|
const session = options.cognitoFacade.createSession((_a = cfg.cognito) === null || _a === void 0 ? void 0 : _a.poolConfig, authCfg);
|
|
112
112
|
return {
|
|
113
|
-
async getToken() {
|
|
114
|
-
return session.getToken();
|
|
113
|
+
async getToken(opts) {
|
|
114
|
+
return session.getToken(opts);
|
|
115
115
|
},
|
|
116
116
|
};
|
|
117
117
|
}
|
|
@@ -18,6 +18,11 @@ export declare class AuthorizedApiContext {
|
|
|
18
18
|
private readonly _orderApiCryptoService;
|
|
19
19
|
private readonly _logoutSubject;
|
|
20
20
|
private readonly _wsClient;
|
|
21
|
+
/**
|
|
22
|
+
* `true` if this context created the websocket client itself and therefore has to destroy it.
|
|
23
|
+
* A client passed in by the application is owned by the application.
|
|
24
|
+
*/
|
|
25
|
+
private readonly _ownsWsClient;
|
|
21
26
|
private readonly _cache;
|
|
22
27
|
private readonly _exportApi;
|
|
23
28
|
private readonly _adminApi;
|
|
@@ -27,6 +32,21 @@ export declare class AuthorizedApiContext {
|
|
|
27
32
|
private readonly _syncApi;
|
|
28
33
|
private readonly _decoupledOperationsApi;
|
|
29
34
|
constructor(cfg: BrokerizeConfig, auth: Auth, wsClient?: BrokerizeWebSocketClient);
|
|
35
|
+
/**
|
|
36
|
+
* The websocket client keeps one context around to refetch the status of a decoupled operation
|
|
37
|
+
* with after an interrupted connection. That context has to outlive the connection, so it must
|
|
38
|
+
* not simply be whichever one was constructed last: child contexts are commonly created per
|
|
39
|
+
* request and destroyed again, and a destroyed context cannot perform that request.
|
|
40
|
+
*
|
|
41
|
+
* The first context attaches and keeps the client - that is the one that created it, and the
|
|
42
|
+
* children, which are handed the very same client, leave it alone.
|
|
43
|
+
*/
|
|
44
|
+
private _attachToWsClient;
|
|
45
|
+
/**
|
|
46
|
+
* Counterpart of `_attachToWsClient`: leave no destroyed context behind, so that a context
|
|
47
|
+
* created later can take over.
|
|
48
|
+
*/
|
|
49
|
+
private _detachFromWsClient;
|
|
30
50
|
createChildContext(): AuthorizedApiContext;
|
|
31
51
|
private _initRequestInit;
|
|
32
52
|
getBrokers(): Promise<openApiClient.GetBrokersResponse>;
|
|
@@ -88,12 +88,45 @@ class AuthorizedApiContext {
|
|
|
88
88
|
throw new Error("createAbortController not provided. This should not happen as there should be a default implementation.");
|
|
89
89
|
}
|
|
90
90
|
this._abortController = cfg.createAbortController();
|
|
91
|
+
this._ownsWsClient = !wsClient;
|
|
91
92
|
this._wsClient = wsClient || this._initInternalWebSocketClient();
|
|
92
|
-
|
|
93
|
-
this._wsClient._setAuthorizedApiContext(this);
|
|
94
|
-
}
|
|
93
|
+
this._attachToWsClient();
|
|
95
94
|
this._cache = {};
|
|
96
95
|
}
|
|
96
|
+
/**
|
|
97
|
+
* The websocket client keeps one context around to refetch the status of a decoupled operation
|
|
98
|
+
* with after an interrupted connection. That context has to outlive the connection, so it must
|
|
99
|
+
* not simply be whichever one was constructed last: child contexts are commonly created per
|
|
100
|
+
* request and destroyed again, and a destroyed context cannot perform that request.
|
|
101
|
+
*
|
|
102
|
+
* The first context attaches and keeps the client - that is the one that created it, and the
|
|
103
|
+
* children, which are handed the very same client, leave it alone.
|
|
104
|
+
*/
|
|
105
|
+
_attachToWsClient() {
|
|
106
|
+
const wsClient = this._wsClient;
|
|
107
|
+
/* an application may pass in its own implementation of the interface. */
|
|
108
|
+
if (!wsClient._setAuthorizedApiContext ||
|
|
109
|
+
!wsClient._getAuthorizedApiContext) {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (!wsClient._getAuthorizedApiContext()) {
|
|
113
|
+
wsClient._setAuthorizedApiContext(this);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Counterpart of `_attachToWsClient`: leave no destroyed context behind, so that a context
|
|
118
|
+
* created later can take over.
|
|
119
|
+
*/
|
|
120
|
+
_detachFromWsClient() {
|
|
121
|
+
const wsClient = this._wsClient;
|
|
122
|
+
if (!wsClient._setAuthorizedApiContext ||
|
|
123
|
+
!wsClient._getAuthorizedApiContext) {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (wsClient._getAuthorizedApiContext() === this) {
|
|
127
|
+
wsClient._setAuthorizedApiContext(null);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
97
130
|
createChildContext() {
|
|
98
131
|
const result = new AuthorizedApiContext(this._cfg, this._auth, this._wsClient);
|
|
99
132
|
const childContexts = this._childContexts;
|
|
@@ -107,7 +140,7 @@ class AuthorizedApiContext {
|
|
|
107
140
|
}
|
|
108
141
|
async _initRequestInit() {
|
|
109
142
|
if (this._isDestroyed) {
|
|
110
|
-
throw new
|
|
143
|
+
throw new errors_1.BrokerizeAbortError("AuthorizedApiContext is destroyed");
|
|
111
144
|
}
|
|
112
145
|
const tok = await this._auth.getToken();
|
|
113
146
|
const headers = await (0, apiCtx_1.withAcceptLanguage)(this._cfg, {
|
|
@@ -471,12 +504,21 @@ class AuthorizedApiContext {
|
|
|
471
504
|
const wrappedClient = {
|
|
472
505
|
subscribeDecoupledOperation: this._wsClient.subscribeDecoupledOperation.bind(this._wsClient),
|
|
473
506
|
subscribeInvalidate: this._wsClient.subscribeInvalidate.bind(this._wsClient),
|
|
507
|
+
subscribeConnectionState: this._wsClient.subscribeConnectionState.bind(this._wsClient),
|
|
508
|
+
getConnectionState: this._wsClient.getConnectionState.bind(this._wsClient),
|
|
509
|
+
reconnect: this._wsClient.reconnect.bind(this._wsClient),
|
|
474
510
|
};
|
|
475
511
|
return wrappedClient;
|
|
476
512
|
}
|
|
477
513
|
destroy() {
|
|
478
514
|
this._isDestroyed = true;
|
|
479
515
|
this._abortController.abort();
|
|
516
|
+
this._detachFromWsClient();
|
|
517
|
+
if (this._ownsWsClient) {
|
|
518
|
+
/* otherwise its reconnect timer would keep running and keep reconnecting with the
|
|
519
|
+
tokens of a context that is gone. */
|
|
520
|
+
this._wsClient.destroy();
|
|
521
|
+
}
|
|
480
522
|
}
|
|
481
523
|
subscribeLogout(callback) {
|
|
482
524
|
const s = this._logoutSubject.subscribe({
|
package/dist/cjs/errors.d.ts
CHANGED
|
@@ -79,3 +79,63 @@ export declare class BrokerizeTimeoutError extends BrokerizeError {
|
|
|
79
79
|
* JSON parse error.
|
|
80
80
|
*/
|
|
81
81
|
export declare function createErrorFromResponse(response: Response): Promise<BrokerizeError>;
|
|
82
|
+
/**
|
|
83
|
+
* Error codes used by {@link BrokerizeWebSocketError}.
|
|
84
|
+
*
|
|
85
|
+
* - `AUTH`: the websocket connection could not be authenticated. Same code as a failed token
|
|
86
|
+
* refresh on the REST API, so applications can treat both identically.
|
|
87
|
+
* - `WEBSOCKET_CONNECTION_FAILED`: the connection could not be established or was lost
|
|
88
|
+
* (network error, failed handshake, closed socket). The client retries these automatically.
|
|
89
|
+
* - `WEBSOCKET_PROTOCOL_ERROR`: a message from the server could not be parsed.
|
|
90
|
+
* - `WEBSOCKET_ERROR`: any other error reported by the server.
|
|
91
|
+
*/
|
|
92
|
+
export type BrokerizeWebSocketErrorCode = "AUTH" | "WEBSOCKET_CONNECTION_FAILED" | "WEBSOCKET_PROTOCOL_ERROR" | "WEBSOCKET_ERROR";
|
|
93
|
+
export type BrokerizeWebSocketErrorParams = {
|
|
94
|
+
msg: string;
|
|
95
|
+
code: BrokerizeWebSocketErrorCode;
|
|
96
|
+
httpStatusCode?: number;
|
|
97
|
+
/**
|
|
98
|
+
* See {@link BrokerizeWebSocketError.terminal}.
|
|
99
|
+
*/
|
|
100
|
+
terminal?: boolean;
|
|
101
|
+
/**
|
|
102
|
+
* The underlying error or event, if any (e.g. the rejection of `Auth.getToken` or the
|
|
103
|
+
* `error` event of the websocket).
|
|
104
|
+
*/
|
|
105
|
+
cause?: unknown;
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* Every error reported by the websocket client is an instance of this class, so applications can
|
|
109
|
+
* handle it like any other error (`instanceof Error`, `err.message`, stack trace) and can use the
|
|
110
|
+
* same error handling as for the REST API, which reports `BrokerizeError`.
|
|
111
|
+
*/
|
|
112
|
+
export declare class BrokerizeWebSocketError extends BrokerizeError {
|
|
113
|
+
/**
|
|
114
|
+
* If `true`, the affected subscription is over and will not receive any further data. Errors
|
|
115
|
+
* that are passed to a subscription callback are always terminal; non-terminal errors are only
|
|
116
|
+
* reported via `BrokerizeWebSocketClient.subscribeConnectionState`, because the client
|
|
117
|
+
* recovers from them on its own.
|
|
118
|
+
*/
|
|
119
|
+
readonly terminal: boolean;
|
|
120
|
+
/**
|
|
121
|
+
* The underlying error or event, if any.
|
|
122
|
+
*/
|
|
123
|
+
readonly cause?: unknown;
|
|
124
|
+
constructor({ msg, code, httpStatusCode, terminal, cause, }: BrokerizeWebSocketErrorParams);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Check whether the given value is a `BrokerizeWebSocketError`. Prefer this over `instanceof`,
|
|
128
|
+
* which fails if more than one copy of this package ends up in a dependency tree.
|
|
129
|
+
*/
|
|
130
|
+
export declare function isBrokerizeWebSocketError(x: unknown): x is BrokerizeWebSocketError;
|
|
131
|
+
/**
|
|
132
|
+
* Thrown when a request is made on an `AuthorizedApiContext` that was already destroyed.
|
|
133
|
+
*
|
|
134
|
+
* `destroy()` aborts the context's `AbortController`, so a request that is already in flight
|
|
135
|
+
* rejects with a `DOMException` named `AbortError`. This error carries the same `name`, so that
|
|
136
|
+
* both cases can be handled with a single check (`err.name === "AbortError"`), the way `fetch`
|
|
137
|
+
* itself rejects when handed an already-aborted signal.
|
|
138
|
+
*/
|
|
139
|
+
export declare class BrokerizeAbortError extends Error {
|
|
140
|
+
constructor(msg: string);
|
|
141
|
+
}
|
package/dist/cjs/errors.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.BrokerizeTimeoutError = exports.BrokerizeError = exports.TradingError = void 0;
|
|
3
|
+
exports.BrokerizeAbortError = exports.BrokerizeWebSocketError = exports.BrokerizeTimeoutError = exports.BrokerizeError = exports.TradingError = void 0;
|
|
4
4
|
exports.createErrorFromResponse = createErrorFromResponse;
|
|
5
|
+
exports.isBrokerizeWebSocketError = isBrokerizeWebSocketError;
|
|
5
6
|
class TradingError extends Error {
|
|
6
7
|
constructor({ msg, code, brokerCode, brokerError, msgBrokerName, httpStatusCode, hint, }) {
|
|
7
8
|
super(msg);
|
|
@@ -75,3 +76,49 @@ async function createErrorFromResponse(response) {
|
|
|
75
76
|
code: "INTERNAL_SERVER_ERROR",
|
|
76
77
|
});
|
|
77
78
|
}
|
|
79
|
+
const DEFAULT_STATUS_CODES = {
|
|
80
|
+
AUTH: 401,
|
|
81
|
+
WEBSOCKET_CONNECTION_FAILED: 503,
|
|
82
|
+
WEBSOCKET_PROTOCOL_ERROR: 500,
|
|
83
|
+
WEBSOCKET_ERROR: 500,
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Every error reported by the websocket client is an instance of this class, so applications can
|
|
87
|
+
* handle it like any other error (`instanceof Error`, `err.message`, stack trace) and can use the
|
|
88
|
+
* same error handling as for the REST API, which reports `BrokerizeError`.
|
|
89
|
+
*/
|
|
90
|
+
class BrokerizeWebSocketError extends BrokerizeError {
|
|
91
|
+
constructor({ msg, code, httpStatusCode, terminal, cause, }) {
|
|
92
|
+
super(httpStatusCode !== null && httpStatusCode !== void 0 ? httpStatusCode : DEFAULT_STATUS_CODES[code], { msg, code });
|
|
93
|
+
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain (https://stackoverflow.com/questions/41102060/typescript-extending-error-class)
|
|
94
|
+
this.name = "BrokerizeWebSocketError";
|
|
95
|
+
this.terminal = terminal !== null && terminal !== void 0 ? terminal : false;
|
|
96
|
+
this.cause = cause;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
exports.BrokerizeWebSocketError = BrokerizeWebSocketError;
|
|
100
|
+
/**
|
|
101
|
+
* Check whether the given value is a `BrokerizeWebSocketError`. Prefer this over `instanceof`,
|
|
102
|
+
* which fails if more than one copy of this package ends up in a dependency tree.
|
|
103
|
+
*/
|
|
104
|
+
function isBrokerizeWebSocketError(x) {
|
|
105
|
+
return (!!x &&
|
|
106
|
+
typeof x === "object" &&
|
|
107
|
+
x.name === "BrokerizeWebSocketError");
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Thrown when a request is made on an `AuthorizedApiContext` that was already destroyed.
|
|
111
|
+
*
|
|
112
|
+
* `destroy()` aborts the context's `AbortController`, so a request that is already in flight
|
|
113
|
+
* rejects with a `DOMException` named `AbortError`. This error carries the same `name`, so that
|
|
114
|
+
* both cases can be handled with a single check (`err.name === "AbortError"`), the way `fetch`
|
|
115
|
+
* itself rejects when handed an already-aborted signal.
|
|
116
|
+
*/
|
|
117
|
+
class BrokerizeAbortError extends Error {
|
|
118
|
+
constructor(msg) {
|
|
119
|
+
super(msg);
|
|
120
|
+
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain (https://stackoverflow.com/questions/41102060/typescript-extending-error-class)
|
|
121
|
+
this.name = "AbortError";
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
exports.BrokerizeAbortError = BrokerizeAbortError;
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { Auth, AuthContextConfiguration, BrokerizeConfig, CognitoConfig, CognitoFacade, CognitoPoolConfig, GuestAuthContextConfiguration, RegisteredUserAuthContextConfiguration, TokenSet } from "./apiCtx";
|
|
1
|
+
import { Auth, AuthContextConfiguration, BrokerizeConfig, CognitoConfig, CognitoFacade, CognitoPoolConfig, GetTokenOptions, GuestAuthContextConfiguration, RegisteredUserAuthContextConfiguration, TokenSet } from "./apiCtx";
|
|
2
2
|
import { AuthorizedApiContext } from "./authorizedApiContext";
|
|
3
|
-
import { BrokerizeError, BrokerizeTimeoutError } from "./errors";
|
|
3
|
+
import { BrokerizeAbortError, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, isBrokerizeWebSocketError } from "./errors";
|
|
4
4
|
import * as openApiClient from "./swagger";
|
|
5
5
|
import * as Models from "./modelExports";
|
|
6
|
-
import { BrokerizeWebSocketClient, Callback, Subscription } from "./websocketClient";
|
|
6
|
+
import { BrokerizeWebSocketClient, BrokerizeWebSocketClientOptions, Callback, ConnectionStateCallback, Subscription, WebSocketConnectionState, WebSocketConnectionStatus } from "./websocketClient";
|
|
7
7
|
import * as WebSocketTypes from "./websocketTypes";
|
|
8
8
|
import * as Utils from "./utils";
|
|
9
|
-
export { BrokerizeConfig, AuthContextConfiguration, AuthorizedApiContext, BrokerizeWebSocketClient, Models, WebSocketTypes, Subscription, Callback, Utils, BrokerizeError, BrokerizeTimeoutError, Auth, TokenSet, };
|
|
9
|
+
export { BrokerizeConfig, AuthContextConfiguration, AuthorizedApiContext, BrokerizeWebSocketClient, Models, WebSocketTypes, Subscription, Callback, Utils, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, BrokerizeAbortError, GetTokenOptions, isBrokerizeWebSocketError, ConnectionStateCallback, BrokerizeWebSocketClientOptions, WebSocketConnectionState, WebSocketConnectionStatus, Auth, TokenSet, };
|
|
10
10
|
export { CognitoPoolConfig, RegisteredUserAuthContextConfiguration };
|
|
11
11
|
export { CognitoConfig, CognitoFacade };
|
|
12
12
|
export declare class Brokerize {
|
package/dist/cjs/index.js
CHANGED
|
@@ -33,15 +33,18 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.Brokerize = exports.BrokerizeTimeoutError = exports.BrokerizeError = exports.Utils = exports.WebSocketTypes = exports.Models = exports.AuthorizedApiContext = void 0;
|
|
36
|
+
exports.Brokerize = exports.isBrokerizeWebSocketError = exports.BrokerizeAbortError = exports.BrokerizeWebSocketError = exports.BrokerizeTimeoutError = exports.BrokerizeError = exports.Utils = exports.WebSocketTypes = exports.Models = exports.AuthorizedApiContext = void 0;
|
|
37
37
|
/* Import/Export the DOM parts we rely on. Those are partial copies from the official TypeScript DOM library definitions (https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts),
|
|
38
38
|
but reduced to the parts actually used by bg-trading. */
|
|
39
39
|
const apiCtx_1 = require("./apiCtx");
|
|
40
40
|
const authorizedApiContext_1 = require("./authorizedApiContext");
|
|
41
41
|
Object.defineProperty(exports, "AuthorizedApiContext", { enumerable: true, get: function () { return authorizedApiContext_1.AuthorizedApiContext; } });
|
|
42
42
|
const errors_1 = require("./errors");
|
|
43
|
+
Object.defineProperty(exports, "BrokerizeAbortError", { enumerable: true, get: function () { return errors_1.BrokerizeAbortError; } });
|
|
43
44
|
Object.defineProperty(exports, "BrokerizeError", { enumerable: true, get: function () { return errors_1.BrokerizeError; } });
|
|
44
45
|
Object.defineProperty(exports, "BrokerizeTimeoutError", { enumerable: true, get: function () { return errors_1.BrokerizeTimeoutError; } });
|
|
46
|
+
Object.defineProperty(exports, "BrokerizeWebSocketError", { enumerable: true, get: function () { return errors_1.BrokerizeWebSocketError; } });
|
|
47
|
+
Object.defineProperty(exports, "isBrokerizeWebSocketError", { enumerable: true, get: function () { return errors_1.isBrokerizeWebSocketError; } });
|
|
45
48
|
const openApiClient = __importStar(require("./swagger"));
|
|
46
49
|
const Models = __importStar(require("./modelExports"));
|
|
47
50
|
exports.Models = Models;
|
|
@@ -86,6 +86,8 @@ export { GetBrokersResponse } from "./swagger/models/GetBrokersResponse";
|
|
|
86
86
|
export { GetCostEstimationParams } from "./swagger/models/GetCostEstimationParams";
|
|
87
87
|
export { GetOrderResponse } from "./swagger/models/GetOrderResponse";
|
|
88
88
|
export { GetPortfolioOrdersResponse } from "./swagger/models/GetPortfolioOrdersResponse";
|
|
89
|
+
export { PortfolioOrderDetailsSyncInfo } from "./swagger/models/PortfolioOrderDetailsSyncInfo";
|
|
90
|
+
export { PortfolioOrderDetailsSyncInfoStatus } from "./swagger/models/PortfolioOrderDetailsSyncInfoStatus";
|
|
89
91
|
export { GetPortfolioPositionsResponse } from "./swagger/models/GetPortfolioPositionsResponse";
|
|
90
92
|
export { GetPortfolioQuotesResponse } from "./swagger/models/GetPortfolioQuotesResponse";
|
|
91
93
|
export { GetQuoteParams } from "./swagger/models/GetQuoteParams";
|
package/dist/cjs/modelExports.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/* tslint:disable */
|
|
3
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
-
exports.TradeWarningReason = exports.OrderIntent = exports.TrailingDistanceModeEnum = exports.SessionSyncInfoStatus = exports.PrepareOAuthRedirectParamsAppearanceEnum = exports.PortfolioSyncInfoStatus = exports.OrderValidityType = exports.OrderStatus = exports.OrderModel = exports.OrderExtension = exports.LoginResponseState = exports.GenericTableRowValueType = exports.GenericTableRowValueLinkValueType = exports.GenericTableRowType = exports.EnableSessionTanParamsKind = exports.Direction = exports.DecoupledOperationState = exports.CashQuotation = exports.CancelOrderParamsMode = exports.BrokerEnvFilterType = exports.AuthMethodFlow = void 0;
|
|
4
|
+
exports.TradeWarningReason = exports.OrderIntent = exports.TrailingDistanceModeEnum = exports.SessionSyncInfoStatus = exports.PrepareOAuthRedirectParamsAppearanceEnum = exports.PortfolioSyncInfoStatus = exports.OrderValidityType = exports.OrderStatus = exports.OrderModel = exports.OrderExtension = exports.LoginResponseState = exports.PortfolioOrderDetailsSyncInfoStatus = exports.GenericTableRowValueType = exports.GenericTableRowValueLinkValueType = exports.GenericTableRowType = exports.EnableSessionTanParamsKind = exports.Direction = exports.DecoupledOperationState = exports.CashQuotation = exports.CancelOrderParamsMode = exports.BrokerEnvFilterType = exports.AuthMethodFlow = void 0;
|
|
5
5
|
var AuthMethodFlow_1 = require("./swagger/models/AuthMethodFlow");
|
|
6
6
|
Object.defineProperty(exports, "AuthMethodFlow", { enumerable: true, get: function () { return AuthMethodFlow_1.AuthMethodFlow; } });
|
|
7
7
|
var BrokerEnvFilterType_1 = require("./swagger/models/BrokerEnvFilterType");
|
|
@@ -22,6 +22,8 @@ var GenericTableRowValueLinkValueType_1 = require("./swagger/models/GenericTable
|
|
|
22
22
|
Object.defineProperty(exports, "GenericTableRowValueLinkValueType", { enumerable: true, get: function () { return GenericTableRowValueLinkValueType_1.GenericTableRowValueLinkValueType; } });
|
|
23
23
|
var GenericTableRowValueType_1 = require("./swagger/models/GenericTableRowValueType");
|
|
24
24
|
Object.defineProperty(exports, "GenericTableRowValueType", { enumerable: true, get: function () { return GenericTableRowValueType_1.GenericTableRowValueType; } });
|
|
25
|
+
var PortfolioOrderDetailsSyncInfoStatus_1 = require("./swagger/models/PortfolioOrderDetailsSyncInfoStatus");
|
|
26
|
+
Object.defineProperty(exports, "PortfolioOrderDetailsSyncInfoStatus", { enumerable: true, get: function () { return PortfolioOrderDetailsSyncInfoStatus_1.PortfolioOrderDetailsSyncInfoStatus; } });
|
|
25
27
|
var LoginResponseState_1 = require("./swagger/models/LoginResponseState");
|
|
26
28
|
Object.defineProperty(exports, "LoginResponseState", { enumerable: true, get: function () { return LoginResponseState_1.LoginResponseState; } });
|
|
27
29
|
var OrderExtension_1 = require("./swagger/models/OrderExtension");
|