@brokerize/client 1.11.0 → 1.12.0

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.
Files changed (62) hide show
  1. package/README.md +45 -0
  2. package/dist/apiCtx.d.ts +10 -2
  3. package/dist/apiCtx.js +4 -4
  4. package/dist/authorizedApiContext.d.ts +5 -0
  5. package/dist/authorizedApiContext.js +11 -2
  6. package/dist/cjs/apiCtx.d.ts +10 -2
  7. package/dist/cjs/apiCtx.js +4 -4
  8. package/dist/cjs/authorizedApiContext.d.ts +5 -0
  9. package/dist/cjs/authorizedApiContext.js +10 -1
  10. package/dist/cjs/errors.d.ts +60 -0
  11. package/dist/cjs/errors.js +48 -1
  12. package/dist/cjs/index.d.ts +4 -4
  13. package/dist/cjs/index.js +4 -1
  14. package/dist/cjs/modelExports.d.ts +2 -0
  15. package/dist/cjs/modelExports.js +3 -1
  16. package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfo.d.ts +60 -0
  17. package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfo.js +51 -0
  18. package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfoStatus.d.ts +22 -0
  19. package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfoStatus.js +35 -0
  20. package/dist/cjs/swagger/models/PortfolioSyncInfoComplete.d.ts +7 -0
  21. package/dist/cjs/swagger/models/PortfolioSyncInfoComplete.js +6 -0
  22. package/dist/cjs/swagger/models/PortfolioSyncInfoCompleteSpecifics.d.ts +7 -0
  23. package/dist/cjs/swagger/models/PortfolioSyncInfoCompleteSpecifics.js +5 -0
  24. package/dist/cjs/swagger/models/PortfolioSyncInfoIncomplete.d.ts +7 -0
  25. package/dist/cjs/swagger/models/PortfolioSyncInfoIncomplete.js +6 -0
  26. package/dist/cjs/swagger/models/PortfolioSyncInfoIncompleteSpecifics.d.ts +7 -0
  27. package/dist/cjs/swagger/models/PortfolioSyncInfoIncompleteSpecifics.js +5 -0
  28. package/dist/cjs/swagger/models/TradeWarningReason.d.ts +1 -0
  29. package/dist/cjs/swagger/models/TradeWarningReason.js +1 -0
  30. package/dist/cjs/swagger/models/index.d.ts +2 -0
  31. package/dist/cjs/swagger/models/index.js +2 -0
  32. package/dist/cjs/websocketClient.d.ts +109 -2
  33. package/dist/cjs/websocketClient.js +416 -74
  34. package/dist/cjs/websocketTypes.d.ts +10 -0
  35. package/dist/client.d.ts +247 -46
  36. package/dist/errors.d.ts +60 -0
  37. package/dist/errors.js +44 -0
  38. package/dist/index.d.ts +4 -4
  39. package/dist/index.js +2 -2
  40. package/dist/modelExports.d.ts +2 -0
  41. package/dist/modelExports.js +1 -0
  42. package/dist/swagger/models/PortfolioOrderDetailsSyncInfo.d.ts +60 -0
  43. package/dist/swagger/models/PortfolioOrderDetailsSyncInfo.js +45 -0
  44. package/dist/swagger/models/PortfolioOrderDetailsSyncInfoStatus.d.ts +22 -0
  45. package/dist/swagger/models/PortfolioOrderDetailsSyncInfoStatus.js +29 -0
  46. package/dist/swagger/models/PortfolioSyncInfoComplete.d.ts +7 -0
  47. package/dist/swagger/models/PortfolioSyncInfoComplete.js +6 -0
  48. package/dist/swagger/models/PortfolioSyncInfoCompleteSpecifics.d.ts +7 -0
  49. package/dist/swagger/models/PortfolioSyncInfoCompleteSpecifics.js +5 -0
  50. package/dist/swagger/models/PortfolioSyncInfoIncomplete.d.ts +7 -0
  51. package/dist/swagger/models/PortfolioSyncInfoIncomplete.js +6 -0
  52. package/dist/swagger/models/PortfolioSyncInfoIncompleteSpecifics.d.ts +7 -0
  53. package/dist/swagger/models/PortfolioSyncInfoIncompleteSpecifics.js +5 -0
  54. package/dist/swagger/models/TradeWarningReason.d.ts +1 -0
  55. package/dist/swagger/models/TradeWarningReason.js +1 -0
  56. package/dist/swagger/models/index.d.ts +2 -0
  57. package/dist/swagger/models/index.js +2 -0
  58. package/dist/tsdoc-metadata.json +1 -1
  59. package/dist/websocketClient.d.ts +109 -2
  60. package/dist/websocketClient.js +416 -74
  61. package/dist/websocketTypes.d.ts +10 -0
  62. 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;
