nsekit 0.3.8 → 0.3.10

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 (40) hide show
  1. package/dist/brokers/dhan/DhanBroker.d.ts +2 -0
  2. package/dist/brokers/dhan/DhanBroker.d.ts.map +1 -1
  3. package/dist/brokers/dhan/dhan-auth.d.ts +9 -4
  4. package/dist/brokers/dhan/dhan-auth.d.ts.map +1 -1
  5. package/dist/brokers/dhan/dhan-instruments.d.ts +4 -0
  6. package/dist/brokers/dhan/dhan-instruments.d.ts.map +1 -1
  7. package/dist/brokers/dhan/dhan-socket.d.ts +15 -3
  8. package/dist/brokers/dhan/dhan-socket.d.ts.map +1 -1
  9. package/dist/brokers/finvasia/FinvasiaBroker.d.ts +2 -0
  10. package/dist/brokers/finvasia/FinvasiaBroker.d.ts.map +1 -1
  11. package/dist/brokers/finvasia/finvasia-auth.d.ts +11 -2
  12. package/dist/brokers/finvasia/finvasia-auth.d.ts.map +1 -1
  13. package/dist/brokers/finvasia/finvasia-instruments.d.ts +5 -0
  14. package/dist/brokers/finvasia/finvasia-instruments.d.ts.map +1 -1
  15. package/dist/brokers/finvasia/finvasia-socket.d.ts +2 -1
  16. package/dist/brokers/finvasia/finvasia-socket.d.ts.map +1 -1
  17. package/dist/brokers/fivepaisa/FivePaisaBroker.d.ts +2 -0
  18. package/dist/brokers/fivepaisa/FivePaisaBroker.d.ts.map +1 -1
  19. package/dist/brokers/fivepaisa/fivepaisa-auth.d.ts +10 -3
  20. package/dist/brokers/fivepaisa/fivepaisa-auth.d.ts.map +1 -1
  21. package/dist/brokers/fivepaisa/fivepaisa-instruments.d.ts +4 -0
  22. package/dist/brokers/fivepaisa/fivepaisa-instruments.d.ts.map +1 -1
  23. package/dist/brokers/fivepaisa/fivepaisa-socket.d.ts +2 -1
  24. package/dist/brokers/fivepaisa/fivepaisa-socket.d.ts.map +1 -1
  25. package/dist/brokers/paper/PaperBroker.d.ts +5 -0
  26. package/dist/brokers/paper/PaperBroker.d.ts.map +1 -1
  27. package/dist/brokers/zerodha/ZerodhaBroker.d.ts +2 -0
  28. package/dist/brokers/zerodha/ZerodhaBroker.d.ts.map +1 -1
  29. package/dist/brokers/zerodha/zerodha-auth.d.ts +8 -3
  30. package/dist/brokers/zerodha/zerodha-auth.d.ts.map +1 -1
  31. package/dist/brokers/zerodha/zerodha-instruments.d.ts +4 -0
  32. package/dist/brokers/zerodha/zerodha-instruments.d.ts.map +1 -1
  33. package/dist/index.d.ts +9 -2
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +145 -98
  36. package/dist/instruments/instrument-master.d.ts +15 -2
  37. package/dist/instruments/instrument-master.d.ts.map +1 -1
  38. package/dist/shared/egress-ip.d.ts +25 -0
  39. package/dist/shared/egress-ip.d.ts.map +1 -0
  40. package/package.json +7 -6
