@socketsecurity/sdk 1.9.2 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,35 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
6
 
7
+ ## [1.10.1](https://github.com/SocketDev/socket-sdk-js/releases/tag/v1.10.1) - 2025-10-04
8
+
9
+ ### Added
10
+ - Automatic retry with exponential backoff to all HTTP API calls for improved reliability on transient failures
11
+
12
+ ## [1.10.0](https://github.com/SocketDev/socket-sdk-js/releases/tag/v1.10.0) - 2025-10-04
13
+
14
+ ### Added
15
+ - Added `PromiseQueue` utility for controlled concurrency in async operations
16
+ - HTTP retry logic with exponential backoff for improved reliability on transient failures
17
+ - Added option type interfaces: `CreateDependenciesSnapshotOptions`, `CreateOrgFullScanOptions`, `CreateScanFromFilepathsOptions`, `StreamOrgFullScanOptions`, `UploadManifestFilesOptions`
18
+
19
+ ### Changed
20
+ - **BREAKING**: Refactored SDK methods to use options objects instead of positional parameters for better API clarity:
21
+ - `createDependenciesSnapshot(filepaths, options)` - replaced `repo` and `branch` positional parameters with options object
22
+ - `createOrgFullScan(orgSlug, filepaths, options)` - replaced positional parameters with options object
23
+ - `createScanFromFilepaths(filepaths, options)` - replaced positional parameters with options object
24
+ - `streamOrgFullScan(orgSlug, fullScanId, options)` - replaced positional parameters with options object
25
+ - `uploadManifestFiles(orgSlug, filepaths, options)` - replaced positional parameters with options object
26
+ - Improved type safety by replacing `any` types with `unknown` or `never` where appropriate
27
+ - Enhanced code style with numeric separators for better readability of large numbers
28
+ - Improved coverage reporting accuracy with c8 ignore comments
29
+ - Updated `@socketsecurity/registry` dependency to 1.4.0
30
+
31
+ ### Fixed
32
+ - Fixed import assertion syntax for JSON imports to use standard import syntax
33
+ - Fixed HTTP retry test mocks to correctly match PUT method requests
34
+ - Fixed critical issues in type handling and URL search parameter conversions
35
+
7
36
  ## [1.9.2](https://github.com/SocketDev/socket-sdk-js/releases/tag/v1.9.2) - 2025-10-04
8
37
 
9
38
  ### Changed
package/README.md CHANGED
@@ -19,7 +19,11 @@ pnpm add @socketsecurity/sdk
19
19
  ```javascript
20
20
  import { SocketSdk } from '@socketsecurity/sdk'
21
21
 
22
- const client = new SocketSdk('yourApiKeyHere')
22
+ const client = new SocketSdk('yourApiKeyHere', {
23
+ retries: 3, // Retry failed requests up to 3 times (default: 3)
24
+ retryDelay: 1000, // Start with 1s delay, exponential backoff (default: 1000ms)
25
+ timeout: 30000, // Request timeout in milliseconds (optional)
26
+ })
23
27
 
24
28
  const res = await client.getQuota()
25
29
 
@@ -29,6 +33,27 @@ if (res.success) {
29
33
  }
30
34
  ```
31
35
 
36
+ ### Configuration Options
37
+
38
+ The SDK constructor accepts the following options:
39
+
40
+ ```typescript
41
+ interface SocketSdkOptions {
42
+ baseUrl?: string // API base URL (default: 'https://api.socket.dev/v0/')
43
+ timeout?: number // Request timeout in milliseconds
44
+ retries?: number // Number of retry attempts for failed requests (default: 3)
45
+ retryDelay?: number // Initial retry delay in ms, with exponential backoff (default: 1000)
46
+ userAgent?: string // Custom user agent string
47
+ agent?: Agent // Custom HTTP agent for advanced networking
48
+ }
49
+ ```
50
+
51
+ **Retry Logic:**
52
+ - Automatically retries transient network errors and 5xx server responses
53
+ - Uses exponential backoff: 1s, 2s, 4s, 8s... (configurable via `retryDelay`)
54
+ - Does NOT retry 401/403 authentication errors (immediate failure)
55
+ - Set `retries: 0` to disable retry logic entirely
56
+
32
57
  ### Quota Management Example
