@adaptic/utils 0.0.902 → 0.0.904

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.mjs CHANGED
@@ -12,15 +12,12 @@ import require$$0$3 from 'stream';
12
12
  import require$$7 from 'url';
13
13
  import require$$0$1 from 'zlib';
14
14
  import require$$0$2 from 'buffer';
15
- import { clearLine, cursorTo } from 'readline';
16
- import * as fs from 'fs';
17
- import fs__default from 'fs';
18
- import * as path from 'path';
19
- import path__default from 'path';
15
+ import require$$0$5 from 'fs';
16
+ import require$$1$2 from 'path';
20
17
  import require$$4$1 from 'assert';
21
- import require$$1$2 from 'tty';
22
- import require$$1$3 from 'util';
23
- import require$$0$5 from 'os';
18
+ import require$$1$3 from 'tty';
19
+ import require$$1$4 from 'util';
20
+ import require$$0$6 from 'os';
24
21
 
25
22
  /**
26
23
  * Configurable logger interface compatible with Pino and other logging libraries.
@@ -625,7 +622,7 @@ async function createOrder$1(auth, params) {
625
622
  try {
626
623
  const { APIKey, APISecret, type } = await validateAuth(auth);
627
624
  const apiBaseUrl = getTradingApiUrl(type);
628
- const response = await fetch(`${apiBaseUrl}/v2/orders`, {
625
+ const response = await fetch(`${apiBaseUrl}/orders`, {
629
626
  method: "POST",
630
627
  headers: {
631
628
  "APCA-API-KEY-ID": APIKey,
@@ -674,7 +671,7 @@ async function getOrders$1(auth, params = {}) {
674
671
  queryParams.append("symbols", params.symbols.join(","));
675
672
  if (params.side)
676
673
  queryParams.append("side", params.side);
677
- const response = await fetch(`${apiBaseUrl}/v2/orders?${queryParams}`, {
674
+ const response = await fetch(`${apiBaseUrl}/orders?${queryParams}`, {
678
675
  method: "GET",
679
676
  headers: {
680
677
  "APCA-API-KEY-ID": APIKey,
@@ -712,7 +709,7 @@ async function cancelAllOrders$1(auth) {
712
709
  try {
713
710
  const { APIKey, APISecret, type } = await validateAuth(auth);
714
711
  const apiBaseUrl = getTradingApiUrl(type);
715
- const response = await fetch(`${apiBaseUrl}/v2/orders`, {
712
+ const response = await fetch(`${apiBaseUrl}/orders`, {
716
713
  method: "DELETE",
717
714
  headers: {
718
715
  "APCA-API-KEY-ID": APIKey,
@@ -745,7 +742,7 @@ async function getOrder$1(auth, orderId, nested) {
745
742
  const queryParams = new URLSearchParams();
746
743
  if (nested)
747
744
  queryParams.append("nested", "true");
748
- const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}?${queryParams}`, {
745
+ const response = await fetch(`${apiBaseUrl}/orders/${orderId}?${queryParams}`, {
749
746
  method: "GET",
750
747
  headers: {
751
748
  "APCA-API-KEY-ID": APIKey,
@@ -775,7 +772,7 @@ async function replaceOrder$1(auth, orderId, params) {
775
772
  try {
776
773
  const { APIKey, APISecret, type } = await validateAuth(auth);
777
774
  const apiBaseUrl = getTradingApiUrl(type);
778
- const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}`, {
775
+ const response = await fetch(`${apiBaseUrl}/orders/${orderId}`, {
779
776
  method: "PATCH",
780
777
  headers: {
781
778
  "APCA-API-KEY-ID": APIKey,
@@ -807,7 +804,7 @@ async function cancelOrder$1(auth, orderId) {
807
804
  try {
808
805
  const { APIKey, APISecret, type } = await validateAuth(auth);
809
806
  const apiBaseUrl = getTradingApiUrl(type);
810
- const response = await fetch(`${apiBaseUrl}/v2/orders/${orderId}`, {
807
+ const response = await fetch(`${apiBaseUrl}/orders/${orderId}`, {
811
808
  method: "DELETE",
812
809
  headers: {
813
810
  "APCA-API-KEY-ID": APIKey,
@@ -866,7 +863,7 @@ async function createLimitOrder(auth, params = {
866
863
  body.client_order_id = client_order_id;
867
864
  }
868
865
  return makeRequest(auth, {
869
- endpoint: "/v2/orders",
866
+ endpoint: "/orders",
870
867
  method: "POST",
871
868
  body,
872
869
  });
@@ -1495,7 +1492,7 @@ async function fetchAllPositions(auth) {
1495
1492
  try {
1496
1493
  const { APIKey, APISecret, type } = await validateAuth(auth);
1497
1494
  const apiBaseUrl = getTradingApiUrl(type);
1498
- const apiUrl = `${apiBaseUrl}/v2/positions`;
1495
+ const apiUrl = `${apiBaseUrl}/positions`;
1499
1496
  const response = await fetch(apiUrl, {
1500
1497
  method: "GET",
1501
1498
  headers: {
@@ -1526,7 +1523,7 @@ async function fetchPosition(auth, symbolOrAssetId) {
1526
1523
  try {
1527
1524
  const { APIKey, APISecret, type } = await validateAuth(auth);
1528
1525
  const apiBaseUrl = getTradingApiUrl(type);
1529
- const response = await fetch(`${apiBaseUrl}/v2/positions/${symbolOrAssetId}`, {
1526
+ const response = await fetch(`${apiBaseUrl}/positions/${symbolOrAssetId}`, {
1530
1527
  method: "GET",
1531
1528
  headers: {
1532
1529
  "APCA-API-KEY-ID": APIKey,
@@ -1643,7 +1640,7 @@ async function closePosition$1(auth, symbolOrAssetId, params) {
1643
1640
  queryParams.append("percentage", params.percentage.toString());
1644
1641
  }
1645
1642
  const queryString = queryParams.toString();
1646
- const url = `${apiBaseUrl}/v2/positions/${encodeURIComponent(symbolOrAssetId)}${queryString ? `?${queryString}` : ""}`;
1643
+ const url = `${apiBaseUrl}/positions/${encodeURIComponent(symbolOrAssetId)}${queryString ? `?${queryString}` : ""}`;
1647
1644
  const response = await fetch(url, {
1648
1645
  method: "DELETE",
1649
1646
  headers: {
@@ -1749,7 +1746,7 @@ async function closeAllPositions$1(auth, params = { cancel_orders: true, useLimi
1749
1746
  }
1750
1747
  else {
1751
1748
  const response = await makeRequest(auth, {
1752
- endpoint: "/v2/positions",
1749
+ endpoint: "/positions",
1753
1750
  method: "DELETE",
1754
1751
  queryString: cancel_orders ? "?cancel_orders=true" : "",
1755
1752
  });
@@ -1915,7 +1912,7 @@ async function fetchPortfolioHistory({ params, accountId, client, alpacaAccount,
1915
1912
  }
1916
1913
  const { APIKey, APISecret, type } = alpacaAccountObj;
1917
1914
  const apiBaseUrl = getTradingApiUrl(type);
1918
- const apiUrl = `${apiBaseUrl}/v2/account/portfolio/history`;
1915
+ const apiUrl = `${apiBaseUrl}/account/portfolio/history`;
1919
1916
  const { start, end, period } = params;
1920
1917
  // Validate date formats
1921
1918
  if (start) {
@@ -2222,7 +2219,7 @@ async function getAsset(auth, symbolOrAssetId) {
2222
2219
  const apiBaseUrl = getTradingApiUrl(type);
2223
2220
  // Use encodeURIComponent to handle special characters in symbols (e.g., BTC/USDT)
2224
2221
  const encodedSymbolOrAssetId = encodeURIComponent(symbolOrAssetId);
2225
- const response = await fetch(`${apiBaseUrl}/v2/assets/${encodedSymbolOrAssetId}`, {
2222
+ const response = await fetch(`${apiBaseUrl}/assets/${encodedSymbolOrAssetId}`, {
2226
2223
  method: "GET",
2227
2224
  headers: {
2228
2225
  "APCA-API-KEY-ID": APIKey,
@@ -5166,6 +5163,11 @@ function validateConcurrency(concurrency) {
5166
5163
  /**********************************************************************************
5167
5164
  * Polygon.io calls
5168
5165
  **********************************************************************************/
