@agg-build/sdk 4.27.2 → 4.27.4

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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_agg_websocket = require("./agg-websocket-DJbIfxKb.js");
2
+ const require_agg_websocket = require("./agg-websocket-DTHMujEm.js");
3
3
  const require_candle_builder = require("./candle-builder-BULYdxB4.js");
4
4
  //#region ../common/src/enums/venue.ts
5
5
  /** Use these constants instead of hardcoding "kalshi" or "polymarket". */
@@ -1164,6 +1164,7 @@ function withTimeout(p, ms) {
1164
1164
  var AggClient = class {
1165
1165
  constructor(options) {
1166
1166
  this.listeners = /* @__PURE__ */ new Set();
1167
+ this.webSocketAuthCleanups = /* @__PURE__ */ new Set();
1167
1168
  this._authStatus = "unauthenticated";
1168
1169
  this.authChannel = null;
1169
1170
  this.pendingRefresh = null;
@@ -1261,6 +1262,7 @@ var AggClient = class {
1261
1262
  const { type } = event.data ?? {};
1262
1263
  if (type === "logout") {
1263
1264
  this.accessToken = void 0;
1265
+ this.accessTokenUserId = void 0;
1264
1266
  this.refreshTokenValue = void 0;
1265
1267
  this.currentUser = void 0;
1266
1268
  this._authStatus = "unauthenticated";
@@ -1276,6 +1278,7 @@ var AggClient = class {
1276
1278
  destroy() {
1277
1279
  this.authChannel?.close();
1278
1280
  this.authChannel = null;
1281
+ for (const cleanup of this.webSocketAuthCleanups) cleanup();
1279
1282
  }
1280
1283
  /**
1281
1284
  * Generic HTTP method with automatic header injection and 401 retry.
@@ -1382,6 +1385,7 @@ var AggClient = class {
1382
1385
  }
1383
1386
  /** Set the user access token (for future user-tier auth). */
1384
1387
  setAccessToken(token) {
1388
+ if (this.accessToken !== token) this.accessTokenUserId = void 0;
1385
1389
  this.accessToken = token;
1386
1390
  this._authStatus = "authenticated";
1387
1391
  this.persistSession();
@@ -1390,6 +1394,7 @@ var AggClient = class {
1390
1394
  /** Set the current auth session tokens and optionally seed the user profile. */
1391
1395
  setSession(session) {
1392
1396
  const wasAuthenticated = this.isAuthenticated;
1397
+ this.accessTokenUserId = session.user?.id ?? (this.accessToken === session.accessToken ? this.accessTokenUserId : void 0);
1393
1398
  this.accessToken = session.accessToken;
1394
1399
  if ("refreshToken" in session) this.refreshTokenValue = session.refreshToken;
1395
1400
  if (session.user !== void 0) this.currentUser = normalizeSessionUser(session.user, this.currentUser);
@@ -1401,6 +1406,7 @@ var AggClient = class {
1401
1406
  /** Clear the user access token, refresh token, and user info. Broadcasts cross-tab logout. */
1402
1407
  clearAccessToken() {
1403
1408
  this.accessToken = void 0;
1409
+ this.accessTokenUserId = void 0;
1404
1410
  this.refreshTokenValue = void 0;
1405
1411
  this.currentUser = void 0;
1406
1412
  this._authStatus = "unauthenticated";
@@ -1587,6 +1593,7 @@ var AggClient = class {
1587
1593
  async getCurrentUser() {
1588
1594
  const user = await this.request("/users/me");
1589
1595
  this.currentUser = user;
1596
+ this.accessTokenUserId = user.id;
1590
1597
  this.persistSession();
1591
1598
  this.notifyListeners();
1592
1599
  return user;
@@ -2330,7 +2337,8 @@ var AggClient = class {
2330
2337
  });
2331
2338
  }
2332
2339
  /**
2333
- * Create an AggWebSocket instance configured with this client's appId and optional auth token.
2340
+ * Create an AggWebSocket instance configured with this client's appId and current auth session.
2341
+ * Session changes update this socket until it or the client is destroyed.
2334
2342
  * Requires `wsUrl` to be set in the client options.
2335
2343
  */
2336
2344
  createWebSocket(callbacks, options) {
@@ -2341,7 +2349,7 @@ var AggClient = class {
2341
2349
  const watchdogHeaders = {};
2342
2350
  if (this._appId) watchdogHeaders["x-app-id"] = this._appId;
2343
2351
  if (this.apiKey) watchdogHeaders["x-app-api-key"] = this.apiKey;
2344
- return createSocket({
2352
+ const socket = createSocket({
2345
2353
  url: url.toString(),
2346
2354
  callbacks,
2347
2355
  initialToken: this.accessToken,
@@ -2352,6 +2360,101 @@ var AggClient = class {
2352
2360
  ...options?.bookWatchdog
2353
2361
  }
2354
2362
  });
2363
+ this.bindWebSocketAuth(socket, callbacks);
2364
+ return socket;
2365
+ }
2366
+ bindWebSocketAuth(socket, callbacks) {
2367
+ let token = this.accessToken;
2368
+ let userId = this.accessTokenUserId;
2369
+ let authenticatedUserId;
2370
+ let awaitingDisconnect = false;
2371
+ let connectRequested = false;
2372
+ let manuallyDisconnected = false;
2373
+ let currentCallbacks = callbacks ?? {};
2374
+ const originalSetCallbacks = socket.setCallbacks;
2375
+ const originalConnect = socket.connect;
2376
+ const originalDisconnect = socket.disconnect;
2377
+ const originalDestroy = socket.destroy;
2378
+ const canReceiveUserEvent = (eventUserId) => !!this.accessToken && !awaitingDisconnect && authenticatedUserId !== void 0 && (this.accessTokenUserId === void 0 || authenticatedUserId === this.accessTokenUserId) && (eventUserId === void 0 || eventUserId === authenticatedUserId);
2379
+ const wrapCallbacks = (handlers) => ({
2380
+ ...handlers,
2381
+ onConnectionStateChange: (connected) => {
2382
+ if (!connected) {
2383
+ authenticatedUserId = void 0;
2384
+ awaitingDisconnect = false;
2385
+ }
2386
+ handlers.onConnectionStateChange?.(connected);
2387
+ },
2388
+ onAuthenticated: (message) => {
2389
+ if (awaitingDisconnect || !this.accessToken || this.accessTokenUserId !== void 0 && this.accessTokenUserId !== message.userId) return;
2390
+ authenticatedUserId = message.userId;
2391
+ handlers.onAuthenticated?.(message);
2392
+ },
2393
+ onOrderEvent: (message) => {
2394
+ if (canReceiveUserEvent(message.userId)) handlers.onOrderEvent?.(message);
2395
+ },
2396
+ onOrderEventReceipt: (message) => {
2397
+ if (canReceiveUserEvent()) handlers.onOrderEventReceipt?.(message);
2398
+ },
2399
+ onOrderSubmitted: (message) => {
2400
+ if (canReceiveUserEvent()) handlers.onOrderSubmitted?.(message);
2401
+ },
2402
+ onBalanceUpdate: (message) => {
2403
+ if (canReceiveUserEvent()) handlers.onBalanceUpdate?.(message);
2404
+ },
2405
+ onRedeemEvent: (message) => {
2406
+ if (canReceiveUserEvent()) handlers.onRedeemEvent?.(message);
2407
+ },
2408
+ onWithdrawalLifecycle: (message) => {
2409
+ if (canReceiveUserEvent(message.userId)) handlers.onWithdrawalLifecycle?.(message);
2410
+ }
2411
+ });
2412
+ socket.setCallbacks = (handlers) => {
2413
+ currentCallbacks = handlers;
2414
+ originalSetCallbacks.call(socket, wrapCallbacks(handlers));
2415
+ };
2416
+ socket.setCallbacks(currentCallbacks);
2417
+ socket.connect = () => {
2418
+ connectRequested = true;
2419
+ manuallyDisconnected = false;
2420
+ originalConnect.call(socket);
2421
+ };
2422
+ socket.disconnect = () => {
2423
+ connectRequested = false;
2424
+ manuallyDisconnected = true;
2425
+ originalDisconnect.call(socket);
2426
+ };
2427
+ const unsubscribe = this.onAuthStateChange(() => {
2428
+ const nextToken = this.accessToken;
2429
+ const nextUserId = this.accessTokenUserId;
2430
+ if (token === nextToken && userId === nextUserId) return;
2431
+ const resetConnection = !nextToken || !!token && (userId !== nextUserId || nextUserId === void 0);
2432
+ token = nextToken;
2433
+ userId = nextUserId;
2434
+ if (resetConnection) {
2435
+ const diagnostics = socket.getDiagnostics();
2436
+ const reconnect = connectRequested || socket.connected || !manuallyDisconnected && (diagnostics.orderbookOutcomeIds.length > 0 || diagnostics.tradeOutcomeIds.length > 0 || diagnostics.arbMarketIds.length > 0 || diagnostics.arbFeedSubscribers > 0);
2437
+ authenticatedUserId = void 0;
2438
+ awaitingDisconnect = true;
2439
+ originalDisconnect.call(socket);
2440
+ socket.authenticate(nextToken ?? "");
2441
+ if (reconnect) originalConnect.call(socket);
2442
+ } else if (nextToken) socket.authenticate(nextToken);
2443
+ });
2444
+ const cleanup = () => {
2445
+ unsubscribe();
2446
+ this.webSocketAuthCleanups.delete(cleanup);
2447
+ socket.setCallbacks = originalSetCallbacks;
2448
+ socket.connect = originalConnect;
2449
+ socket.disconnect = originalDisconnect;
2450
+ socket.destroy = originalDestroy;
2451
+ socket.setCallbacks(currentCallbacks);
2452
+ };
2453
+ this.webSocketAuthCleanups.add(cleanup);
2454
+ socket.destroy = () => {
2455
+ cleanup();
2456
+ originalDestroy.call(socket);
2457
+ };
2355
2458
  }
2356
2459
  /** Execute a previously quoted managed trade. Returns pending order IDs. */
2357
2460
  async executeManaged(params) {
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as loadImmutableHistory, c as orderbookCrc32, i as snapshotToOrderbook, l as projectedOrderbookChecksum, n as applyOrderbookDelta, r as computeChecksum, s as readChartHistoryText, t as AggWebSocket } from "./agg-websocket-CK2iXfti.mjs";
1
+ import { a as loadImmutableHistory, c as orderbookCrc32, i as snapshotToOrderbook, l as projectedOrderbookChecksum, n as applyOrderbookDelta, r as computeChecksum, s as readChartHistoryText, t as AggWebSocket } from "./agg-websocket-BrkWNijv.mjs";
2
2
  import { t as CandleBuilder } from "./candle-builder-BNewIe9K.mjs";
3
3
  //#region ../common/src/enums/venue.ts
4
4
  /** Use these constants instead of hardcoding "kalshi" or "polymarket". */
@@ -1163,6 +1163,7 @@ function withTimeout(p, ms) {
1163
1163
  var AggClient = class {
1164
1164
  constructor(options) {
1165
1165
  this.listeners = /* @__PURE__ */ new Set();
1166
+ this.webSocketAuthCleanups = /* @__PURE__ */ new Set();
1166
1167
  this._authStatus = "unauthenticated";
1167
1168
  this.authChannel = null;
1168
1169
  this.pendingRefresh = null;
@@ -1260,6 +1261,7 @@ var AggClient = class {
1260
1261
  const { type } = event.data ?? {};
1261
1262
  if (type === "logout") {
1262
1263
  this.accessToken = void 0;
1264
+ this.accessTokenUserId = void 0;
1263
1265
  this.refreshTokenValue = void 0;
1264
1266
  this.currentUser = void 0;
1265
1267
  this._authStatus = "unauthenticated";
@@ -1275,6 +1277,7 @@ var AggClient = class {
1275
1277
  destroy() {
1276
1278
  this.authChannel?.close();
1277
1279
  this.authChannel = null;
1280
+ for (const cleanup of this.webSocketAuthCleanups) cleanup();
1278
1281
  }
1279
1282
  /**
1280
1283
  * Generic HTTP method with automatic header injection and 401 retry.
@@ -1381,6 +1384,7 @@ var AggClient = class {
1381
1384
  }
1382
1385
  /** Set the user access token (for future user-tier auth). */
1383
1386
  setAccessToken(token) {
1387
+ if (this.accessToken !== token) this.accessTokenUserId = void 0;
1384
1388
  this.accessToken = token;
1385
1389
  this._authStatus = "authenticated";
1386
1390
  this.persistSession();
@@ -1389,6 +1393,7 @@ var AggClient = class {
1389
1393
  /** Set the current auth session tokens and optionally seed the user profile. */
1390
1394
  setSession(session) {
1391
1395
  const wasAuthenticated = this.isAuthenticated;
1396
+ this.accessTokenUserId = session.user?.id ?? (this.accessToken === session.accessToken ? this.accessTokenUserId : void 0);
1392
1397
  this.accessToken = session.accessToken;
1393
1398
  if ("refreshToken" in session) this.refreshTokenValue = session.refreshToken;
1394
1399
  if (session.user !== void 0) this.currentUser = normalizeSessionUser(session.user, this.currentUser);
@@ -1400,6 +1405,7 @@ var AggClient = class {
1400
1405
  /** Clear the user access token, refresh token, and user info. Broadcasts cross-tab logout. */
1401
1406
  clearAccessToken() {
1402
1407
  this.accessToken = void 0;
1408
+ this.accessTokenUserId = void 0;
1403
1409
  this.refreshTokenValue = void 0;
1404
1410
  this.currentUser = void 0;
1405
1411
  this._authStatus = "unauthenticated";
@@ -1586,6 +1592,7 @@ var AggClient = class {
1586
1592
  async getCurrentUser() {
1587
1593
  const user = await this.request("/users/me");
1588
1594
  this.currentUser = user;
1595
+ this.accessTokenUserId = user.id;
1589
1596
  this.persistSession();
1590
1597
  this.notifyListeners();
1591
1598
  return user;
@@ -2329,7 +2336,8 @@ var AggClient = class {
2329
2336
  });
2330
2337
  }
2331
2338
  /**
2332
- * Create an AggWebSocket instance configured with this client's appId and optional auth token.
2339
+ * Create an AggWebSocket instance configured with this client's appId and current auth session.
2340
+ * Session changes update this socket until it or the client is destroyed.
2333
2341
  * Requires `wsUrl` to be set in the client options.
2334
2342
  */
2335
2343
  createWebSocket(callbacks, options) {
@@ -2340,7 +2348,7 @@ var AggClient = class {
2340
2348
  const watchdogHeaders = {};
2341
2349
  if (this._appId) watchdogHeaders["x-app-id"] = this._appId;
2342
2350
  if (this.apiKey) watchdogHeaders["x-app-api-key"] = this.apiKey;
2343
- return createSocket({
2351
+ const socket = createSocket({
2344
2352
  url: url.toString(),
2345
2353
  callbacks,
2346
2354
  initialToken: this.accessToken,
@@ -2351,6 +2359,101 @@ var AggClient = class {
2351
2359
  ...options?.bookWatchdog
2352
2360
  }
2353
2361
  });
2362
+ this.bindWebSocketAuth(socket, callbacks);
2363
+ return socket;
2364
+ }
2365
+ bindWebSocketAuth(socket, callbacks) {
2366
+ let token = this.accessToken;
2367
+ let userId = this.accessTokenUserId;
2368
+ let authenticatedUserId;
2369
+ let awaitingDisconnect = false;
2370
+ let connectRequested = false;
2371
+ let manuallyDisconnected = false;
2372
+ let currentCallbacks = callbacks ?? {};
2373
+ const originalSetCallbacks = socket.setCallbacks;
2374
+ const originalConnect = socket.connect;
2375
+ const originalDisconnect = socket.disconnect;
2376
+ const originalDestroy = socket.destroy;
2377
+ const canReceiveUserEvent = (eventUserId) => !!this.accessToken && !awaitingDisconnect && authenticatedUserId !== void 0 && (this.accessTokenUserId === void 0 || authenticatedUserId === this.accessTokenUserId) && (eventUserId === void 0 || eventUserId === authenticatedUserId);
2378
+ const wrapCallbacks = (handlers) => ({
2379
+ ...handlers,
2380
+ onConnectionStateChange: (connected) => {
2381
+ if (!connected) {
2382
+ authenticatedUserId = void 0;
2383
+ awaitingDisconnect = false;
2384
+ }
2385
+ handlers.onConnectionStateChange?.(connected);
2386
+ },
2387
+ onAuthenticated: (message) => {
2388
+ if (awaitingDisconnect || !this.accessToken || this.accessTokenUserId !== void 0 && this.accessTokenUserId !== message.userId) return;
2389
+ authenticatedUserId = message.userId;
2390
+ handlers.onAuthenticated?.(message);
2391
+ },
2392
+ onOrderEvent: (message) => {
2393
+ if (canReceiveUserEvent(message.userId)) handlers.onOrderEvent?.(message);
2394
+ },
2395
+ onOrderEventReceipt: (message) => {
2396
+ if (canReceiveUserEvent()) handlers.onOrderEventReceipt?.(message);
2397
+ },
2398
+ onOrderSubmitted: (message) => {
2399
+ if (canReceiveUserEvent()) handlers.onOrderSubmitted?.(message);
2400
+ },
2401
+ onBalanceUpdate: (message) => {
2402
+ if (canReceiveUserEvent()) handlers.onBalanceUpdate?.(message);
2403
+ },
2404
+ onRedeemEvent: (message) => {
2405
+ if (canReceiveUserEvent()) handlers.onRedeemEvent?.(message);
2406
+ },
2407
+ onWithdrawalLifecycle: (message) => {
2408
+ if (canReceiveUserEvent(message.userId)) handlers.onWithdrawalLifecycle?.(message);
2409
+ }
2410
+ });
2411
+ socket.setCallbacks = (handlers) => {
2412
+ currentCallbacks = handlers;
2413
+ originalSetCallbacks.call(socket, wrapCallbacks(handlers));
2414
+ };
2415
+ socket.setCallbacks(currentCallbacks);
2416
+ socket.connect = () => {
2417
+ connectRequested = true;
2418
+ manuallyDisconnected = false;
2419
+ originalConnect.call(socket);
2420
+ };
2421
+ socket.disconnect = () => {
2422
+ connectRequested = false;
2423
+ manuallyDisconnected = true;
2424
+ originalDisconnect.call(socket);
2425
+ };
2426
+ const unsubscribe = this.onAuthStateChange(() => {
2427
+ const nextToken = this.accessToken;
2428
+ const nextUserId = this.accessTokenUserId;
2429
+ if (token === nextToken && userId === nextUserId) return;
2430
+ const resetConnection = !nextToken || !!token && (userId !== nextUserId || nextUserId === void 0);
2431
+ token = nextToken;
2432
+ userId = nextUserId;
2433
+ if (resetConnection) {
2434
+ const diagnostics = socket.getDiagnostics();
2435
+ const reconnect = connectRequested || socket.connected || !manuallyDisconnected && (diagnostics.orderbookOutcomeIds.length > 0 || diagnostics.tradeOutcomeIds.length > 0 || diagnostics.arbMarketIds.length > 0 || diagnostics.arbFeedSubscribers > 0);
2436
+ authenticatedUserId = void 0;
2437
+ awaitingDisconnect = true;
2438
+ originalDisconnect.call(socket);
2439
+ socket.authenticate(nextToken ?? "");
2440
+ if (reconnect) originalConnect.call(socket);
2441
+ } else if (nextToken) socket.authenticate(nextToken);
2442
+ });
2443
+ const cleanup = () => {
2444
+ unsubscribe();
2445
+ this.webSocketAuthCleanups.delete(cleanup);
2446
+ socket.setCallbacks = originalSetCallbacks;
2447
+ socket.connect = originalConnect;
2448
+ socket.disconnect = originalDisconnect;
2449
+ socket.destroy = originalDestroy;
2450
+ socket.setCallbacks(currentCallbacks);
2451
+ };
2452
+ this.webSocketAuthCleanups.add(cleanup);
2453
+ socket.destroy = () => {
2454
+ cleanup();
2455
+ originalDestroy.call(socket);
2456
+ };
2354
2457
  }
2355
2458
  /** Execute a previously quoted managed trade. Returns pending order IDs. */
2356
2459
  async executeManaged(params) {