33
58
 
34
59
  ```javascript
package/dist/constants.js CHANGED
@@ -8,9 +8,6 @@ exports.publicPolicy = exports.httpAgentNames = exports.DEFAULT_USER_AGENT = voi
8
8
  * @fileoverview Configuration constants and enums for the Socket SDK.
9
9
  * Provides default values, HTTP agents, and public policy configurations for API interactions.
10
10
  */
11
- // Import attributes are only supported when the '--module' option is set to
12
- // 'esnext', 'node18', 'node20', 'nodenext', or 'preserve'.
13
- // @ts-ignore: Avoid TS import attributes error.
14
11
  const package_json_1 = __importDefault(require("../package.json"));
15
12
  const user_agent_1 = require("./user-agent");
16
13
  exports.DEFAULT_USER_AGENT = (0, user_agent_1.createUserAgentFromPkgJson)(package_json_1.default);
@@ -24,7 +24,7 @@ function createRequestBodyForFilepaths(filepaths, basePath) {
24
24
  const filename = node_path_1.default.basename(absPath);
25
25
  requestBody.push([
26
26
  `Content-Disposition: form-data; name="${relPath}"; filename="${filename}"\r\n`,
27
- `Content-Type: application/octet-stream\r\n\r\n`,
27
+ 'Content-Type: application/octet-stream\r\n\r\n',
28
28
  (0, node_fs_1.createReadStream)(absPath, { highWaterMark: 1024 * 1024 }),
29
29
  ]);
30
30
  }
@@ -39,7 +39,7 @@ function createRequestBodyForJson(jsonData, basename = 'data.json') {
39
39
  const name = node_path_1.default.basename(basename, ext);
40
40
  return [
41
41
  `Content-Disposition: form-data; name="${name}"; filename="${basename}"\r\n` +
42
- `Content-Type: application/json\r\n\r\n`,
42
+ 'Content-Type: application/json\r\n\r\n',
43
43
  node_stream_1.Readable.from(JSON.stringify(jsonData), { highWaterMark: 1024 * 1024 }),
44
44
  '\r\n',
45
45
  ];
@@ -75,4 +75,39 @@ export declare function isResponseOk(response: IncomingMessage): boolean;
75
75
  * Transform artifact data based on authentication status.
76
76
  * Filters and compacts response data for public/free-tier users.
77
77
  */
78
- export declare function reshapeArtifactForPublicPolicy<T extends Record<string, any>>(data: T, isAuthenticated: boolean, actions?: string | undefined): T;
78
+ export declare function reshapeArtifactForPublicPolicy<T extends Record<string, unknown>>(data: T, isAuthenticated: boolean, actions?: string | undefined): T;
79
+ /**
80
+ * Retry helper for HTTP requests with exponential backoff.
81
+ * Wraps any async HTTP function and retries on failure.
82
+ *
83
+ * @param fn - Async function to retry
84
+ * @param retries - Number of retry attempts (default: 3)
85
+ * @param retryDelay - Initial delay in ms (default: 1000)
86
+ * @returns Result of the function call
87
+ * @throws {Error} Last error if all retries exhausted
88
+ */
89
+ export declare function withRetry<T>(fn: () => Promise<T>, retries?: number, retryDelay?: number): Promise<T>;
90
+ /**
91
+ * Create GET request with automatic retry logic.
92
+ * Retries on network errors and 5xx responses.
93
+ *
94
+ * @param retries - Number of retry attempts (default: 3)
95
+ * @param retryDelay - Initial delay in ms (default: 1000)
96
+ */
97
+ export declare function createGetRequestWithRetry(baseUrl: string, urlPath: string, options: RequestOptions, retries?: number, retryDelay?: number): Promise<IncomingMessage>;
98
+ /**
99
+ * Create DELETE request with automatic retry logic.
100
+ * Retries on network errors and 5xx responses.
101
+ *
102
+ * @param retries - Number of retry attempts (default: 3)
103
+ * @param retryDelay - Initial delay in ms (default: 1000)
104
+ */
105
+ export declare function createDeleteRequestWithRetry(baseUrl: string, urlPath: string, options: RequestOptions, retries?: number, retryDelay?: number): Promise<IncomingMessage>;
106
+ /**
107
+ * Create request with JSON payload and automatic retry logic.
108
+ * Retries on network errors and 5xx responses.
109
+ *
110
+ * @param retries - Number of retry attempts (default: 3)
111
+ * @param retryDelay - Initial delay in ms (default: 1000)
112
+ */
113
+ export declare function createRequestWithJsonAndRetry(method: SendMethod, baseUrl: string, urlPath: string, json: unknown, options: RequestOptions, retries?: number, retryDelay?: number): Promise<IncomingMessage>;
@@ -13,6 +13,10 @@ exports.getResponse = getResponse;
13
13
  exports.getResponseJson = getResponseJson;
14
14
  exports.isResponseOk = isResponseOk;
15
15
  exports.reshapeArtifactForPublicPolicy = reshapeArtifactForPublicPolicy;
16
+ exports.withRetry = withRetry;
17
+ exports.createGetRequestWithRetry = createGetRequestWithRetry;
18
+ exports.createDeleteRequestWithRetry = createDeleteRequestWithRetry;
19
+ exports.createRequestWithJsonAndRetry = createRequestWithJsonAndRetry;
16
20
  /**
17
21
  * @fileoverview HTTP client utilities for Socket API communication.
18
22
  * Provides low-level HTTP request handling with proper error management and response parsing.
@@ -248,12 +252,15 @@ function reshapeArtifactForPublicPolicy(data, isAuthenticated, actions) {
248
252
  // Handle both single artifacts and objects with artifacts arrays.
249
253
  if (data['artifacts']) {
250
254
  // Object with artifacts array.
255
+ const artifacts = data['artifacts'];
251
256
  return {
252
257
  ...data,
253
- artifacts: data['artifacts']?.map(reshapeArtifact),
258
+ artifacts: Array.isArray(artifacts)
259
+ ? artifacts.map(reshapeArtifact)
260
+ : artifacts,
254
261
  };
255
262
  }
256
- else if (data['alerts']) {
263
+ if (data['alerts']) {
257
264
  // Single artifact with alerts.
258
265
  return reshapeArtifact(data);
259
266
  }
@@ -261,3 +268,80 @@ function reshapeArtifactForPublicPolicy(data, isAuthenticated, actions) {
261
268
  return data;
262
269
  /* c8 ignore stop */
263
270
  }
271
+ /**
272
+ * Retry helper for HTTP requests with exponential backoff.
273
+ * Wraps any async HTTP function and retries on failure.
274
+ *
275
+ * @param fn - Async function to retry
276
+ * @param retries - Number of retry attempts (default: 3)
277
+ * @param retryDelay - Initial delay in ms (default: 1000)
278
+ * @returns Result of the function call
279
+ * @throws {Error} Last error if all retries exhausted
280
+ */
281
+ async function withRetry(fn, retries = 3, retryDelay = 1000) {
282
+ let lastError;
283
+ for (let attempt = 0; attempt <= retries; attempt++) {
284
+ try {
285
+ // eslint-disable-next-line no-await-in-loop
286
+ return await fn();
287
+ }
288
+ catch (error) {
289
+ lastError = error;
290
+ // Last attempt - throw error with retry context.
291
+ if (attempt === retries) {
292
+ const enhancedError = new Error(`Request failed after ${retries + 1} attempts`, { cause: lastError });
293
+ throw enhancedError;
294
+ }
295
+ // Check if error is retryable (network errors, 5xx responses).
296
+ if (error instanceof ResponseError) {
297
+ const status = error.response.statusCode;
298
+ // Don't retry client errors (4xx).
299
+ if (status && status >= 400 && status < 500) {
300
+ throw error;
301
+ }
302
+ (0, debug_1.debugLog)('withRetry', `Retrying after ${status} error (attempt ${attempt + 1}/${retries + 1})`);
303
+ }
304
+ else {
305
+ (0, debug_1.debugLog)('withRetry', `Retrying after network error (attempt ${attempt + 1}/${retries + 1})`);
306
+ }
307
+ // Exponential backoff.
308
+ const delayMs = retryDelay * 2 ** attempt;
309
+ (0, debug_1.debugLog)('withRetry', `Waiting ${delayMs}ms before retry`);
310
+ // eslint-disable-next-line no-await-in-loop
311
+ await new Promise(resolve => setTimeout(resolve, delayMs));
312
+ }
313
+ }
314
+ // Fallback error if lastError is somehow undefined.
315
+ /* c8 ignore next - Defensive fallback for undefined lastError */
316
+ throw lastError || new Error('Request failed after retries');
317
+ }
318
+ /**
319
+ * Create GET request with automatic retry logic.
320
+ * Retries on network errors and 5xx responses.
321
+ *
322
+ * @param retries - Number of retry attempts (default: 3)
323
+ * @param retryDelay - Initial delay in ms (default: 1000)
324
+ */
325
+ async function createGetRequestWithRetry(baseUrl, urlPath, options, retries = 3, retryDelay = 1000) {
326
+ return await withRetry(() => createGetRequest(baseUrl, urlPath, options), retries, retryDelay);
327
+ }
328
+ /**
329
+ * Create DELETE request with automatic retry logic.
330
+ * Retries on network errors and 5xx responses.
331
+ *
332
+ * @param retries - Number of retry attempts (default: 3)
333
+ * @param retryDelay - Initial delay in ms (default: 1000)
334
+ */
335
+ async function createDeleteRequestWithRetry(baseUrl, urlPath, options, retries = 3, retryDelay = 1000) {
336
+ return await withRetry(() => createDeleteRequest(baseUrl, urlPath, options), retries, retryDelay);
337
+ }
338
+ /**
339
+ * Create request with JSON payload and automatic retry logic.
340
+ * Retries on network errors and 5xx responses.
341
+ *
342
+ * @param retries - Number of retry attempts (default: 3)
343
+ * @param retryDelay - Initial delay in ms (default: 1000)
344
+ */
345
+ async function createRequestWithJsonAndRetry(method, baseUrl, urlPath, json, options, retries = 3, retryDelay = 1000) {
346
+ return await withRetry(() => createRequestWithJson(method, baseUrl, urlPath, json, options), retries, retryDelay);
347
+ }
package/dist/index.d.ts CHANGED
@@ -4,11 +4,11 @@
4
4
  */
5
5
  import { DEFAULT_USER_AGENT, httpAgentNames, publicPolicy } from './constants';
6
6
  import { normalizeBaseUrl, promiseWithResolvers, queryToSearchParams, resolveAbsPaths, resolveBasePath } from './utils';
7
- export type * from './types';
8
- export { createUserAgentFromPkgJson } from './user-agent';
9
- export { createDeleteRequest, createGetRequest, createRequestWithJson, getErrorResponseBody, getHttpModule, getResponse, getResponseJson, isResponseOk, reshapeArtifactForPublicPolicy, ResponseError, } from './http-client';
10
7
  export { createRequestBodyForFilepaths, createRequestBodyForJson, createUploadRequest, } from './file-upload';
11
- export { SocketSdk } from './socket-sdk-class';
8
+ export { createDeleteRequest, createGetRequest, createRequestWithJson, getErrorResponseBody, getHttpModule, getResponse, getResponseJson, isResponseOk, ResponseError, reshapeArtifactForPublicPolicy, } from './http-client';
12
9
  export { calculateTotalQuotaCost, getAllMethodRequirements, getMethodRequirements, getMethodsByPermissions, getMethodsByQuotaCost, getQuotaCost, getQuotaUsageSummary, getRequiredPermissions, hasQuotaForMethods, } from './quota-utils';
10
+ export { SocketSdk } from './socket-sdk-class';
11
+ export type * from './types';
12
+ export { createUserAgentFromPkgJson } from './user-agent';
13
13
  export { normalizeBaseUrl, promiseWithResolvers, queryToSearchParams, resolveAbsPaths, resolveBasePath, };
14
14
  export { DEFAULT_USER_AGENT, httpAgentNames, publicPolicy };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.publicPolicy = exports.httpAgentNames = exports.DEFAULT_USER_AGENT = exports.resolveBasePath = exports.resolveAbsPaths = exports.queryToSearchParams = exports.promiseWithResolvers = exports.normalizeBaseUrl = exports.hasQuotaForMethods = exports.getRequiredPermissions = exports.getQuotaUsageSummary = exports.getQuotaCost = exports.getMethodsByQuotaCost = exports.getMethodsByPermissions = exports.getMethodRequirements = exports.getAllMethodRequirements = exports.calculateTotalQuotaCost = exports.SocketSdk = exports.createUploadRequest = exports.createRequestBodyForJson = exports.createRequestBodyForFilepaths = exports.ResponseError = exports.reshapeArtifactForPublicPolicy = exports.isResponseOk = exports.getResponseJson = exports.getResponse = exports.getHttpModule = exports.getErrorResponseBody = exports.createRequestWithJson = exports.createGetRequest = exports.createDeleteRequest = exports.createUserAgentFromPkgJson = void 0;
3
+ exports.publicPolicy = exports.httpAgentNames = exports.DEFAULT_USER_AGENT = exports.resolveBasePath = exports.resolveAbsPaths = exports.queryToSearchParams = exports.promiseWithResolvers = exports.normalizeBaseUrl = exports.createUserAgentFromPkgJson = exports.SocketSdk = exports.hasQuotaForMethods = exports.getRequiredPermissions = exports.getQuotaUsageSummary = exports.getQuotaCost = exports.getMethodsByQuotaCost = exports.getMethodsByPermissions = exports.getMethodRequirements = exports.getAllMethodRequirements = exports.calculateTotalQuotaCost = exports.reshapeArtifactForPublicPolicy = exports.ResponseError = exports.isResponseOk = exports.getResponseJson = exports.getResponse = exports.getHttpModule = exports.getErrorResponseBody = exports.createRequestWithJson = exports.createGetRequest = exports.createDeleteRequest = exports.createUploadRequest = exports.createRequestBodyForJson = exports.createRequestBodyForFilepaths = void 0;
4
4
  /**
5
5
  * @fileoverview Main entry point for the Socket SDK.
6
6
  * Provides the SocketSdk class and utility functions for Socket security analysis API interactions.
@@ -16,9 +16,11 @@ Object.defineProperty(exports, "promiseWithResolvers", { enumerable: true, get:
16
16
  Object.defineProperty(exports, "queryToSearchParams", { enumerable: true, get: function () { return utils_1.queryToSearchParams; } });
17
17
  Object.defineProperty(exports, "resolveAbsPaths", { enumerable: true, get: function () { return utils_1.resolveAbsPaths; } });
18
18
  Object.defineProperty(exports, "resolveBasePath", { enumerable: true, get: function () { return utils_1.resolveBasePath; } });
19
- // Re-export functions from modules
20
- const user_agent_1 = require("./user-agent");
21
- Object.defineProperty(exports, "createUserAgentFromPkgJson", { enumerable: true, get: function () { return user_agent_1.createUserAgentFromPkgJson; } });
19
+ // Re-export file upload functions
20
+ const file_upload_1 = require("./file-upload");
21
+ Object.defineProperty(exports, "createRequestBodyForFilepaths", { enumerable: true, get: function () { return file_upload_1.createRequestBodyForFilepaths; } });
22
+ Object.defineProperty(exports, "createRequestBodyForJson", { enumerable: true, get: function () { return file_upload_1.createRequestBodyForJson; } });
23
+ Object.defineProperty(exports, "createUploadRequest", { enumerable: true, get: function () { return file_upload_1.createUploadRequest; } });
22
24
  // Re-export HTTP client functions
23
25
  const http_client_1 = require("./http-client");
24
26
  Object.defineProperty(exports, "createDeleteRequest", { enumerable: true, get: function () { return http_client_1.createDeleteRequest; } });
@@ -29,16 +31,8 @@ Object.defineProperty(exports, "getHttpModule", { enumerable: true, get: functio
29
31
  Object.defineProperty(exports, "getResponse", { enumerable: true, get: function () { return http_client_1.getResponse; } });
30
32
  Object.defineProperty(exports, "getResponseJson", { enumerable: true, get: function () { return http_client_1.getResponseJson; } });
31
33
  Object.defineProperty(exports, "isResponseOk", { enumerable: true, get: function () { return http_client_1.isResponseOk; } });
32
- Object.defineProperty(exports, "reshapeArtifactForPublicPolicy", { enumerable: true, get: function () { return http_client_1.reshapeArtifactForPublicPolicy; } });
33
34
  Object.defineProperty(exports, "ResponseError", { enumerable: true, get: function () { return http_client_1.ResponseError; } });
34
- // Re-export file upload functions
35
- const file_upload_1 = require("./file-upload");
36
- Object.defineProperty(exports, "createRequestBodyForFilepaths", { enumerable: true, get: function () { return file_upload_1.createRequestBodyForFilepaths; } });
37
- Object.defineProperty(exports, "createRequestBodyForJson", { enumerable: true, get: function () { return file_upload_1.createRequestBodyForJson; } });
38
- Object.defineProperty(exports, "createUploadRequest", { enumerable: true, get: function () { return file_upload_1.createUploadRequest; } });
39
- // Re-export the main SocketSdk class
40
- const socket_sdk_class_1 = require("./socket-sdk-class");
41
- Object.defineProperty(exports, "SocketSdk", { enumerable: true, get: function () { return socket_sdk_class_1.SocketSdk; } });
35
+ Object.defineProperty(exports, "reshapeArtifactForPublicPolicy", { enumerable: true, get: function () { return http_client_1.reshapeArtifactForPublicPolicy; } });
42
36
  // Re-export quota utility functions
43
37
  const quota_utils_1 = require("./quota-utils");
44
38
  Object.defineProperty(exports, "calculateTotalQuotaCost", { enumerable: true, get: function () { return quota_utils_1.calculateTotalQuotaCost; } });
@@ -50,3 +44,9 @@ Object.defineProperty(exports, "getQuotaCost", { enumerable: true, get: function
50
44
  Object.defineProperty(exports, "getQuotaUsageSummary", { enumerable: true, get: function () { return quota_utils_1.getQuotaUsageSummary; } });
51
45
  Object.defineProperty(exports, "getRequiredPermissions", { enumerable: true, get: function () { return quota_utils_1.getRequiredPermissions; } });
52
46
  Object.defineProperty(exports, "hasQuotaForMethods", { enumerable: true, get: function () { return quota_utils_1.hasQuotaForMethods; } });
47
+ // Re-export the main SocketSdk class
48
+ const socket_sdk_class_1 = require("./socket-sdk-class");
49
+ Object.defineProperty(exports, "SocketSdk", { enumerable: true, get: function () { return socket_sdk_class_1.SocketSdk; } });
50
+ // Re-export functions from modules
51
+ const user_agent_1 = require("./user-agent");
52
+ Object.defineProperty(exports, "createUserAgentFromPkgJson", { enumerable: true, get: function () { return user_agent_1.createUserAgentFromPkgJson; } });
@@ -0,0 +1,35 @@
1
+ export declare class PromiseQueue {
2
+ private queue;
3
+ private running;
4
+ private readonly maxConcurrency;
5
+ private readonly maxQueueLength;
6
+ /**
7
+ * Creates a new PromiseQueue
8
+ * @param maxConcurrency - Maximum number of promises that can run concurrently
9
+ * @param maxQueueLength - Maximum queue size (older tasks are dropped if exceeded)
10
+ */
11
+ constructor(maxConcurrency: number, maxQueueLength?: number | undefined);
12
+ /**
13
+ * Add a task to the queue
14
+ * @param fn - Async function to execute
15
+ * @returns Promise that resolves with the function's result
16
+ */
17
+ add<T>(fn: () => Promise<T>): Promise<T>;
18
+ private runNext;
19
+ /**
20
+ * Wait for all queued and running tasks to complete
21
+ */
22
+ onIdle(): Promise<void>;
23
+ /**
24
+ * Get the number of tasks currently running
25
+ */
26
+ get activeCount(): number;
27
+ /**
28
+ * Get the number of tasks waiting in the queue
29
+ */
30
+ get pendingCount(): number;
31
+ /**
32
+ * Clear all pending tasks from the queue (does not affect running tasks)
33
+ */
34
+ clear(): void;
35
+ }
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PromiseQueue = void 0;
4
+ class PromiseQueue {
5
+ queue = [];
6
+ running = 0;
7
+ maxConcurrency;
8
+ maxQueueLength;
9
+ /**
10
+ * Creates a new PromiseQueue
11
+ * @param maxConcurrency - Maximum number of promises that can run concurrently
12
+ * @param maxQueueLength - Maximum queue size (older tasks are dropped if exceeded)
13
+ */
14
+ constructor(maxConcurrency, maxQueueLength) {
15
+ this.maxConcurrency = maxConcurrency;
16
+ this.maxQueueLength = maxQueueLength;
17
+ if (maxConcurrency < 1) {
18
+ throw new Error('maxConcurrency must be at least 1');
19
+ }
20
+ }
21
+ /**
22
+ * Add a task to the queue
23
+ * @param fn - Async function to execute
24
+ * @returns Promise that resolves with the function's result
25
+ */
26
+ async add(fn) {
27
+ return await new Promise((resolve, reject) => {
28
+ const task = { fn, resolve, reject };
29
+ if (this.maxQueueLength && this.queue.length >= this.maxQueueLength) {
30
+ // Drop oldest task to prevent memory buildup
31
+ this.queue.shift();
32
+ }
33
+ this.queue.push(task);
34
+ this.runNext();
35
+ });
36
+ }
37
+ runNext() {
38
+ if (this.running >= this.maxConcurrency || this.queue.length === 0) {
39
+ return;
40
+ }
41
+ const task = this.queue.shift();
42
+ /* c8 ignore next 3 - Defensive check; unreachable since we verify queue.length above */
43
+ if (!task) {
44
+ return;
45
+ }
46
+ this.running++;
47
+ task
48
+ .fn()
49
+ .then(task.resolve)
50
+ .catch(task.reject)
51
+ .finally(() => {
52
+ this.running--;
53
+ this.runNext();
54
+ });
55
+ }
56
+ /**
57
+ * Wait for all queued and running tasks to complete
58
+ */
59
+ async onIdle() {
60
+ return await new Promise(resolve => {
61
+ const check = () => {
62
+ if (this.running === 0 && this.queue.length === 0) {
63
+ resolve();
64
+ }
65
+ else {
66
+ setImmediate(check);
67
+ }
68
+ };
69
+ check();
70
+ });
71
+ }
72
+ /**
73
+ * Get the number of tasks currently running
74
+ */
75
+ get activeCount() {
76
+ return this.running;
77
+ }
78
+ /**
79
+ * Get the number of tasks waiting in the queue
80
+ */
81
+ get pendingCount() {
82
+ return this.queue.length;
83
+ }
84
+ /**
85
+ * Clear all pending tasks from the queue (does not affect running tasks)
86
+ */
87
+ clear() {
88
+ this.queue = [];
89
+ }
90
+ }
91
+ exports.PromiseQueue = PromiseQueue;
@@ -22,8 +22,11 @@ function loadRequirements() {
22
22
  return requirements;
23
23
  }
24
24
  try {
25
- // Resolve path relative to current working directory
26
- const requirementsPath = (0, node_path_1.join)(process.cwd(), 'requirements.json');
25
+ // Resolve path relative to this module file location.
26
+ // When compiled, __dirname will point to dist/ directory.
27
+ // In source, __dirname points to src/ directory.
28
+ // requirements.json is always in the parent directory of dist/ or src/.
29
+ const requirementsPath = (0, node_path_1.join)(__dirname, '..', 'requirements.json');
27
30
  const data = (0, node_fs_1.readFileSync)(requirementsPath, 'utf8');
28
31
  requirements = JSON.parse(data);
29
32
  return requirements;
@@ -1,4 +1,4 @@
1
- import type { ArtifactPatches, BatchPackageFetchResultType, BatchPackageStreamOptions, Entitlement, GetOptions, PatchViewResponse, QueryParams, SendOptions, SocketSdkGenericResult, SocketSdkOptions, SocketSdkResult, UploadManifestFilesError, UploadManifestFilesReturnType } from './types';
1
+ import type { ArtifactPatches, BatchPackageFetchResultType, BatchPackageStreamOptions, CreateDependenciesSnapshotOptions, CreateOrgFullScanOptions, CreateScanFromFilepathsOptions, Entitlement, GetOptions, PatchViewResponse, QueryParams, SendOptions, SocketSdkGenericResult, SocketSdkOptions, SocketSdkResult, StreamOrgFullScanOptions, UploadManifestFilesError, UploadManifestFilesOptions, UploadManifestFilesReturnType } from './types';
2
2
  import type { IncomingMessage } from 'node:http';
3
3
  /**
4
4
  * Socket SDK for programmatic access to Socket.dev security analysis APIs.
@@ -8,7 +8,7 @@ export declare class SocketSdk {
8
8
  #private;
9
9
  /**
10
10
  * Initialize Socket SDK with API token and configuration options.
11
- * Sets up authentication, base URL, and HTTP client options.
11
+ * Sets up authentication, base URL, HTTP client options, and retry behavior.
12
12
  */
13
13
  constructor(apiToken: string, options?: SocketSdkOptions | undefined);
14
14
  /**
@@ -39,7 +39,7 @@ export declare class SocketSdk {
39
39
  *
40
40
  * @throws {Error} When server returns 5xx status codes
41
41
  */
42
- createDependenciesSnapshot(filepaths: string[], pathsRelativeTo?: string, queryParams?: QueryParams | undefined): Promise<SocketSdkResult<'createDependenciesSnapshot'>>;
42
+ createDependenciesSnapshot(filepaths: string[], options?: CreateDependenciesSnapshotOptions | undefined): Promise<SocketSdkResult<'createDependenciesSnapshot'>>;
43
43
  /**
44
44
  * Create a diff scan from two full scan IDs.
45
45
  * Compares two existing full scans to identify changes.
@@ -53,7 +53,7 @@ export declare class SocketSdk {
53
53
  *
54
54
  * @throws {Error} When server returns 5xx status codes
55
55
  */
56
- createOrgFullScan(orgSlug: string, filepaths: string[], pathsRelativeTo?: string, queryParams?: QueryParams | undefined): Promise<SocketSdkResult<'CreateOrgFullScan'>>;
56
+ createOrgFullScan(orgSlug: string, filepaths: string[], options?: CreateOrgFullScanOptions | undefined): Promise<SocketSdkResult<'CreateOrgFullScan'>>;
57
57
  /**
58
58
  * Create a new repository in an organization.
59
59
  * Registers a repository for monitoring and security scanning.
@@ -74,7 +74,7 @@ export declare class SocketSdk {
74
74
  *
75
75
  * @throws {Error} When server returns 5xx status codes
76
76
  */
77
- createScanFromFilepaths(filepaths: string[], pathsRelativeTo?: string, issueRules?: Record<string, boolean> | undefined): Promise<SocketSdkResult<'createReport'>>;
77
+ createScanFromFilepaths(filepaths: string[], options?: CreateScanFromFilepathsOptions | undefined): Promise<SocketSdkResult<'createReport'>>;
78
78
  /**
79
79
  * Delete a diff scan from an organization.
80
80
  * Permanently removes diff scan data and results.
@@ -362,7 +362,7 @@ export declare class SocketSdk {
362
362
  *
363
363
  * @throws {Error} When server returns 5xx status codes
364
364
  */
365
- streamOrgFullScan(orgSlug: string, fullScanId: string, output?: string | boolean): Promise<SocketSdkResult<'getOrgFullScan'>>;
365
+ streamOrgFullScan(orgSlug: string, fullScanId: string, options?: StreamOrgFullScanOptions | undefined): Promise<SocketSdkResult<'getOrgFullScan'>>;
366
366
  /**
367
367
  * Stream patches for artifacts in a scan report.
368
368
  *
@@ -411,7 +411,7 @@ export declare class SocketSdk {
411
411
  *
412
412
  * @throws {Error} When server returns 5xx status codes
413
413
  */
414
- uploadManifestFiles(orgSlug: string, filepaths: string[], pathsRelativeTo?: string): Promise<UploadManifestFilesReturnType | UploadManifestFilesError>;
414
+ uploadManifestFiles(orgSlug: string, filepaths: string[], options?: UploadManifestFilesOptions | undefined): Promise<UploadManifestFilesReturnType | UploadManifestFilesError>;
415
415
  /**
416
416
  * View detailed information about a specific patch by its UUID.
417
417
  *