5166
+ /**
5167
+ * Set of Polygon API response statuses that indicate valid, usable data.
5168
+ * "OK" = real-time data, "DELAYED" = delayed data (still valid, e.g. free-tier plans).
5169
+ */
5170
+ const POLYGON_VALID_STATUSES = new Set(["OK", "DELAYED"]);
5169
5171
  // Constants from environment variables
5170
5172
  const POLYGON_API_KEY = process.env.POLYGON_API_KEY;
5171
5173
  // Define concurrency limits per API
@@ -5280,7 +5282,7 @@ const fetchLastTrade = async (symbol, options) => {
5280
5282
  try {
5281
5283
  const response = await fetchWithRetry(`${baseUrl}?${params.toString()}`, {}, 3, 1000);
5282
5284
  const data = await response.json();
5283
- if (data.status !== "OK" || !data.results) {
5285
+ if (!POLYGON_VALID_STATUSES.has(data.status) || !data.results) {
5284
5286
  throw new Error(`Polygon.io API error: ${data.status || "No results"} ${data.error || ""}`);
5285
5287
  }
5286
5288
  const { p: price, s: vol, t: timestamp } = data.results;
@@ -5352,9 +5354,12 @@ const fetchPrices = async (params, options) => {
5352
5354
  //getLogger().info(`Debug: Fetching ${nextUrl}`);
5353
5355
  const response = await fetchWithRetry(nextUrl, {}, 3, 1000);
5354
5356
  const data = await response.json();
5355
- if (data.status !== "OK") {
5357
+ if (!POLYGON_VALID_STATUSES.has(data.status)) {
5356
5358
  throw new Error(`Polygon.io API responded with status: ${data.status}`);
5357
5359
  }
5360
+ if (data.status === "DELAYED") {
5361
+ getLogger().warn(`Polygon.io returned DELAYED data for ${params.ticker} — using delayed results`, { ticker: params.ticker, source: "PolygonAPI.fetchPrices" });
5362
+ }
5358
5363
  if (data.results) {
5359
5364
  allResults = [...allResults, ...data.results];
5360
5365
  }
@@ -5466,7 +5471,7 @@ const fetchGroupedDaily = async (date, options) => {
5466
5471
  try {
5467
5472
  const response = await fetchWithRetry(`${baseUrl}?${params.toString()}`, {}, 3, 1000);
5468
5473
  const data = await response.json();
5469
- if (data.status !== "OK") {
5474
+ if (!POLYGON_VALID_STATUSES.has(data.status)) {
5470
5475
  throw new Error(`Polygon.io API responded with status: ${data.status}`);
5471
5476
  }
5472
5477
  return {
@@ -5557,7 +5562,7 @@ symbol, date = new Date(), options) => {
5557
5562
  return polygonLimit(async () => {
5558
5563
  const response = await fetchWithRetry(`${baseUrl}?${params.toString()}`, {}, 3, 1000);
5559
5564
  const data = await response.json();
5560
- if (data.status !== "OK") {
5565
+ if (!POLYGON_VALID_STATUSES.has(data.status)) {
5561
5566
  throw new Error(`Failed to fetch daily open/close data for ${symbol}: ${data.status}`);
5562
5567
  }
5563
5568
  return data;
@@ -12136,6 +12141,33 @@ Object.defineProperties(createChalk.prototype, styles);
12136
12141
  const chalk = createChalk();
12137
12142
  createChalk({level: stderrColor ? stderrColor.level : 0});
12138
12143
 
12144
+ // Detect whether we are running in a Node.js environment with a real stdout.
12145
+ // In browsers (or environments without process.stdout) all terminal / fs
12146
+ // operations become no-ops so the library can be safely imported client-side.
12147
+ const isNode = typeof process !== "undefined" &&
12148
+ typeof process.stdout !== "undefined" &&
12149
+ typeof process.stdout.write === "function";
12150
+ // Lazy-load Node-only dependencies so bundlers can tree-shake / stub them.
12151
+ // chalk is kept as a static import (ESM-only in v5) — Rollup handles it.
12152
+ // readline, fs, and path are loaded at runtime only in Node.
12153
+ let clearLine;
12154
+ let cursorTo;
12155
+ let fs;
12156
+ let path;
12157
+ if (isNode) {
12158
+ try {
12159
+ /* eslint-disable @typescript-eslint/no-require-imports */
12160
+ const readline = require("readline");
12161
+ clearLine = readline.clearLine;
12162
+ cursorTo = readline.cursorTo;
12163
+ fs = require("fs");
12164
+ path = require("path");
12165
+ /* eslint-enable @typescript-eslint/no-require-imports */
12166
+ }
12167
+ catch {
12168
+ // Silently degrade — all operations will be no-ops.
12169
+ }
12170
+ }
12139
12171
  class DisplayManager {
12140
12172
  static instance;
12141
12173
  promptText = "";
@@ -12153,9 +12185,19 @@ class DisplayManager {
12153
12185
  * Logs a message while preserving the prompt at the bottom
12154
12186
  */
12155
12187
  log(message, options) {
12188
+ if (!isNode) {
12189
+ // In browser environments, fall back to console
12190
+ const level = options?.type === "error"
12191
+ ? "error"
12192
+ : options?.type === "warn"
12193
+ ? "warn"
12194
+ : "log";
12195
+ console[level](message);
12196
+ return;
12197
+ }
12156
12198
  // Clear the current prompt line
12157
- clearLine(process.stdout, 0);
12158
- cursorTo(process.stdout, 0);
12199
+ clearLine?.(process.stdout, 0);
12200
+ cursorTo?.(process.stdout, 0);
12159
12201
  // Format the timestamp
12160
12202
  const date = new Date();
12161
12203
  const timestamp = date.toLocaleString("en-US", {
@@ -12166,11 +12208,13 @@ class DisplayManager {
12166
12208
  // Build the log message
12167
12209
  let logMessage = `[${timestamp}]${options?.source ? ` [${options.source}] ` : ""}${account ? ` [${account}] ` : ""}${symbol ? ` [${symbol}] ` : ""}${message}`;
12168
12210
  // Add color based on type
12169
- if (options?.type === "error") {
12170
- logMessage = chalk.red(logMessage);
12171
- }
12172
- else if (options?.type === "warn") {
12173
- logMessage = chalk.yellow(logMessage);
12211
+ if (chalk) {
12212
+ if (options?.type === "error") {
12213
+ logMessage = chalk.red(logMessage);
12214
+ }
12215
+ else if (options?.type === "warn") {
12216
+ logMessage = chalk.yellow(logMessage);
12217
+ }
12174
12218
  }
12175
12219
  // Write the log message
12176
12220
  process.stdout.write(logMessage + "\n");
@@ -12190,6 +12234,8 @@ class DisplayManager {
12190
12234
  * Writes a log entry to a symbol-specific log file
12191
12235
  */
12192
12236
  writeSymbolLog(symbol, date, logMessage, options) {
12237
+ if (!fs || !path)
12238
+ return;
12193
12239
  try {
12194
12240
  // Create logs directory if it doesn't exist
12195
12241
  if (!fs.existsSync("logs")) {
@@ -12216,6 +12262,8 @@ class DisplayManager {
12216
12262
  * Writes a log entry to a generic log file when no symbol is provided
12217
12263
  */
12218
12264
  writeGenericLog(date, logMessage, options) {
12265
+ if (!fs || !path)
12266
+ return;
12219
12267
  try {
12220
12268
  // Create logs directory if it doesn't exist
12221
12269
  if (!fs.existsSync("logs")) {
@@ -12240,11 +12288,15 @@ class DisplayManager {
12240
12288
  }
12241
12289
  }
12242
12290
  writePrompt() {
12291
+ if (!isNode)
12292
+ return;
12243
12293
  process.stdout.write(this.promptText);
12244
12294
  }
12245
12295
  clearPrompt() {
12246
- clearLine(process.stdout, 0);
12247
- cursorTo(process.stdout, 0);
12296
+ if (!isNode)
12297
+ return;
12298
+ clearLine?.(process.stdout, 0);
12299
+ cursorTo?.(process.stdout, 0);
12248
12300
  }
12249
12301
  restorePrompt() {
12250
12302
  this.writePrompt();
@@ -15217,8 +15269,8 @@ function requireMain () {
15217
15269
 
15218
15270
  */
15219
15271
 
15220
- const fs = fs__default;
15221
- const path = path__default;
15272
+ const fs = require$$0$5;
15273
+ const path = require$$1$2;
15222
15274
 
15223
15275
  function log (message /*: string */) {
15224
15276
  console.log(`[dotenv][DEBUG] ${message}`);
@@ -17026,8 +17078,8 @@ var hasRequiredSupportsColor;
17026
17078
  function requireSupportsColor () {
17027
17079
  if (hasRequiredSupportsColor) return supportsColor_1;
17028
17080
  hasRequiredSupportsColor = 1;
17029
- const os = require$$0$5;
17030
- const tty = require$$1$2;
17081
+ const os = require$$0$6;
17082
+ const tty = require$$1$3;
17031
17083
  const hasFlag = requireHasFlag();
17032
17084
 
17033
17085
  const {env} = process;
@@ -17173,8 +17225,8 @@ function requireNode$1 () {
17173
17225
  if (hasRequiredNode$1) return node$1.exports;
17174
17226
  hasRequiredNode$1 = 1;
17175
17227
  (function (module, exports$1) {
17176
- const tty = require$$1$2;
17177
- const util = require$$1$3;
17228
+ const tty = require$$1$3;
17229
+ const util = require$$1$4;
17178
17230
 
17179
17231
  /**
17180
17232
  * This is the Node.js implementation of `debug()`.
@@ -19520,7 +19572,7 @@ function requireUrljoin () {
19520
19572
 
19521
19573
  var extend = requireExtend();
19522
19574
  var url = require$$7;
19523
- var path = path__default;
19575
+ var path = require$$1$2;
19524
19576
 
19525
19577
  /**
19526
19578
  * Join two or more url pieces into one.
@@ -47159,7 +47211,7 @@ function requireBuffer_list () {
47159
47211
  function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (String )(input); }
47160
47212
  var _require = require$$0$2,
47161
47213
  Buffer = _require.Buffer;
47162
- var _require2 = require$$1$3,
47214
+ var _require2 = require$$1$4,
47163
47215
  inspect = _require2.inspect;
47164
47216
  var custom = inspect && inspect.custom || 'inspect';
47165
47217
  function copyBuffer(src, target, offset) {
@@ -47658,7 +47710,7 @@ function requireNode () {
47658
47710
  * For Node.js, simply re-export the core `util.deprecate` function.
47659
47711
  */
47660
47712
 
47661
- node = require$$1$3.deprecate;
47713
+ node = require$$1$4.deprecate;
47662
47714
  return node;
47663
47715
  }
47664
47716
 
@@ -49044,7 +49096,7 @@ function require_stream_readable () {
49044
49096
  }
49045
49097
 
49046
49098
  /*<replacement>*/
49047
- var debugUtil = require$$1$3;
49099
+ var debugUtil = require$$1$4;
49048
49100
  var debug;
49049
49101
  if (debugUtil && debugUtil.debuglog) {
49050
49102
  debug = debugUtil.debuglog('stream');
@@ -50896,7 +50948,7 @@ function requireHelpers () {
50896
50948
  if (hasRequiredHelpers) return helpers;
50897
50949
  hasRequiredHelpers = 1;
50898
50950
 
50899
- const util = require$$1$3;
50951
+ const util = require$$1$4;
50900
50952
 
50901
50953
  helpers.IncompleteBufferError = IncompleteBufferError;
50902
50954