@@ -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,6 +51,7 @@ 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
  if (this._wsClient._setAuthorizedApiContext) {
56
57
  this._wsClient._setAuthorizedApiContext(this);
@@ -70,7 +71,7 @@ export class AuthorizedApiContext {
70
71
  }
71
72
  async _initRequestInit() {
72
73
  if (this._isDestroyed) {
73
- throw new Error("AuthorizedApiContext is destroyed");
74
+ throw new BrokerizeAbortError("AuthorizedApiContext is destroyed");
74
75
  }
75
76
  const tok = await this._auth.getToken();
76
77
  const headers = await withAcceptLanguage(this._cfg, {
@@ -434,12 +435,20 @@ export class AuthorizedApiContext {
434
435
  const wrappedClient = {
435
436
  subscribeDecoupledOperation: this._wsClient.subscribeDecoupledOperation.bind(this._wsClient),
436
437
  subscribeInvalidate: this._wsClient.subscribeInvalidate.bind(this._wsClient),
438
+ subscribeConnectionState: this._wsClient.subscribeConnectionState.bind(this._wsClient),
439
+ getConnectionState: this._wsClient.getConnectionState.bind(this._wsClient),
440
+ reconnect: this._wsClient.reconnect.bind(this._wsClient),
437
441
  };
438
442
  return wrappedClient;
439
443
  }
440
444
  destroy() {
441
445
  this._isDestroyed = true;
442
446
  this._abortController.abort();
447
+ if (this._ownsWsClient) {
448
+ /* otherwise its reconnect timer would keep running and keep reconnecting with the
449
+ tokens of a context that is gone. */
450
+ this._wsClient.destroy();
451
+ }
443
452
  }
444
453
  subscribeLogout(callback) {
445
454
  const s = this._logoutSubject.subscribe({
@@ -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
  };
@@ -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;
@@ -88,6 +88,7 @@ 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
  if (this._wsClient._setAuthorizedApiContext) {
93
94
  this._wsClient._setAuthorizedApiContext(this);
@@ -107,7 +108,7 @@ class AuthorizedApiContext {
107
108
  }
108
109
  async _initRequestInit() {
109
110
  if (this._isDestroyed) {
110
- throw new Error("AuthorizedApiContext is destroyed");
111
+ throw new errors_1.BrokerizeAbortError("AuthorizedApiContext is destroyed");
111
112
  }
112
113
  const tok = await this._auth.getToken();
113
114
  const headers = await (0, apiCtx_1.withAcceptLanguage)(this._cfg, {
@@ -471,12 +472,20 @@ class AuthorizedApiContext {
471
472
  const wrappedClient = {
472
473
  subscribeDecoupledOperation: this._wsClient.subscribeDecoupledOperation.bind(this._wsClient),
473
474
  subscribeInvalidate: this._wsClient.subscribeInvalidate.bind(this._wsClient),
475
+ subscribeConnectionState: this._wsClient.subscribeConnectionState.bind(this._wsClient),
476
+ getConnectionState: this._wsClient.getConnectionState.bind(this._wsClient),
477
+ reconnect: this._wsClient.reconnect.bind(this._wsClient),
474
478
  };
475
479
  return wrappedClient;
476
480
  }
477
481
  destroy() {
478
482
  this._isDestroyed = true;
479
483
  this._abortController.abort();
484
+ if (this._ownsWsClient) {
485
+ /* otherwise its reconnect timer would keep running and keep reconnecting with the
486
+ tokens of a context that is gone. */
487
+ this._wsClient.destroy();
488
+ }
480
489
  }
481
490
  subscribeLogout(callback) {
482
491
  const s = this._logoutSubject.subscribe({
@@ -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
+ }
@@ -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;
@@ -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";
@@ -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");
@@ -0,0 +1,60 @@
1
+ /**
2
+ * brokerize
3
+ * The brokerize API allows clients to implement multi-brokerage with a unified interface. For more information, visit brokerize.com
4
+ *
5
+ *
6
+ *
7
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
8
+ * https://openapi-generator.tech
9
+ * Do not edit the class manually.
10
+ */
11
+ import { PortfolioOrderDetailsSyncInfoStatus } from "./PortfolioOrderDetailsSyncInfoStatus";
12
+ /**
13
+ * Whether the *details* of the synced orders are already known — the executions, and with them the
14
+ * execution prices and the fees.
15
+ *
16
+ * This is a second, independent axis next to the sync status: a portfolio counts as `COMPLETE` as
17
+ * soon as every order has been loaded, but some brokers (flatex) report an order's executions only
18
+ * when that single order is fetched individually, which happens during the sync for recent orders
19
+ * only. The remaining ones are fetched in the background afterwards.
20
+ *
21
+ * It matters because every evaluation that reconstructs the past — the trade list, the trade
22
+ * statistics, the value history — is built from executions alone. An order whose details are still
23
+ * missing contributes nothing at all to them.
24
+ *
25
+ * Not reported on every endpoint; absent means "no statement", not "complete".
26
+ * @export
27
+ * @interface PortfolioOrderDetailsSyncInfo
28
+ */
29
+ export interface PortfolioOrderDetailsSyncInfo {
30
+ /**
31
+ * Set while `status` is `PENDING`, absent once it is `COMPLETE`.
32
+ *
33
+ * Evaluations are complete for everything that happened after this point in time; before it,
34
+ * executions may still be missing. It is the timestamp of the newest order whose details are
35
+ * still outstanding — and it is that order, not the oldest one, because the reconstruction is
36
+ * anchored at the current holdings and works backwards: a gap only affects what lies before it.
37
+ *
38
+ * The boundary moves backwards as the background fetch works through the backlog, newest first.
39
+ * It is not a progress bar for the *amount* that is still missing: details fetched out of order
40
+ * (a user opening an old order in the app fetches it right away) close a gap behind the
41
+ * boundary and leave it where it is.
42
+ *
43
+ * Caveat: for an order whose details are missing, the broker has usually only told us when it
44
+ * was *created*, not when it executed — an order that executed considerably later than it was
45
+ * created can therefore sit slightly after this boundary.
46
+ * @type {Date}
47
+ * @memberof PortfolioOrderDetailsSyncInfo
48
+ */
49
+ completeFrom?: Date;
50
+ /**
51
+ *
52
+ * @type {PortfolioOrderDetailsSyncInfoStatus}
53
+ * @memberof PortfolioOrderDetailsSyncInfo
54
+ */
55
+ status: PortfolioOrderDetailsSyncInfoStatus;
56
+ }
57
+ export declare function PortfolioOrderDetailsSyncInfoFromJSON(json: any): PortfolioOrderDetailsSyncInfo;
58
+ export declare function PortfolioOrderDetailsSyncInfoFromJSONTyped(json: any, ignoreDiscriminator: boolean): PortfolioOrderDetailsSyncInfo;
59
+ export declare function PortfolioOrderDetailsSyncInfoToJSONRecursive(value?: PortfolioOrderDetailsSyncInfo | null, ignoreParent?: boolean): any;
60
+ export declare function PortfolioOrderDetailsSyncInfoToJSON(value?: PortfolioOrderDetailsSyncInfo | null): any;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ /* tslint:disable */
3
+ /* eslint-disable */
4
+ /**
5
+ * brokerize
6
+ * The brokerize API allows clients to implement multi-brokerage with a unified interface. For more information, visit brokerize.com
7
+ *
8
+ *
9
+ *
10
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
+ * https://openapi-generator.tech
12
+ * Do not edit the class manually.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.PortfolioOrderDetailsSyncInfoFromJSON = PortfolioOrderDetailsSyncInfoFromJSON;
16
+ exports.PortfolioOrderDetailsSyncInfoFromJSONTyped = PortfolioOrderDetailsSyncInfoFromJSONTyped;
17
+ exports.PortfolioOrderDetailsSyncInfoToJSONRecursive = PortfolioOrderDetailsSyncInfoToJSONRecursive;
18
+ exports.PortfolioOrderDetailsSyncInfoToJSON = PortfolioOrderDetailsSyncInfoToJSON;
19
+ const runtime_1 = require("../runtime");
20
+ const PortfolioOrderDetailsSyncInfoStatus_1 = require("./PortfolioOrderDetailsSyncInfoStatus");
21
+ function PortfolioOrderDetailsSyncInfoFromJSON(json) {
22
+ return PortfolioOrderDetailsSyncInfoFromJSONTyped(json, false);
23
+ }
24
+ function PortfolioOrderDetailsSyncInfoFromJSONTyped(json, ignoreDiscriminator) {
25
+ if (json === undefined || json === null) {
26
+ return json;
27
+ }
28
+ return {
29
+ completeFrom: !(0, runtime_1.exists)(json, "completeFrom")
30
+ ? undefined
31
+ : new Date(json["completeFrom"]),
32
+ status: (0, PortfolioOrderDetailsSyncInfoStatus_1.PortfolioOrderDetailsSyncInfoStatusFromJSON)(json["status"]),
33
+ };
34
+ }
35
+ function PortfolioOrderDetailsSyncInfoToJSONRecursive(value, ignoreParent = false) {
36
+ if (value === undefined) {
37
+ return undefined;
38
+ }
39
+ if (value === null) {
40
+ return null;
41
+ }
42
+ return {
43
+ completeFrom: value.completeFrom === undefined
44
+ ? undefined
45
+ : value.completeFrom.toISOString(),
46
+ status: (0, PortfolioOrderDetailsSyncInfoStatus_1.PortfolioOrderDetailsSyncInfoStatusToJSON)(value.status),
47
+ };
48
+ }
49
+ function PortfolioOrderDetailsSyncInfoToJSON(value) {
50
+ return PortfolioOrderDetailsSyncInfoToJSONRecursive(value, false);
51
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * brokerize
3
+ * The brokerize API allows clients to implement multi-brokerage with a unified interface. For more information, visit brokerize.com
4
+ *
5
+ *
6
+ *
7
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
8
+ * https://openapi-generator.tech
9
+ * Do not edit the class manually.
10
+ */
11
+ /**
12
+ *
13
+ * @export
14
+ */
15
+ export declare const PortfolioOrderDetailsSyncInfoStatus: {
16
+ readonly Complete: "COMPLETE";
17
+ readonly Pending: "PENDING";
18
+ };
19
+ export type PortfolioOrderDetailsSyncInfoStatus = (typeof PortfolioOrderDetailsSyncInfoStatus)[keyof typeof PortfolioOrderDetailsSyncInfoStatus];
20
+ export declare function PortfolioOrderDetailsSyncInfoStatusFromJSON(json: any): PortfolioOrderDetailsSyncInfoStatus;
21
+ export declare function PortfolioOrderDetailsSyncInfoStatusFromJSONTyped(json: any, ignoreDiscriminator: boolean): PortfolioOrderDetailsSyncInfoStatus;
22
+ export declare function PortfolioOrderDetailsSyncInfoStatusToJSON(value?: PortfolioOrderDetailsSyncInfoStatus | null): any;
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ /* tslint:disable */
3
+ /* eslint-disable */
4
+ /**
5
+ * brokerize
6
+ * The brokerize API allows clients to implement multi-brokerage with a unified interface. For more information, visit brokerize.com
7
+ *
8
+ *
9
+ *
10
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
+ * https://openapi-generator.tech
12
+ * Do not edit the class manually.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.PortfolioOrderDetailsSyncInfoStatus = void 0;
16
+ exports.PortfolioOrderDetailsSyncInfoStatusFromJSON = PortfolioOrderDetailsSyncInfoStatusFromJSON;
17
+ exports.PortfolioOrderDetailsSyncInfoStatusFromJSONTyped = PortfolioOrderDetailsSyncInfoStatusFromJSONTyped;
18
+ exports.PortfolioOrderDetailsSyncInfoStatusToJSON = PortfolioOrderDetailsSyncInfoStatusToJSON;
19
+ /**
20
+ *
21
+ * @export
22
+ */
23
+ exports.PortfolioOrderDetailsSyncInfoStatus = {
24
+ Complete: "COMPLETE",
25
+ Pending: "PENDING",
26
+ };
27
+ function PortfolioOrderDetailsSyncInfoStatusFromJSON(json) {
28
+ return PortfolioOrderDetailsSyncInfoStatusFromJSONTyped(json, false);
29
+ }
30
+ function PortfolioOrderDetailsSyncInfoStatusFromJSONTyped(json, ignoreDiscriminator) {
31
+ return json;
32
+ }
33
+ function PortfolioOrderDetailsSyncInfoStatusToJSON(value) {
34
+ return value;
35
+ }