package/dist/index.js CHANGED
@@ -17284,7 +17284,7 @@ var require_utils = __commonJS((exports, module) => {
17284
17284
  var hexTable = function() {
17285
17285
  var array = [];
17286
17286
  for (var i = 0;i < 256; ++i) {
17287
- array[array.length] = "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase();
17287
+ array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
17288
17288
  }
17289
17289
  return array;
17290
17290
  }();
@@ -17296,7 +17296,7 @@ var require_utils = __commonJS((exports, module) => {
17296
17296
  var compacted = [];
17297
17297
  for (var j = 0;j < obj.length; ++j) {
17298
17298
  if (typeof obj[j] !== "undefined") {
17299
- compacted[compacted.length] = obj[j];
17299
+ compacted.push(obj[j]);
17300
17300
  }
17301
17301
  }
17302
17302
  item.obj[item.prop] = compacted;
@@ -17318,11 +17318,7 @@ var require_utils = __commonJS((exports, module) => {
17318
17318
  }
17319
17319
  if (typeof source !== "object" && typeof source !== "function") {
17320
17320
  if (isArray(target)) {
17321
- var nextIndex = target.length;
17322
- if (options && typeof options.arrayLimit === "number" && nextIndex > options.arrayLimit) {
17323
- return markOverflow(arrayToObject(target.concat(source), options), nextIndex);
17324
- }
17325
- target[nextIndex] = source;
17321
+ target.push(source);
17326
17322
  } else if (target && typeof target === "object") {
17327
17323
  if (isOverflow(target)) {
17328
17324
  var newIndex = getMaxIndex(target) + 1;
@@ -17346,11 +17342,7 @@ var require_utils = __commonJS((exports, module) => {
17346
17342
  }
17347
17343
  return markOverflow(result, getMaxIndex(source) + 1);
17348
17344
  }
17349
- var combined = [target].concat(source);
17350
- if (options && typeof options.arrayLimit === "number" && combined.length > options.arrayLimit) {
17351
- return markOverflow(arrayToObject(combined, options), combined.length - 1);
17352
- }
17353
- return combined;
17345
+ return [target].concat(source);
17354
17346
  }
17355
17347
  var mergeTarget = target;
17356
17348
  if (isArray(target) && !isArray(source)) {
@@ -17363,7 +17355,7 @@ var require_utils = __commonJS((exports, module) => {
17363
17355
  if (targetItem && typeof targetItem === "object" && item && typeof item === "object") {
17364
17356
  target[i] = merge2(targetItem, item, options);
17365
17357
  } else {
17366
- target[target.length] = item;
17358
+ target.push(item);
17367
17359
  }
17368
17360
  } else {
17369
17361
  target[i] = item;
@@ -17378,15 +17370,6 @@ var require_utils = __commonJS((exports, module) => {
17378
17370
  } else {
17379
17371
  acc[key] = value;
17380
17372
  }
17381
- if (isOverflow(source) && !isOverflow(acc)) {
17382
- markOverflow(acc, getMaxIndex(source));
17383
- }
17384
- if (isOverflow(acc)) {
17385
- var keyNum = parseInt(key, 10);
17386
- if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) {
17387
- setMaxIndex(acc, keyNum);
17388
- }
17389
- }
17390
17373
  return acc;
17391
17374
  }, mergeTarget);
17392
17375
  };
@@ -17464,8 +17447,8 @@ var require_utils = __commonJS((exports, module) => {
17464
17447
  var key = keys[j];
17465
17448
  var val = obj[key];
17466
17449
  if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) {
17467
- queue[queue.length] = { obj, prop: key };
17468
- refs[refs.length] = val;
17450
+ queue.push({ obj, prop: key });
17451
+ refs.push(val);
17469
17452
  }
17470
17453
  }
17471
17454
  }
@@ -17498,7 +17481,7 @@ var require_utils = __commonJS((exports, module) => {
17498
17481
  if (isArray(val)) {
17499
17482
  var mapped = [];
17500
17483
  for (var i = 0;i < val.length; i += 1) {
17501
- mapped[mapped.length] = fn(val[i]);
17484
+ mapped.push(fn(val[i]));
17502
17485
  }
17503
17486
  return mapped;
17504
17487
  }
@@ -17514,7 +17497,6 @@ var require_utils = __commonJS((exports, module) => {
17514
17497
  isBuffer,
17515
17498
  isOverflow,
17516
17499
  isRegExp,
17517
- markOverflow,
17518
17500
  maybeMap,
17519
17501
  merge
17520
17502
  };
@@ -17856,12 +17838,6 @@ var require_parse = __commonJS((exports, module) => {
17856
17838
  if (part.indexOf("[]=") > -1) {
17857
17839
  val = isArray(val) ? [val] : val;
17858
17840
  }
17859
- if (options.comma && isArray(val) && val.length > options.arrayLimit) {
17860
- if (options.throwOnLimitExceeded) {
17861
- throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
17862
- }
17863
- val = utils.combine([], val, options.arrayLimit, options.plainObjects);
17864
- }
17865
17841
  if (key !== null) {
17866
17842
  var existing = has.call(obj, key);
17867
17843
  if (existing && options.duplicates === "combine") {
@@ -17894,17 +17870,11 @@ var require_parse = __commonJS((exports, module) => {
17894
17870
  var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root;
17895
17871
  var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, ".") : cleanRoot;
17896
17872
  var index = parseInt(decodedRoot, 10);
17897
- var isValidArrayIndex = !isNaN(index) && root !== decodedRoot && String(index) === decodedRoot && index >= 0 && options.parseArrays;
17898
17873
  if (!options.parseArrays && decodedRoot === "") {
17899
17874
  obj = { 0: leaf };
17900
- } else if (isValidArrayIndex && index < options.arrayLimit) {
17875
+ } else if (!isNaN(index) && root !== decodedRoot && String(index) === decodedRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit)) {
17901
17876
  obj = [];
17902
17877
  obj[index] = leaf;
17903
- } else if (isValidArrayIndex && options.throwOnLimitExceeded) {
17904
- throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
17905
- } else if (isValidArrayIndex) {
17906
- obj[index] = leaf;
17907
- utils.markOverflow(obj, index);
17908
17878
  } else if (decodedRoot !== "__proto__") {
17909
17879
  obj[decodedRoot] = leaf;
17910
17880
  }
@@ -17934,7 +17904,7 @@ var require_parse = __commonJS((exports, module) => {
17934
17904
  return;
17935
17905
  }
17936
17906
  }
17937
- keys[keys.length] = parent;
17907
+ keys.push(parent);
17938
17908
  }
17939
17909
  var i = 0;
17940
17910
  while ((segment = child.exec(key)) !== null && i < options.depth) {
@@ -17945,13 +17915,13 @@ var require_parse = __commonJS((exports, module) => {
17945
17915
  return;
17946
17916
  }
17947
17917
  }
17948
- keys[keys.length] = segment[1];
17918
+ keys.push(segment[1]);
17949
17919
  }
17950
17920
  if (segment) {
17951
17921
  if (options.strictDepth === true) {
17952
17922
  throw new RangeError("Input depth exceeded depth option of " + options.depth + " and strictDepth is true");
17953
17923
  }
17954
- keys[keys.length] = "[" + key.slice(segment.index) + "]";
17924
+ keys.push("[" + key.slice(segment.index) + "]");
17955
17925
  }
17956
17926
  return keys;
17957
17927
  };
@@ -20155,7 +20125,7 @@ var CANDLE_INTERVAL_TO_KITE = {
20155
20125
 
20156
20126
  // src/brokers/zerodha/zerodha-auth.ts
20157
20127
  import crypto from "crypto";
20158
- async function exchangeToken(requestToken, apiKey, apiSecret) {
20128
+ async function exchangeToken(requestToken, apiKey, apiSecret, opts) {
20159
20129
  try {
20160
20130
  const checksum = crypto.createHash("sha256").update(apiKey + requestToken + apiSecret).digest("hex");
20161
20131
  const response = await fetch("https://api.kite.trade/session/token", {
@@ -20165,7 +20135,8 @@ async function exchangeToken(requestToken, apiKey, apiSecret) {
20165
20135
  api_key: apiKey,
20166
20136
  request_token: requestToken,
20167
20137
  checksum
20168
- })
20138
+ }),
20139
+ dispatcher: opts?.dispatcher
20169
20140
  });
20170
20141
  if (!response.ok) {
20171
20142
  const body = await response.text();
@@ -20187,7 +20158,7 @@ async function exchangeToken(requestToken, apiKey, apiSecret) {
20187
20158
  return Err(err instanceof Error ? err : new Error(String(err)));
20188
20159
  }
20189
20160
  }
20190
- async function authenticate(creds) {
20161
+ async function authenticate(creds, opts) {
20191
20162
  const { apiKey, apiSecret, accessToken: requestToken } = creds;
20192
20163
  if (!apiKey)
20193
20164
  return Err(new Error("Missing apiKey in credentials"));
@@ -20195,9 +20166,9 @@ async function authenticate(creds) {
20195
20166
  return Err(new Error("Missing apiSecret in credentials"));
20196
20167
  if (!requestToken)
20197
20168
  return Err(new Error("Missing accessToken (request_token) in credentials"));
20198
- return exchangeToken(requestToken, apiKey, apiSecret);
20169
+ return exchangeToken(requestToken, apiKey, apiSecret, opts);
20199
20170
  }
20200
- async function refreshSession(_session) {
20171
+ async function refreshSession(_session, _opts) {
20201
20172
  return Err(new Error("Zerodha does not support token refresh. Re-authenticate with a new request_token."));
20202
20173
  }
20203
20174
  function isSessionValid(session) {
@@ -20581,8 +20552,12 @@ class ZerodhaInstruments {
20581
20552
  rawFileCache: true,
20582
20553
  rawFilePath: "data/instruments/zerodha-instruments.csv"
20583
20554
  };
20555
+ dispatcher;
20556
+ setDispatcher(dispatcher) {
20557
+ this.dispatcher = dispatcher;
20558
+ }
20584
20559
  async* streamDump() {
20585
- const response = await fetch(KITE_INSTRUMENTS_URL);
20560
+ const response = await fetch(KITE_INSTRUMENTS_URL, { dispatcher: this.dispatcher });
20586
20561
  if (!response.ok) {
20587
20562
  throw new Error(`Failed to fetch Kite instruments: ${response.status}`);
20588
20563
  }
@@ -20655,6 +20630,19 @@ class ZerodhaInstruments {
20655
20630
  }
20656
20631
  }
20657
20632
 
20633
+ // src/shared/egress-ip.ts
20634
+ import { Agent, Pool } from "undici";
20635
+ function egressDispatcher(egressIp) {
20636
+ if (!egressIp)
20637
+ return;
20638
+ return new Agent({
20639
+ factory: (origin, opts) => new Pool(origin, { ...opts, localAddress: egressIp })
20640
+ });
20641
+ }
20642
+ function wsEgressOptions(egressIp) {
20643
+ return egressIp ? { localAddress: egressIp } : {};
20644
+ }
20645
+
20658
20646
  // src/brokers/zerodha/ZerodhaBroker.ts
20659
20647
  class ZerodhaBroker {
20660
20648
  id = "zerodha";
@@ -20674,13 +20662,18 @@ class ZerodhaBroker {
20674
20662
  apiKey = "";
20675
20663
  KiteConnect = null;
20676
20664
  _iMaster;
20665
+ egressIp;
20666
+ dispatcher;
20677
20667
  constructor(options) {
20678
20668
  this.instruments = new ZerodhaInstruments;
20679
20669
  this._iMaster = new InstrumentMaster(options);
20670
+ this.egressIp = options?.egressIp;
20671
+ this.dispatcher = egressDispatcher(options?.egressIp);
20672
+ this.instruments.setDispatcher(this.dispatcher);
20680
20673
  }
20681
20674
  async authenticate(creds) {
20682
20675
  this.apiKey = creds.apiKey;
20683
- const result = await authenticate(creds);
20676
+ const result = await authenticate(creds, { dispatcher: this.dispatcher });
20684
20677
  if (!result.ok)
20685
20678
  return result;
20686
20679
  this.session = result.value;
@@ -20689,7 +20682,7 @@ class ZerodhaBroker {
20689
20682
  return result;
20690
20683
  }
20691
20684
  async refreshSession(session) {
20692
- return refreshSession(session);
20685
+ return refreshSession(session, { dispatcher: this.dispatcher });
20693
20686
  }
20694
20687
  isSessionValid() {
20695
20688
  return isSessionValid(this.session);
@@ -21172,7 +21165,7 @@ function generateTOTP(secret) {
21172
21165
  const code = (hmac[offset] & 127) << 24 | (hmac[offset + 1] & 255) << 16 | (hmac[offset + 2] & 255) << 8 | hmac[offset + 3] & 255;
21173
21166
  return String(code % 1e6).padStart(6, "0");
21174
21167
  }
21175
- async function authenticate2(creds) {
21168
+ async function authenticate2(creds, opts) {
21176
21169
  const { userId, password, totpSecret, apiKey, vendorCode } = creds;
21177
21170
  if (!userId)
21178
21171
  return Err(new Error("Missing userId in credentials"));
@@ -21207,7 +21200,8 @@ async function authenticate2(creds) {
21207
21200
  const response = await fetch(`${host}/QuickAuth`, {
21208
21201
  method: "POST",
21209
21202
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
21210
- body: `jData=${jData}`
21203
+ body: `jData=${jData}`,
21204
+ dispatcher: opts?.dispatcher
21211
21205
  });
21212
21206
  text = await response.text();
21213
21207
  try {
@@ -21246,7 +21240,7 @@ function getOAuthURL(clientId) {
21246
21240
  const uid = clientId.endsWith("_U") ? clientId.slice(0, -2) : clientId;
21247
21241
  return `${SHOONYA_OAUTH_BASE}?api_key=${encodeURIComponent(clientId)}&route_to=${encodeURIComponent(uid)}`;
21248
21242
  }
21249
- async function exchangeAuthCode(authCode, secretCode, clientId, uid) {
21243
+ async function exchangeAuthCode(authCode, secretCode, clientId, uid, opts) {
21250
21244
  if (!authCode)
21251
21245
  return Err(new Error("Missing authCode"));
21252
21246
  if (!secretCode)
@@ -21265,7 +21259,8 @@ async function exchangeAuthCode(authCode, secretCode, clientId, uid) {
21265
21259
  const response = await fetch(`${SHOONYA_API_BASE3}/GenAcsTok`, {
21266
21260
  method: "POST",
21267
21261
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
21268
- body: `jData=${jData}`
21262
+ body: `jData=${jData}`,
21263
+ dispatcher: opts?.dispatcher
21269
21264
  });
21270
21265
  const text = await response.text();
21271
21266
  let json;
@@ -21557,11 +21552,13 @@ class FinvasiaSocket {
21557
21552
  maxReconnects = 5;
21558
21553
  reconnectTimer = null;
21559
21554
  onAuthFailed;
21560
- constructor(userId, accessToken, onAuthFailed, authMethod = "totp") {
21555
+ egressIp;
21556
+ constructor(userId, accessToken, onAuthFailed, authMethod = "totp", egressIp) {
21561
21557
  this.userId = userId;
21562
21558
  this.accessToken = accessToken;
21563
21559
  this.authMethod = authMethod;
21564
21560
  this.onAuthFailed = onAuthFailed;
21561
+ this.egressIp = egressIp;
21565
21562
  }
21566
21563
  connect() {
21567
21564
  if (this.state === "CONNECTED" || this.state === "CONNECTING")
@@ -21569,7 +21566,7 @@ class FinvasiaSocket {
21569
21566
  this.state = "CONNECTING";
21570
21567
  const wsUrl = this.authMethod === "oauth" ? SHOONYA_WS_OAUTH_URL3 : SHOONYA_WS_URL3;
21571
21568
  try {
21572
- this.ws = new WS(wsUrl);
21569
+ this.ws = new WS(wsUrl, wsEgressOptions(this.egressIp));
21573
21570
  } catch {
21574
21571
  this.state = "DISCONNECTED";
21575
21572
  return;
@@ -21876,15 +21873,19 @@ class FinvasiaInstruments {
21876
21873
  };
21877
21874
  accessToken = "";
21878
21875
  userId = "";
21876
+ dispatcher;
21879
21877
  setCredentials(userId, accessToken) {
21880
21878
  this.userId = userId;
21881
21879
  this.accessToken = accessToken;
21882
21880
  }
21881
+ setDispatcher(dispatcher) {
21882
+ this.dispatcher = dispatcher;
21883
+ }
21883
21884
  async* streamDump() {
21884
21885
  for (const [exchange, filename] of Object.entries(SHOONYA_INSTRUMENT_FILES)) {
21885
21886
  const url = `${SHOONYA_INSTRUMENTS_BASE}${filename}`;
21886
21887
  try {
21887
- const response = await fetch(url);
21888
+ const response = await fetch(url, { dispatcher: this.dispatcher });
21888
21889
  if (!response.ok)
21889
21890
  continue;
21890
21891
  const text = extractTextFromZip(await response.arrayBuffer());
@@ -21943,7 +21944,8 @@ class FinvasiaInstruments {
21943
21944
  const response = await fetch(`${SHOONYA_API_BASE3}/SearchScrip`, {
21944
21945
  method: "POST",
21945
21946
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
21946
- body: `jData=${payload}&jKey=${this.accessToken}`
21947
+ body: `jData=${payload}&jKey=${this.accessToken}`,
21948
+ dispatcher: this.dispatcher
21947
21949
  });
21948
21950
  if (!response.ok) {
21949
21951
  return Err(new Error(`Shoonya search failed (${response.status})`));
@@ -22017,10 +22019,15 @@ class FinvasiaBroker {
22017
22019
  credentials = null;
22018
22020
  instrumentsImpl;
22019
22021
  _iMaster;
22022
+ egressIp;
22023
+ dispatcher;
22020
22024
  constructor(options) {
22021
22025
  this.instrumentsImpl = new FinvasiaInstruments;
22022
22026
  this.instruments = this.instrumentsImpl;
22023
22027
  this._iMaster = new InstrumentMaster(options);
22028
+ this.egressIp = options?.egressIp;
22029
+ this.dispatcher = egressDispatcher(options?.egressIp);
22030
+ this.instrumentsImpl.setDispatcher(this.dispatcher);
22024
22031
  }
22025
22032
  async authenticate(creds) {
22026
22033
  if (creds.accessToken && creds.userId) {
@@ -22034,7 +22041,7 @@ class FinvasiaBroker {
22034
22041
  if (!creds.clientId || !creds.secretCode || !creds.userId) {
22035
22042
  return Err(new Error("Finvasia OAuth: authCode requires clientId, secretCode, and userId"));
22036
22043
  }
22037
- const result2 = await exchangeAuthCode(creds.authCode, creds.secretCode, creds.clientId, creds.userId);
22044
+ const result2 = await exchangeAuthCode(creds.authCode, creds.secretCode, creds.clientId, creds.userId, { dispatcher: this.dispatcher });
22038
22045
  if (!result2.ok)
22039
22046
  return result2;
22040
22047
  this.credentials = creds;
@@ -22042,7 +22049,7 @@ class FinvasiaBroker {
22042
22049
  this.instrumentsImpl.setCredentials(this.session.userId, this.session.accessToken);
22043
22050
  return result2;
22044
22051
  }
22045
- const result = await authenticate2(creds);
22052
+ const result = await authenticate2(creds, { dispatcher: this.dispatcher });
22046
22053
  if (!result.ok)
22047
22054
  return result;
22048
22055
  this.credentials = creds;
@@ -22566,7 +22573,8 @@ class FinvasiaBroker {
22566
22573
  const response = await fetch(`${SHOONYA_API_BASE3}/${endpoint}`, {
22567
22574
  method: "POST",
22568
22575
  headers,
22569
- body
22576
+ body,
22577
+ dispatcher: this.dispatcher
22570
22578
  });
22571
22579
  const text = await response.text();
22572
22580
  let parsed;
@@ -22596,7 +22604,7 @@ class FinvasiaBroker {
22596
22604
  const authMethod = this.session.metadata?.authMethod === "oauth" ? "oauth" : "totp";
22597
22605
  this.socket = new FinvasiaSocket(this.session.userId, this.session.accessToken, () => {
22598
22606
  this.handleSocketAuthFailed();
22599
- }, authMethod);
22607
+ }, authMethod, this.egressIp);
22600
22608
  this.socket.connect();
22601
22609
  }
22602
22610
  handleSocketAuthFailed() {
@@ -22725,7 +22733,7 @@ var DHAN_WS_URL3 = active2.DHAN_WS_URL;
22725
22733
  var DHAN_INSTRUMENTS_URL3 = active2.DHAN_INSTRUMENTS_URL;
22726
22734
 
22727
22735
  // src/brokers/dhan/dhan-auth.ts
22728
- async function authenticate3(creds) {
22736
+ async function authenticate3(creds, opts) {
22729
22737
  const { apiKey: accessToken, userId: clientId } = creds;
22730
22738
  if (!accessToken)
22731
22739
  return Err(new Error("Missing apiKey (access_token) in credentials"));
@@ -22737,7 +22745,8 @@ async function authenticate3(creds) {
22737
22745
  "Content-Type": "application/json",
22738
22746
  "access-token": accessToken,
22739
22747
  "client-id": clientId
22740
- }
22748
+ },
22749
+ dispatcher: opts?.dispatcher
22741
22750
  });
22742
22751
  if (!response.ok) {
22743
22752
  const body = await response.text();
@@ -22759,7 +22768,7 @@ async function authenticate3(creds) {
22759
22768
  return Err(err instanceof Error ? err : new Error(String(err)));
22760
22769
  }
22761
22770
  }
22762
- async function generateConsent(creds) {
22771
+ async function generateConsent(creds, opts) {
22763
22772
  const { apiKey: appId, apiSecret: appSecret, userId: clientId } = creds;
22764
22773
  if (!appId)
22765
22774
  return Err(new Error("Missing apiKey (App ID) in credentials"));
@@ -22775,7 +22784,8 @@ async function generateConsent(creds) {
22775
22784
  app_id: appId,
22776
22785
  app_secret: appSecret
22777
22786
  },
22778
- body: JSON.stringify({})
22787
+ body: JSON.stringify({}),
22788
+ dispatcher: opts?.dispatcher
22779
22789
  });
22780
22790
  if (!response.ok) {
22781
22791
  const body = await response.text();
@@ -22791,7 +22801,7 @@ async function generateConsent(creds) {
22791
22801
  return Err(err instanceof Error ? err : new Error(String(err)));
22792
22802
  }
22793
22803
  }
22794
- async function consumeConsent(creds, tokenId) {
22804
+ async function consumeConsent(creds, tokenId, opts) {
22795
22805
  const { apiKey: appId, apiSecret: appSecret, userId: clientId } = creds;
22796
22806
  if (!appId)
22797
22807
  return Err(new Error("Missing apiKey (App ID) in credentials"));
@@ -22807,7 +22817,8 @@ async function consumeConsent(creds, tokenId) {
22807
22817
  app_id: appId,
22808
22818
  app_secret: appSecret
22809
22819
  },
22810
- body: JSON.stringify({})
22820
+ body: JSON.stringify({}),
22821
+ dispatcher: opts?.dispatcher
22811
22822
  });
22812
22823
  if (!response.ok) {
22813
22824
  const body = await response.text();
@@ -22833,7 +22844,7 @@ async function consumeConsent(creds, tokenId) {
22833
22844
  return Err(err instanceof Error ? err : new Error(String(err)));
22834
22845
  }
22835
22846
  }
22836
- async function refreshSession3(session) {
22847
+ async function refreshSession3(session, opts) {
22837
22848
  const { accessToken, userId: clientId } = session;
22838
22849
  if (!accessToken)
22839
22850
  return Err(new Error("Missing accessToken in session"));
@@ -22846,7 +22857,8 @@ async function refreshSession3(session) {
22846
22857
  "Content-Type": "application/json",
22847
22858
  "access-token": accessToken,
22848
22859
  dhanClientId: clientId
22849
- }
22860
+ },
22861
+ dispatcher: opts?.dispatcher
22850
22862
  });
22851
22863
  if (!response.ok) {
22852
22864
  const body = await response.text();
@@ -23084,20 +23096,24 @@ class DhanSocket {
23084
23096
  clientId;
23085
23097
  accessToken;
23086
23098
  reconnectAttempts = 0;
23087
- maxReconnects = 5;
23099
+ disposed = false;
23088
23100
  reconnectTimer = null;
23089
23101
  heartbeatTimer = null;
23090
- constructor(clientId, accessToken) {
23102
+ egressIp;
23103
+ constructor(clientId, accessToken, egressIp) {
23091
23104
  this.clientId = clientId;
23092
23105
  this.accessToken = accessToken;
23106
+ this.egressIp = egressIp;
23093
23107
  }
23094
23108
  connect() {
23109
+ if (this.disposed)
23110
+ return;
23095
23111
  if (this.state === "CONNECTED" || this.state === "CONNECTING")
23096
23112
  return;
23097
23113
  this.state = "CONNECTING";
23098
23114
  try {
23099
23115
  const url = `${DHAN_WS_URL3}?version=2&token=${this.accessToken}&clientId=${this.clientId}&authType=2`;
23100
- this.ws = new WS2(url);
23116
+ this.ws = new WS2(url, wsEgressOptions(this.egressIp));
23101
23117
  } catch {
23102
23118
  this.state = "DISCONNECTED";
23103
23119
  return;
@@ -23143,9 +23159,9 @@ class DhanSocket {
23143
23159
  });
23144
23160
  }
23145
23161
  disconnect() {
23162
+ this.disposed = true;
23146
23163
  this.clearReconnectTimer();
23147
23164
  this.stopHeartbeat();
23148
- this.reconnectAttempts = this.maxReconnects;
23149
23165
  if (this.ws) {
23150
23166
  this.ws.close();
23151
23167
  this.ws = null;
@@ -23357,12 +23373,13 @@ class DhanSocket {
23357
23373
  }
23358
23374
  }
23359
23375
  attemptReconnect() {
23360
- if (this.reconnectAttempts >= this.maxReconnects)
23376
+ if (this.disposed || this.reconnectTimer)
23361
23377
  return;
23362
23378
  this.state = "RECONNECTING";
23363
23379
  this.reconnectAttempts += 1;
23364
23380
  const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
23365
23381
  this.reconnectTimer = setTimeout(() => {
23382
+ this.reconnectTimer = null;
23366
23383
  this.connect();
23367
23384
  }, delay);
23368
23385
  }
@@ -23442,12 +23459,16 @@ class DhanInstruments {
23442
23459
  };
23443
23460
  accessToken = "";
23444
23461
  clientId = "";
23462
+ dispatcher;
23445
23463
  setCredentials(clientId, accessToken) {
23446
23464
  this.clientId = clientId;
23447
23465
  this.accessToken = accessToken;
23448
23466
  }
23467
+ setDispatcher(dispatcher) {
23468
+ this.dispatcher = dispatcher;
23469
+ }
23449
23470
  async* streamDump() {
23450
- const response = await fetch(DHAN_INSTRUMENTS_URL3);
23471
+ const response = await fetch(DHAN_INSTRUMENTS_URL3, { dispatcher: this.dispatcher });
23451
23472
  if (!response.ok) {
23452
23473
  throw new Error(`Failed to fetch Dhan instruments: ${response.status}`);
23453
23474
  }
@@ -23507,7 +23528,8 @@ class DhanInstruments {
23507
23528
  "access-token": this.accessToken,
23508
23529
  "client-id": this.clientId
23509
23530
  },
23510
- body: JSON.stringify(payload)
23531
+ body: JSON.stringify(payload),
23532
+ dispatcher: this.dispatcher
23511
23533
  });
23512
23534
  if (!response.ok) {
23513
23535
  return Err(new Error(`Dhan search failed (${response.status})`));
@@ -23608,14 +23630,19 @@ class DhanBroker {
23608
23630
  oauthCreds = null;
23609
23631
  instrumentsImpl;
23610
23632
  _iMaster;
23633
+ egressIp;
23634
+ dispatcher;
23611
23635
  constructor(options) {
23612
23636
  this.instrumentsImpl = new DhanInstruments;
23613
23637
  this.instruments = this.instrumentsImpl;
23614
23638
  this._iMaster = new InstrumentMaster(options);
23639
+ this.egressIp = options?.egressIp;
23640
+ this.dispatcher = egressDispatcher(options?.egressIp);
23641
+ this.instrumentsImpl.setDispatcher(this.dispatcher);
23615
23642
  }
23616
23643
  async authenticate(creds) {
23617
23644
  this.clientId = creds.userId ?? "";
23618
- const result = await authenticate3(creds);
23645
+ const result = await authenticate3(creds, { dispatcher: this.dispatcher });
23619
23646
  if (!result.ok)
23620
23647
  return result;
23621
23648
  this.session = result.value;
@@ -23623,7 +23650,7 @@ class DhanBroker {
23623
23650
  return result;
23624
23651
  }
23625
23652
  async refreshSession(session) {
23626
- const result = await refreshSession3(session);
23653
+ const result = await refreshSession3(session, { dispatcher: this.dispatcher });
23627
23654
  if (result.ok) {
23628
23655
  this.session = result.value;
23629
23656
  if (!this.clientId && result.value.userId)
@@ -23646,13 +23673,13 @@ class DhanBroker {
23646
23673
  async generateConsent(creds) {
23647
23674
  this.oauthCreds = creds;
23648
23675
  this.clientId = creds.userId ?? "";
23649
- return generateConsent(creds);
23676
+ return generateConsent(creds, { dispatcher: this.dispatcher });
23650
23677
  }
23651
23678
  async consumeConsent(tokenId) {
23652
23679
  if (!this.oauthCreds) {
23653
23680
  return Err(new Error("Call generateConsent() before consumeConsent()"));
23654
23681
  }
23655
- const result = await consumeConsent(this.oauthCreds, tokenId);
23682
+ const result = await consumeConsent(this.oauthCreds, tokenId, { dispatcher: this.dispatcher });
23656
23683
  if (!result.ok)
23657
23684
  return result;
23658
23685
  this.session = result.value;
@@ -24054,7 +24081,7 @@ class DhanBroker {
24054
24081
  if (body && (method === "POST" || method === "PUT")) {
24055
24082
  options.body = JSON.stringify(body);
24056
24083
  }
24057
- const response = await fetch(url, options);
24084
+ const response = await fetch(url, { ...options, dispatcher: this.dispatcher });
24058
24085
  if (!response.ok) {
24059
24086
  const text = await response.text();
24060
24087
  throw new Error(`Dhan ${method} ${path} failed (${response.status}): ${text}`);
@@ -24066,7 +24093,7 @@ class DhanBroker {
24066
24093
  return;
24067
24094
  if (!this.session)
24068
24095
  throw new Error("Cannot create socket without an active session");
24069
- this.socket = new DhanSocket(this.clientId, this.session.accessToken);
24096
+ this.socket = new DhanSocket(this.clientId, this.session.accessToken, this.egressIp);
24070
24097
  this.socket.connect();
24071
24098
  }
24072
24099
  }
@@ -24975,7 +25002,7 @@ function generateTOTP2(secret) {
24975
25002
  const code = (hmac[offset] & 127) << 24 | (hmac[offset + 1] & 255) << 16 | (hmac[offset + 2] & 255) << 8 | hmac[offset + 3] & 255;
24976
25003
  return String(code % 1e6).padStart(6, "0");
24977
25004
  }
24978
- async function authenticate4(creds) {
25005
+ async function authenticate4(creds, opts) {
24979
25006
  const userKey = creds.userKey ?? creds.apiKey;
24980
25007
  const clientCode = creds.clientCode;
24981
25008
  const encryptionKey = creds.encryptionKey;
@@ -25003,7 +25030,8 @@ async function authenticate4(creds) {
25003
25030
  const totpRes = await fetch(ROUTES.TOTP_LOGIN, {
25004
25031
  method: "POST",
25005
25032
  headers: { "Content-Type": "application/json" },
25006
- body: JSON.stringify(totpPayload)
25033
+ body: JSON.stringify(totpPayload),
25034
+ dispatcher: opts?.dispatcher
25007
25035
  });
25008
25036
  let totpJson = await totpRes.json();
25009
25037
  if (!totpJson.body?.RequestToken && totpSecret && totpJson.body?.Message?.toLowerCase().includes("used in past")) {
@@ -25015,7 +25043,8 @@ async function authenticate4(creds) {
25015
25043
  const retryRes = await fetch(ROUTES.TOTP_LOGIN, {
25016
25044
  method: "POST",
25017
25045
  headers: { "Content-Type": "application/json" },
25018
- body: JSON.stringify({ head: { Key: userKey }, body: { Email_ID: clientCode, TOTP: freshTotp, PIN: pin } })
25046
+ body: JSON.stringify({ head: { Key: userKey }, body: { Email_ID: clientCode, TOTP: freshTotp, PIN: pin } }),
25047
+ dispatcher: opts?.dispatcher
25019
25048
  });
25020
25049
  totpJson = await retryRes.json();
25021
25050
  }
@@ -25023,12 +25052,12 @@ async function authenticate4(creds) {
25023
25052
  return Err(new Error(`5paisa TOTP login failed: ${totpJson.body?.Message ?? "No RequestToken returned"}`));
25024
25053
  }
25025
25054
  console.log("[5paisa] Step 1 OK: got RequestToken");
25026
- return exchangeRequestToken(totpJson.body.RequestToken, userKey, encryptionKey, userId, clientCode);
25055
+ return exchangeRequestToken(totpJson.body.RequestToken, userKey, encryptionKey, userId, clientCode, opts);
25027
25056
  } catch (err) {
25028
25057
  return Err(err instanceof Error ? err : new Error(String(err)));
25029
25058
  }
25030
25059
  }
25031
- async function exchangeRequestToken(requestToken, userKey, encryptionKey, userId, clientCode) {
25060
+ async function exchangeRequestToken(requestToken, userKey, encryptionKey, userId, clientCode, opts) {
25032
25061
  try {
25033
25062
  const accessPayload = {
25034
25063
  head: { Key: userKey },
@@ -25042,7 +25071,8 @@ async function exchangeRequestToken(requestToken, userKey, encryptionKey, userId
25042
25071
  const accessRes = await fetch(ROUTES.ACCESS_TOKEN, {
25043
25072
  method: "POST",
25044
25073
  headers: { "Content-Type": "application/json" },
25045
- body: JSON.stringify(accessPayload)
25074
+ body: JSON.stringify(accessPayload),
25075
+ dispatcher: opts?.dispatcher
25046
25076
  });
25047
25077
  const accessJson = await accessRes.json();
25048
25078
  if (!accessJson.body?.AccessToken) {
@@ -25064,7 +25094,7 @@ async function exchangeRequestToken(requestToken, userKey, encryptionKey, userId
25064
25094
  return Err(err instanceof Error ? err : new Error(String(err)));
25065
25095
  }
25066
25096
  }
25067
- async function authenticateWithToken(creds) {
25097
+ async function authenticateWithToken(creds, _opts) {
25068
25098
  const accessToken = creds.accessToken;
25069
25099
  const clientCode = creds.clientCode ?? creds.userId ?? "";
25070
25100
  if (!accessToken)
@@ -25364,9 +25394,11 @@ class FivePaisaSocket {
25364
25394
  reconnectAttempts = 0;
25365
25395
  maxReconnects = 5;
25366
25396
  reconnectTimer = null;
25367
- constructor(clientCode, accessToken) {
25397
+ egressIp;
25398
+ constructor(clientCode, accessToken, egressIp) {
25368
25399
  this.clientCode = clientCode;
25369
25400
  this.accessToken = accessToken;
25401
+ this.egressIp = egressIp;
25370
25402
  }
25371
25403
  connect() {
25372
25404
  if (this.state === "CONNECTED" || this.state === "CONNECTING")
@@ -25374,7 +25406,7 @@ class FivePaisaSocket {
25374
25406
  this.state = "CONNECTING";
25375
25407
  const baseUrl = getWsUrl(this.accessToken);
25376
25408
  const url = `${baseUrl}${this.accessToken}|${this.clientCode}`;
25377
- this.ws = new WS3(url);
25409
+ this.ws = new WS3(url, wsEgressOptions(this.egressIp));
25378
25410
  this.ws.on("open", () => {
25379
25411
  this.state = "CONNECTED";
25380
25412
  this.reconnectAttempts = 0;
@@ -25587,15 +25619,19 @@ class FivePaisaInstruments {
25587
25619
  };
25588
25620
  accessToken = "";
25589
25621
  clientCode = "";
25622
+ dispatcher;
25590
25623
  setCredentials(clientCode, accessToken) {
25591
25624
  this.clientCode = clientCode;
25592
25625
  this.accessToken = accessToken;
25593
25626
  }
25627
+ setDispatcher(dispatcher) {
25628
+ this.dispatcher = dispatcher;
25629
+ }
25594
25630
  async* streamDump() {
25595
25631
  for (const segment of SEGMENTS) {
25596
25632
  const url = `${FIVEPAISA_SCRIP_MASTER_BASE3}/${segment}`;
25597
25633
  try {
25598
- const response = await fetch(url);
25634
+ const response = await fetch(url, { dispatcher: this.dispatcher });
25599
25635
  if (!response.ok)
25600
25636
  continue;
25601
25637
  const text = await response.text();
@@ -25717,13 +25753,19 @@ class FivePaisaBroker {
25717
25753
  credentials = null;
25718
25754
  instrumentsImpl;
25719
25755
  _iMaster;
25756
+ egressIp;
25757
+ dispatcher;
25720
25758
  constructor(options) {
25721
25759
  this.instrumentsImpl = new FivePaisaInstruments;
25722
25760
  this.instruments = this.instrumentsImpl;
25723
25761
  this._iMaster = new InstrumentMaster(options);
25762
+ this.egressIp = options?.egressIp;
25763
+ this.dispatcher = egressDispatcher(options?.egressIp);
25764
+ this.instrumentsImpl.setDispatcher(this.dispatcher);
25724
25765
  }
25725
25766
  async authenticate(creds) {
25726
- const result = creds.accessToken ? await authenticateWithToken(creds) : await authenticate4(creds);
25767
+ const opts = { dispatcher: this.dispatcher };
25768
+ const result = creds.accessToken ? await authenticateWithToken(creds, opts) : await authenticate4(creds, opts);
25727
25769
  if (!result.ok)
25728
25770
  return result;
25729
25771
  this.credentials = creds;
@@ -25779,7 +25821,10 @@ class FivePaisaBroker {
25779
25821
  const brokerOid = res.BrokerOrderID ?? 0;
25780
25822
  const isRejected = (res.Status ?? 0) !== 0 || (res.RMSResponseCode ?? 0) < 0 || (res.Message ?? "").toLowerCase().includes("rejected");
25781
25823
  if (isRejected) {
25782
- return Err(new Error(res.Message ?? `Order rejected (Status=${res.Status}, RMS=${res.RMSResponseCode})`));
25824
+ const err = new Error(res.Message ?? `Order rejected (Status=${res.Status}, RMS=${res.RMSResponseCode})`);
25825
+ if (brokerOid > 0)
25826
+ err.brokerOrderId = String(brokerOid);
25827
+ return Err(err);
25783
25828
  }
25784
25829
  if (brokerOid === 0) {
25785
25830
  return Err(new Error(`Order placement failed: ${res.Message ?? "No BrokerOrderID returned"}`));
@@ -26060,7 +26105,8 @@ class FivePaisaBroker {
26060
26105
  headers: {
26061
26106
  "Content-Type": "application/json",
26062
26107
  Authorization: `bearer ${token}`
26063
- }
26108
+ },
26109
+ dispatcher: this.dispatcher
26064
26110
  });
26065
26111
  const text = await res.text();
26066
26112
  let json;
@@ -26232,7 +26278,8 @@ class FivePaisaBroker {
26232
26278
  "Content-Type": "application/json",
26233
26279
  Authorization: `Bearer ${this.session.accessToken}`
26234
26280
  },
26235
- body: JSON.stringify(payload)
26281
+ body: JSON.stringify(payload),
26282
+ dispatcher: this.dispatcher
26236
26283
  });
26237
26284
  const text = await response.text();
26238
26285
  let json;
@@ -26255,7 +26302,7 @@ class FivePaisaBroker {
26255
26302
  }
26256
26303
  return;
26257
26304
  }
26258
- this.socket = new FivePaisaSocket(this.session.userId, this.session.accessToken);
26305
+ this.socket = new FivePaisaSocket(this.session.userId, this.session.accessToken, this.egressIp);
26259
26306
  this.socket.connect();
26260
26307
  }
26261
26308
  }