@socketsecurity/sdk 3.0.19 → 3.0.20
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 +6 -0
- package/dist/constants.d.ts +3 -0
- package/dist/file-upload.d.ts +2 -0
- package/dist/index.mjs +58 -9
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,12 @@ 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
|
+
## [3.0.20](https://github.com/SocketDev/socket-sdk-js/releases/tag/v3.0.20) - 2025-10-30
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- Updated `@socketsecurity/lib` to v2.9.0
|
|
12
|
+
|
|
7
13
|
## [3.0.19](https://github.com/SocketDev/socket-sdk-js/releases/tag/v3.0.19) - 2025-10-30
|
|
8
14
|
|
|
9
15
|
### Changed
|
package/dist/constants.d.ts
CHANGED
|
@@ -8,5 +8,8 @@ export declare const MIN_HTTP_TIMEOUT = 5000;
|
|
|
8
8
|
export declare const MAX_RESPONSE_SIZE: number;
|
|
9
9
|
export declare const MAX_STREAM_SIZE: number;
|
|
10
10
|
export declare const SOCKET_PUBLIC_BLOB_STORE_URL = "https://socketusercontent.com";
|
|
11
|
+
export declare const SOCKET_CONTACT_URL = "https://socket.dev/contact";
|
|
12
|
+
export declare const SOCKET_DASHBOARD_URL = "https://socket.dev/dashboard";
|
|
13
|
+
export declare const SOCKET_API_TOKENS_URL = "https://socket.dev/dashboard/settings/api-tokens";
|
|
11
14
|
export declare const httpAgentNames: Set<string>;
|
|
12
15
|
export declare const publicPolicy: Map<"ambiguousClassifier" | "badEncoding" | "badSemver" | "badSemverDependency" | "bidi" | "binScriptConfusion" | "chromeContentScript" | "chromeHostPermission" | "chromePermission" | "chromeWildcardHostPermission" | "chronoAnomaly" | "compromisedSSHKey" | "copyleftLicense" | "criticalCVE" | "cve" | "debugAccess" | "deprecated" | "deprecatedException" | "deprecatedLicense" | "didYouMean" | "dynamicRequire" | "emptyPackage" | "envVars" | "explicitlyUnlicensedItem" | "extraneousDependency" | "fileDependency" | "filesystemAccess" | "floatingDependency" | "generic" | "ghaArgToEnv" | "ghaArgToOutput" | "ghaArgToSink" | "ghaContextToEnv" | "ghaContextToOutput" | "ghaContextToSink" | "ghaEnvToSink" | "gitDependency" | "gitHubDependency" | "gptAnomaly" | "gptDidYouMean" | "gptMalware" | "gptSecurity" | "hasNativeCode" | "highEntropyStrings" | "homoglyphs" | "httpDependency" | "installScripts" | "invalidPackageJSON" | "invisibleChars" | "licenseChange" | "licenseException" | "licenseSpdxDisj" | "longStrings" | "majorRefactor" | "malware" | "manifestConfusion" | "mediumCVE" | "mildCVE" | "minifiedFile" | "miscLicenseIssues" | "missingAuthor" | "missingDependency" | "missingLicense" | "missingTarball" | "mixedLicense" | "modifiedException" | "modifiedLicense" | "networkAccess" | "newAuthor" | "noAuthorData" | "noBugTracker" | "noLicenseFound" | "noREADME" | "noRepository" | "noTests" | "noV1" | "noWebsite" | "nonOSILicense" | "nonSPDXLicense" | "nonpermissiveLicense" | "notice" | "obfuscatedFile" | "obfuscatedRequire" | "peerDependency" | "potentialVulnerability" | "semverAnomaly" | "shellAccess" | "shellScriptOverride" | "shrinkwrap" | "socketUpgradeAvailable" | "suspiciousStarActivity" | "suspiciousString" | "telemetry" | "trivialPackage" | "troll" | "typeModuleCompatibility" | "uncaughtOptionalDependency" | "unclearLicense" | "unidentifiedLicense" | "unmaintained" | "unpopularPackage" | "unpublished" | "unresolvedRequire" | "unsafeCopyright" | "unstableOwnership" | "unusedDependency" | "urlStrings" | "usesEval" | "vsxActivationWildcard" | "vsxDebuggerContribution" | "vsxExtensionDependency" | "vsxExtensionPack" | "vsxProposedApiUsage" | "vsxUntrustedWorkspaceSupported" | "vsxVirtualWorkspaceSupported" | "vsxWebviewContribution" | "vsxWorkspaceContainsActivation" | "zeroWidth", ALERT_ACTION>;
|
package/dist/file-upload.d.ts
CHANGED
|
@@ -5,6 +5,8 @@ import type { IncomingMessage } from 'node:http';
|
|
|
5
5
|
/**
|
|
6
6
|
* Create multipart form-data body parts for file uploads.
|
|
7
7
|
* Converts file paths to readable streams with proper multipart headers.
|
|
8
|
+
*
|
|
9
|
+
* @throws {Error} When file cannot be read (ENOENT, EACCES, EISDIR, etc.)
|
|
8
10
|
*/
|
|
9
11
|
export declare function createRequestBodyForFilepaths(filepaths: string[], basePath: string): Array<Array<string | ReadStream>>;
|
|
10
12
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -1,14 +1,63 @@
|
|
|
1
1
|
/* Socket SDK ESM - Built with esbuild */
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
var X={name:"@socketsecurity/sdk",version:"3.0.20",license:"MIT",description:"SDK for the Socket API client",author:{name:"Socket Inc",email:"eng@socket.dev",url:"https://socket.dev"},homepage:"https://github.com/SocketDev/socket-sdk-js",repository:{type:"git",url:"git://github.com/SocketDev/socket-sdk-js.git"},type:"module",main:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.mjs"},"./package.json":"./package.json","./testing":{types:"./dist/testing.d.ts",default:"./dist/testing.mjs"},"./types/api":{types:"./types/api.d.ts",default:"./types/api.d.ts"},"./types/api-helpers":{types:"./types/api-helpers.d.ts",default:"./types/api-helpers.d.ts"}},scripts:{build:"node scripts/build.mjs",bump:"node scripts/bump.mjs",check:"node scripts/check.mjs",clean:"node scripts/clean.mjs",cover:"node scripts/cover.mjs",fix:"node scripts/lint.mjs --fix","generate-sdk":"node scripts/generate-sdk.mjs",lint:"node scripts/lint.mjs",precommit:"pnpm run check --lint --staged",prepare:"husky",prepublishOnly:"echo 'ERROR: Use GitHub Actions workflow for publishing' && exit 1",publish:"node scripts/publish.mjs",claude:"node scripts/claude.mjs",test:"node scripts/test.mjs",type:"tsgo --noEmit -p .config/tsconfig.check.json",update:"node scripts/update.mjs"},dependencies:{"@socketsecurity/lib":"2.9.0"},devDependencies:{"@babel/parser":"7.26.3","@babel/traverse":"7.26.4","@babel/types":"7.26.3","@biomejs/biome":"2.2.4","@dotenvx/dotenvx":"1.49.0","@eslint/compat":"1.3.2","@eslint/js":"9.35.0","@types/node":"24.6.2","@typescript/native-preview":"7.0.0-dev.20250926.1","@vitest/coverage-v8":"4.0.3",del:"8.0.1","dev-null-cli":"2.0.0",esbuild:"0.25.10",eslint:"9.35.0","eslint-import-resolver-typescript":"4.4.4","eslint-plugin-import-x":"4.16.1","eslint-plugin-jsdoc":"57.0.8","eslint-plugin-n":"17.23.1","eslint-plugin-sort-destructure-keys":"2.0.0","eslint-plugin-unicorn":"56.0.1","fast-glob":"3.3.3",globals:"16.4.0","http2-wrapper":"2.2.1",husky:"9.1.7","magic-string":"0.30.14",nock:"14.0.10","npm-run-all2":"8.0.4","openapi-typescript":"6.7.6",semver:"7.7.2",taze:"19.6.0","type-coverage":"2.29.7","typescript-eslint":"8.44.1",vitest:"4.0.3","yoctocolors-cjs":"2.1.3"},pnpm:{ignoredBuiltDependencies:["esbuild","unrs-resolver"],overrides:{vite:"7.1.12"}},engines:{node:">=18",pnpm:">=10.16.0"},files:["CHANGELOG.md","data/*.json","dist/*.d.ts","dist/*.js","dist/*.mjs","types/*.d.ts"],typeCoverage:{cache:!0,atLeast:99,ignoreAsAssertion:!0,ignoreCatch:!0,ignoreEmptyType:!0,"ignore-non-null-assertion":!0,"ignore-type-assertion":!0,"ignore-files":"test/*",strict:!0}};function x(o){let{homepage:t}=o;return`${o.name.replace("@","").replace("/","-")}/${o.version}${t?` (${t})`:""}`}var q=x(X),Z=3e4,ee=3,te=1e3,B=300*1e3,N=5e3,j=10*1024*1024,$=100*1024*1024,se="https://socketusercontent.com",re="https://socket.dev/contact",ne="https://socket.dev/dashboard",oe="https://socket.dev/dashboard/settings/api-tokens",G=new Set(["http","https","http2"]),fe=new Map([["malware","error"],["criticalCVE","warn"],["didYouMean","warn"],["gitDependency","warn"],["httpDependency","warn"],["licenseSpdxDisj","warn"],["obfuscatedFile","warn"],["troll","warn"],["deprecated","monitor"],["mediumCVE","monitor"],["mildCVE","monitor"],["shrinkwrap","monitor"],["telemetry","monitor"],["unpopularPackage","monitor"],["unstableOwnership","monitor"],["ambiguousClassifier","ignore"],["badEncoding","ignore"],["badSemver","ignore"],["badSemverDependency","ignore"],["bidi","ignore"],["binScriptConfusion","ignore"],["chromeContentScript","ignore"],["chromeHostPermission","ignore"],["chromePermission","ignore"],["chromeWildcardHostPermission","ignore"],["chronoAnomaly","ignore"],["compromisedSSHKey","ignore"],["copyleftLicense","ignore"],["cve","ignore"],["debugAccess","ignore"],["deprecatedLicense","ignore"],["deprecatedException","ignore"],["dynamicRequire","ignore"],["emptyPackage","ignore"],["envVars","ignore"],["explicitlyUnlicensedItem","ignore"],["extraneousDependency","ignore"],["fileDependency","ignore"],["filesystemAccess","ignore"],["floatingDependency","ignore"],["gitHubDependency","ignore"],["gptAnomaly","ignore"],["gptDidYouMean","ignore"],["gptMalware","ignore"],["gptSecurity","ignore"],["hasNativeCode","ignore"],["highEntropyStrings","ignore"],["homoglyphs","ignore"],["installScripts","ignore"],["invalidPackageJSON","ignore"],["invisibleChars","ignore"],["licenseChange","ignore"],["licenseException","ignore"],["longStrings","ignore"],["majorRefactor","ignore"],["manifestConfusion","ignore"],["minifiedFile","ignore"],["miscLicenseIssues","ignore"],["missingAuthor","ignore"],["missingDependency","ignore"],["missingLicense","ignore"],["missingTarball","ignore"],["mixedLicense","ignore"],["modifiedException","ignore"],["modifiedLicense","ignore"],["networkAccess","ignore"],["newAuthor","ignore"],["noAuthorData","ignore"],["noBugTracker","ignore"],["noLicenseFound","ignore"],["noREADME","ignore"],["noRepository","ignore"],["noTests","ignore"],["noV1","ignore"],["noWebsite","ignore"],["nonOSILicense","ignore"],["nonSPDXLicense","ignore"],["nonpermissiveLicense","ignore"],["notice","ignore"],["obfuscatedRequire","ignore"],["peerDependency","ignore"],["potentialVulnerability","ignore"],["semverAnomaly","ignore"],["shellAccess","ignore"],["shellScriptOverride","ignore"],["socketUpgradeAvailable","ignore"],["suspiciousStarActivity","ignore"],["suspiciousString","ignore"],["trivialPackage","ignore"],["typeModuleCompatibility","ignore"],["uncaughtOptionalDependency","ignore"],["unclearLicense","ignore"],["unidentifiedLicense","ignore"],["unmaintained","ignore"],["unpublished","ignore"],["unresolvedRequire","ignore"],["unsafeCopyright","ignore"],["unusedDependency","ignore"],["urlStrings","ignore"],["usesEval","ignore"],["zeroWidth","ignore"]]);import ae from"node:path";import{memoize as ye}from"@socketsecurity/lib/memoization";import{normalizePath as ie}from"@socketsecurity/lib/path";var Q=ye(o=>o.endsWith("/")?o:`${o}/`,{name:"normalizeBaseUrl"});function z(){if(Promise.withResolvers)return Promise.withResolvers();let o={};return o.promise=new Promise((t,e)=>{o.resolve=t,o.reject=e}),o}function k(o){let t=new URLSearchParams(o),e={__proto__:null},s=t.entries();for(let r of s){let n=r[0],a=r[1];n==="defaultBranch"?n="default_branch":n==="perPage"&&(n="per_page"),a&&(e[n]=a)}return new URLSearchParams(e)}function U(o,t){let e=I(t);return o.map(s=>ie(ae.resolve(e,s)))}function I(o="."){return ie(ae.resolve(process.cwd(),o))}import W from"node:events";import{createReadStream as ke}from"node:fs";import _ from"node:path";import{Readable as Pe}from"node:stream";import{normalizePath as Te}from"@socketsecurity/lib/path";import Re from"node:http";import Se from"node:https";import{debugLog as ce}from"@socketsecurity/lib/debug";import{jsonParse as we}from"@socketsecurity/lib/json";import{perfTimer as J}from"@socketsecurity/lib/performance";var R=class o extends Error{response;constructor(t,e=""){let s=t.statusCode??"unknown",r=t.statusMessage??"No status message";super(`Socket API ${e||"Request failed"} (${s}): ${r}`),this.name="ResponseError",this.response=t,Error.captureStackTrace(this,o)}};async function A(o,t,e){let s=P(o).request(`${o}${t}`,{method:"DELETE",...e}).end();return await T(s)}async function m(o,t,e){let s=J("http:get",{urlPath:t});try{let r=P(o).request(`${o}${t}`,{method:"GET",...e}).end(),n=await T(r);return s({statusCode:n.statusCode}),n}catch(r){throw s({error:!0}),r}}async function y(o,t,e,s,r){let n=J(`http:${o.toLowerCase()}`,{urlPath:e});try{let a=JSON.stringify(s),i=P(t).request(`${t}${e}`,{method:o,...r,headers:{...r.headers,"Content-Length":Buffer.byteLength(a,"utf8"),"Content-Type":"application/json"}});i.write(a),i.end();let c=await T(i);return n({statusCode:c.statusCode}),c}catch(a){throw n({error:!0}),a}}async function L(o){return await new Promise((t,e)=>{let s="",r=0;o.setEncoding("utf8"),o.on("data",n=>{let a=Buffer.byteLength(n,"utf8");if(r+=a,r>j){o.destroy();let i=(r/(1024*1024)).toFixed(2),c=(j/(1024*1024)).toFixed(2),u=[`Response exceeds maximum size limit (${i}MB > ${c}MB)`,"\u2192 The API response is too large to process safely.","\u2192 Try: Use pagination parameters (limit, offset) to reduce response size.","\u2192 Try: Request specific fields instead of full objects.","\u2192 Contact support if you need to process larger responses."].join(`
|
|
3
|
+
`);e(new Error(u));return}s+=n}),o.on("end",()=>t(s)),o.on("error",n=>e(n))})}function P(o){return o.startsWith("https:")?Se:Re}async function T(o){return await new Promise((t,e)=>{let s=!1;o.on("response",r=>{s||t(r)}),o.on("timeout",()=>{s=!0,o.destroy();let r=o.method||"REQUEST",n=o.path||"unknown",a=o.timeout||"configured timeout",i=[`${r} request timed out after ${a}ms: ${n}`,"\u2192 The Socket API did not respond in time.","\u2192 Try: Increase timeout option or check network connectivity.","\u2192 If problem persists, Socket API may be experiencing issues."].join(`
|
|
4
|
+
`);e(new Error(i))}),o.on("error",r=>{if(!s){let n=r,a=o.method||"REQUEST",i=o.path||"unknown",c=`${a} request failed: ${i}`;n.code==="ECONNREFUSED"?c+=["","\u2192 Connection refused. Socket API server is unreachable.","\u2192 Check: Network connectivity and firewall settings.","\u2192 Verify: Base URL is correct (default: https://api.socket.dev)"].join(`
|
|
5
|
+
`):n.code==="ENOTFOUND"?c+=["","\u2192 DNS lookup failed. Cannot resolve hostname.","\u2192 Check: Internet connection and DNS settings.","\u2192 Verify: Base URL hostname is correct."].join(`
|
|
6
|
+
`):n.code==="ETIMEDOUT"?c+=["","\u2192 Connection timed out. Network or server issue.","\u2192 Try: Check network connectivity and retry.","\u2192 If using proxy, verify proxy configuration."].join(`
|
|
7
|
+
`):n.code==="ECONNRESET"?c+=["","\u2192 Connection reset by server. Possible network interruption.","\u2192 Try: Retry the request. Enable retries option if not set."].join(`
|
|
8
|
+
`):n.code==="EPIPE"?c+=["","\u2192 Broken pipe. Server closed connection unexpectedly.","\u2192 Possible: Authentication issue or server error.","\u2192 Check: API token is valid and has required permissions."].join(`
|
|
9
|
+
`):n.code==="CERT_HAS_EXPIRED"||n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"?c+=["","\u2192 SSL/TLS certificate error.","\u2192 Check: System time and date are correct.","\u2192 Try: Update CA certificates on your system."].join(`
|
|
10
|
+
`):n.code&&(c+=`
|
|
11
|
+
\u2192 Error code: ${n.code}`);let u=new Error(c,{cause:r});e(u)}})})}async function d(o,t){let e=J("http:parse-json");try{if(!O(o))throw new R(o,t?`${t} Request failed`:void 0);let s=await L(o);if(s==="")return ce("API response: empty response treated as {}"),e({success:!0}),{};try{let r=we(s);return ce("API response:",r),e({success:!0}),r}catch(r){if(e({error:!0}),r instanceof SyntaxError){let a=o.headers["content-type"],c=["Socket API returned invalid JSON response",`\u2192 Response preview: ${s.length>200?`${s.slice(0,200)}...`:s}`,`\u2192 Parse error: ${r.message}`];a&&!a.includes("application/json")?c.push(`\u2192 Unexpected Content-Type: ${a} (expected application/json)`,"\u2192 The API may have returned an error page instead of JSON."):s.startsWith("<")?c.push("\u2192 Response appears to be HTML, not JSON.","\u2192 This may indicate an API endpoint error or network interception."):s.length===0?c.push("\u2192 Response body is empty when JSON was expected."):(s.includes("502 Bad Gateway")||s.includes("503 Service"))&&c.push("\u2192 Response indicates a server error.","\u2192 The Socket API may be temporarily unavailable.");let u=new Error(c.join(`
|
|
12
|
+
`),{cause:r});throw u.name="SyntaxError",u.originalResponse=s,Object.setPrototypeOf(u,SyntaxError.prototype),u}if(r instanceof Error)throw r;let n=new Error("Unknown JSON parsing error",{cause:r});throw n.name="SyntaxError",n.originalResponse=s,Object.setPrototypeOf(n,SyntaxError.prototype),n}}catch(s){throw e({error:!0}),s}}function O(o){let{statusCode:t}=o;return t?t>=200&&t<300:!1}function M(o,t,e){if(!t){let s=e?e.split(","):void 0,r=n=>({name:n.name,version:n.version,size:n.size,author:n.author,type:n.type,supplyChainRisk:n.supplyChainRisk,scorecards:n.scorecards,topLevelAncestors:n.topLevelAncestors,alerts:n.alerts?.filter(a=>!(a.severity==="low"||s&&a.action&&!s.includes(a.action))).map(a=>({type:a.type,severity:a.severity,key:a.key}))});if(o.artifacts){let n=o.artifacts;return{...o,artifacts:Array.isArray(n)?n.map(r):n}}if(o.alerts)return r(o)}return o}function v(o,t){let e=[];for(let s of o){let r=Te(_.relative(t,s)),n=_.basename(s),a;try{a=ke(s,{highWaterMark:1024*1024})}catch(i){let c=i,u=`Failed to read file: ${s}`;throw c.code==="ENOENT"?u+=`
|
|
13
|
+
\u2192 File does not exist. Check the file path and try again.`:c.code==="EACCES"?u+=`
|
|
14
|
+
\u2192 Permission denied. Run: chmod +r "${s}"`:c.code==="EISDIR"?u+=`
|
|
15
|
+
\u2192 Expected a file but found a directory.`:c.code&&(u+=`
|
|
16
|
+
\u2192 Error code: ${c.code}`),new Error(u,{cause:i})}e.push([`Content-Disposition: form-data; name="${r}"; filename="${n}"\r
|
|
5
17
|
`,`Content-Type: application/octet-stream\r
|
|
6
18
|
\r
|
|
7
|
-
`,
|
|
19
|
+
`,a])}return e}function Ee(o,t="data.json"){let e=_.extname(t);return[`Content-Disposition: form-data; name="${_.basename(t,e)}"; filename="${t}"\r
|
|
8
20
|
Content-Type: application/json\r
|
|
9
21
|
\r
|
|
10
|
-
`,
|
|
11
|
-
`]}async function F(
|
|
12
|
-
`,
|
|
13
|
-
`,
|
|
14
|
-
`)&&await J.once(h,"drain"),typeof p.destroy=="function"&&p.destroy()}else throw new TypeError('Expected "string" or "stream" type')}}catch(p){h.destroy(p),n(p)}finally{g||h.end()}})}import{existsSync as ke,readFileSync as Te}from"node:fs";import{join as Oe}from"node:path";import{memoize as A,once as be}from"@socketsecurity/lib/memoization";var b=be(()=>{try{let a=Oe(__dirname,"..","data","api-method-quota-and-permissions.json");if(!ke(a))throw new Error(`Requirements file not found at: ${a}`);let e=Te(a,"utf8");return JSON.parse(e)}catch(a){throw new Error("Failed to load SDK method requirements",{cause:a})}});function oe(a){return a.reduce((e,t)=>e+ie(t),0)}function Ee(){let a=b(),e={};return Object.entries(a.api).forEach(([t,s])=>{e[t]={permissions:[...s.permissions],quota:s.quota}}),e}var Ie=A(a=>{let t=b().api[a];if(!t)throw new Error(`Unknown SDK method: "${String(a)}"`);return{permissions:[...t.permissions],quota:t.quota}},{name:"getMethodRequirements"}),Ae=A(a=>{let e=b();return Object.entries(e.api).filter(([,t])=>a.some(s=>t.permissions.includes(s))).map(([t])=>t).sort()},{name:"getMethodsByPermissions"}),Ce=A(a=>{let e=b();return Object.entries(e.api).filter(([,t])=>t.quota===a).map(([t])=>t).sort()},{name:"getMethodsByQuotaCost"}),ie=A(a=>{let t=b().api[a];if(!t)throw new Error(`Unknown SDK method: "${String(a)}"`);return t.quota},{name:"getQuotaCost"}),Ue=A(()=>{let a=b(),e={};return Object.entries(a.api).forEach(([t,s])=>{let r=`${s.quota} units`;e[r]||(e[r]=[]),e[r].push(t)}),Object.keys(e).forEach(t=>{e[t]?.sort()}),e},{name:"getQuotaUsageSummary"}),$e=A(a=>{let t=b().api[a];if(!t)throw new Error(`Unknown SDK method: "${String(a)}"`);return[...t.permissions]},{name:"getRequiredPermissions"});function Fe(a,e){let t=oe(e);return a>=t}import{createWriteStream as Le}from"node:fs";import H from"node:readline";import{createTtlCache as xe}from"@socketsecurity/lib/cache-with-ttl";import{UNKNOWN_ERROR as X}from"@socketsecurity/lib/constants/core";import{getAbortSignal as ve}from"@socketsecurity/lib/constants/process";import{SOCKET_PUBLIC_API_TOKEN as ce}from"@socketsecurity/lib/constants/socket";import{debugLog as le,isDebugNs as Me}from"@socketsecurity/lib/debug";import{validateFiles as Y}from"@socketsecurity/lib/fs";import{jsonParse as ue}from"@socketsecurity/lib/json";import{getOwn as qe,isObjectObject as de}from"@socketsecurity/lib/objects";import{pRetry as De}from"@socketsecurity/lib/promises";import{setMaxEventTargetListeners as _e}from"@socketsecurity/lib/suppress-warnings";import{urlSearchParamAsBoolean as Be}from"@socketsecurity/lib/url";var q=ve(),V=class{#o;#e;#i;#a;#t;#c;#u;constructor(e,t){if(typeof e!="string")throw new TypeError('"apiToken" is required and must be a string');let r=e.trim();if(!r)throw new Error('"apiToken" cannot be empty or whitespace-only');if(r.length>1024)throw new Error('"apiToken" exceeds maximum length of 1024 characters');let{agent:n,baseUrl:o="https://api.socket.dev/v0/",cache:i=!1,cacheTtl:u=300*1e3,onFileValidation:d,retries:m=ee,retryDelay:h=te,timeout:g=Z,userAgent:p}={__proto__:null,...t};if(g!==void 0&&(typeof g!="number"||g<N||g>B))throw new TypeError(`"timeout" must be a number between ${N} and ${B} milliseconds`);let f=n?Object.keys(n):[],w=n,T=f.length&&f.every(D=>Q.has(D))?w.https||w.http||w.http2:n;this.#o=r,this.#e=G(o),this.#i=i?xe({memoize:!0,prefix:"socket-sdk",ttl:u}):void 0,this.#a=d,this.#c=m,this.#u=h,this.#t={...T?{agent:T}:{},headers:{Authorization:`Basic ${btoa(`${r}:`)}`,"User-Agent":p??_},signal:q,...g?{timeout:g}:{}}}#p(e){if(!e)return;let t=Array.isArray(e)?e[0]:e;if(!t)return;let s=Number.parseInt(t,10);if(!Number.isNaN(s)&&s>=0)return s*1e3;let r=new Date(t);if(!Number.isNaN(r.getTime())){let n=r.getTime()-Date.now();if(n>0)return n}}async#r(e){let t=await De(e,{baseDelayMs:this.#u,onRetry:(s,r,n)=>{if(!(r instanceof R))return;let{statusCode:o}=r.response;if(o===401||o===403)throw r;if(o===429){let i=this.#p(r.response.headers["retry-after"]);if(i!==void 0)return i}},onRetryRethrow:!0,retries:this.#c});if(t===void 0)throw new Error("Request aborted");return t}async#d(e,t){return this.#i?await this.#i.getOrFetch(e,async()=>await this.#r(t)):await this.#r(t)}async*#g(e,t){let s;try{s=await this.#r(()=>this.#l(e,t))}catch(o){yield await this.#s(o);return}if(!s)throw new Error("Failed to get response from batch PURL request");let r=H.createInterface({input:s,crlfDelay:Number.POSITIVE_INFINITY,signal:q}),n=this.#o===ce;for await(let o of r){let u=o.trim()?ue(o,{throws:!1}):null;de(u)&&(yield this.#n(n?v(u,!1,t?.actions):u))}}async#l(e,t){let s=P(this.#e).request(`${this.#e}purl?${S(t)}`,{method:"POST",...this.#t}).end(JSON.stringify(e)),r=await k(s);if(!O(r))throw new R(r);return r}#m(e){if(e instanceof SyntaxError){let r=e.originalResponse||"";return r||(r=e.message.match(/Invalid JSON response:\n([\s\S]*?)\n→/)?.[1]||""),{cause:`Please report this. JSON.parse threw an error over the following response: \`${(r.slice(0,100)||"").trim()}${r.length>100?"\u2026":""}\``,data:void 0,error:"Server returned invalid JSON",status:0,success:!1}}return{cause:(e?String(e).trim():"")||X,data:void 0,error:"API request failed",status:0,success:!1}}async#h(e){let t=[],s=0,r=50*1024*1024;for await(let n of e){if(s+=n.length,s>r)throw new Error("Response body exceeds maximum size limit");t.push(n)}return Buffer.concat(t).toString("utf8")}async#s(e){if(!(e instanceof R))throw new Error("Unexpected Socket API error",{cause:e});let{statusCode:t}=e.response;if(t&&t>=500)throw new Error(`Socket API server error (${t})`,{cause:e});let s=await x(e.response),r;try{let i=JSON.parse(s);if(typeof i?.error?.message=="string"&&(r=i.error.message,i.error.details)){let u=typeof i.error.details=="string"?i.error.details:JSON.stringify(i.error.details);r=`${r} - Details: ${u}`}}catch{r=s}let n=e.message??X,o=r?.trim();if(o&&!n.includes(o)){let i=e.response?.statusMessage;i&&n.includes(i)?n=n.replace(i,o):n=`${n}: ${o}`}return{cause:r,data:void 0,error:n,status:t??0,success:!1}}#n(e){return{cause:void 0,data:e,error:void 0,status:200,success:!0}}async#y(e,t){return t==="response"?e:t==="text"?await this.#h(e):t==="json"?await c(e):e}async batchPackageFetch(e,t){let s;try{s=await this.#l(e,t)}catch(u){return await this.#s(u)}if(!s)throw new Error("Failed to get response from batch PURL request");let r=H.createInterface({input:s,crlfDelay:Number.POSITIVE_INFINITY,signal:q}),n=this.#o===ce,o=[];for await(let u of r){let m=u.trim()?ue(u,{throws:!1}):null;de(m)&&o.push(n?v(m,!1,t?.actions):m)}let i=Be(qe(t,"compact"));return this.#n(o)}async*batchPackageStream(e,t){let{chunkSize:s=100,concurrencyLimit:r=10,queryParams:n}={__proto__:null,...t},o=r*2;_e(q,o);let{components:i}=e,{length:u}=i,d=[],m=0,h=()=>{if(m>=u)return;let p=this.#g({components:i.slice(m,m+s)},n);g(p),m+=s},g=p=>{let{promise:f,reject:w,resolve:T}=z();d.push({generator:p,promise:f}),p.next().then(D=>T({generator:p,iteratorResult:D}),w)};for(;d.length<r&&m<u;)h();for(;d.length>0;){let{generator:p,iteratorResult:f}=await Promise.race(d.map(T=>T.promise)),w=d.findIndex(T=>T.generator===p);w!==-1&&(d.splice(w,1),f.value&&(yield f.value),f.done?h():g(p))}}async createDependenciesSnapshot(e,t){let{pathsRelativeTo:s=".",queryParams:r}={__proto__:null,...t},n=E(s),o=U(e,n),{invalidPaths:i,validPaths:u}=Y(o);if(this.#a&&i.length>0){let d=await this.#a(u,i,{operation:"createDependenciesSnapshot"});if(!d.shouldContinue)return{cause:d.errorCause,data:void 0,error:d.errorMessage??"File validation failed",status:400,success:!1}}if(!this.#a&&i.length>0&&console.warn(`Warning: ${i.length} files skipped (unreadable). This may occur with Yarn Berry PnP or pnpm symlinks.`),u.length===0)return{cause:"All files failed validation. This may occur with Yarn Berry PnP virtual filesystem. Try: Run `yarn install` or use `nodeLinker: node-modules` in .yarnrc.yml",data:void 0,error:"No readable manifest files found",status:400,success:!1};try{let d=await this.#r(async()=>await c(await F(this.#e,`dependencies/upload?${S(r)}`,$(u,n),this.#t)));return this.#n(d)}catch(d){return await this.#s(d)}}async createOrgDiffScanFromIds(e,t){try{let s=await this.#r(async()=>await c(await y("POST",this.#e,`orgs/${encodeURIComponent(e)}/diff-scans?${S(t)}`,{},this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async createFullScan(e,t,s){let{pathsRelativeTo:r=".",...n}={__proto__:null,...s},o=E(r),i=U(t,o),{invalidPaths:u,validPaths:d}=Y(i);if(this.#a&&u.length>0){let m=await this.#a(d,u,{operation:"createOrgFullScan",orgSlug:e});if(!m.shouldContinue)return{cause:m.errorCause,data:void 0,error:m.errorMessage??"File validation failed",status:400,success:!1}}if(!this.#a&&u.length>0&&console.warn(`Warning: ${u.length} files skipped (unreadable). This may occur with Yarn Berry PnP or pnpm symlinks.`),d.length===0)return{cause:"All files failed validation. This may occur with Yarn Berry PnP virtual filesystem. Try: Run `yarn install` or use `nodeLinker: node-modules` in .yarnrc.yml",data:void 0,error:"No readable manifest files found",status:400,success:!1};try{return{cause:void 0,data:await this.#r(async()=>await c(await F(this.#e,`orgs/${encodeURIComponent(e)}/full-scans?${S(n)}`,$(d,o),this.#t))),error:void 0,status:200,success:!0}}catch(m){let h=await this.#s(m);return{cause:h.cause,data:void 0,error:h.error,status:h.status,success:!1}}}async createRepository(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await y("POST",this.#e,`orgs/${encodeURIComponent(e)}/repos`,t,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async createRepositoryLabel(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await y("POST",this.#e,`orgs/${encodeURIComponent(e)}/repos/labels`,t,this.#t))),error:void 0,status:201,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async deleteOrgDiffScan(e,t){try{let s=await this.#r(async()=>await c(await I(this.#e,`orgs/${encodeURIComponent(e)}/diff-scans/${encodeURIComponent(t)}`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async deleteFullScan(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await I(this.#e,`orgs/${encodeURIComponent(e)}/full-scans/${encodeURIComponent(t)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async deleteRepository(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await I(this.#e,`orgs/${encodeURIComponent(e)}/repos/${encodeURIComponent(t)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async deleteRepositoryLabel(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await I(this.#e,`orgs/${encodeURIComponent(e)}/repos/labels/${encodeURIComponent(t)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async exportCDX(e,t){try{let s=await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/full-scans/${encodeURIComponent(t)}/sbom/export/cdx`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async exportSPDX(e,t){try{let s=await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/full-scans/${encodeURIComponent(t)}/sbom/export/spdx`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getApi(e,t){let{responseType:s="response",throws:r=!0}={__proto__:null,...t};try{let n=await l(this.#e,e,this.#t);if(!O(n)){if(r)throw new R(n);let i=await this.#s(new R(n));return{cause:i.cause,data:void 0,error:i.error,status:i.status,success:!1}}let o=await this.#y(n,s);return r?o:{cause:void 0,data:o,error:void 0,status:n.statusCode??200,success:!0}}catch(n){if(r)throw n;if(n instanceof R){let o=await this.#s(n);return{cause:o.cause,data:void 0,error:o.error,status:o.status,success:!1}}return this.#m(n)}}async getAPITokens(e){try{let t=await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/tokens`,this.#t)));return this.#n(t)}catch(t){return await this.#s(t)}}async getAuditLogEvents(e,t){try{let s=await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/audit-log?${S(t)}`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getDiffScanById(e,t){try{let s=await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/diff-scans/${encodeURIComponent(t)}`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getEnabledEntitlements(e){return((await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/entitlements`,this.#t))))?.items||[]).filter(r=>r&&r.enabled===!0&&r.key).map(r=>r.key)}async getEntitlements(e){return(await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/entitlements`,this.#t))))?.items||[]}async getIssuesByNpmPackage(e,t){try{let s=await this.#r(async()=>await c(await l(this.#e,`npm/${encodeURIComponent(e)}/${encodeURIComponent(t)}/issues`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getOrgAnalytics(e){try{let t=await this.#r(async()=>await c(await l(this.#e,`analytics/org/${encodeURIComponent(e)}`,this.#t)));return this.#n(t)}catch(t){return await this.#s(t)}}async listOrganizations(){try{return{cause:void 0,data:await this.#d("organizations",async()=>await c(await l(this.#e,"organizations",this.#t))),error:void 0,status:200,success:!0}}catch(e){let t=await this.#s(e);return{cause:t.cause,data:void 0,error:t.error,status:t.status,success:!1}}}async getFullScan(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/full-scans/${encodeURIComponent(t)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async listFullScans(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/full-scans?${S(t)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async getFullScanMetadata(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/full-scans/${encodeURIComponent(t)}/metadata`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async getOrgLicensePolicy(e){try{let t=await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/settings/license-policy`,this.#t)));return this.#n(t)}catch(t){return await this.#s(t)}}async getRepository(e,t){let s=encodeURIComponent(e),r=encodeURIComponent(t);try{return{cause:void 0,data:await this.#r(async()=>await c(await l(this.#e,`orgs/${s}/repos/${r}`,this.#t))),error:void 0,status:200,success:!0}}catch(n){let o=await this.#s(n);return{cause:o.cause,data:void 0,error:o.error,status:o.status,success:!1}}}async getRepositoryLabel(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/repos/labels/${encodeURIComponent(t)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async listRepositoryLabels(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/repos/labels?${S(t)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async listRepositories(e,t){try{return{cause:void 0,data:await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/repos?${S(t)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async getOrgSecurityPolicy(e){try{let t=await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/settings/security-policy`,this.#t)));return this.#n(t)}catch(t){return await this.#s(t)}}async getOrgTriage(e){try{let t=await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/triage`,this.#t)));return this.#n(t)}catch(t){return await this.#s(t)}}async getQuota(){try{let e=await this.#d("quota",async()=>await c(await l(this.#e,"quota",this.#t)));return this.#n(e)}catch(e){return await this.#s(e)}}async getRepoAnalytics(e,t){try{let s=await this.#r(async()=>await c(await l(this.#e,`analytics/repo/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getScoreByNpmPackage(e,t){try{let s=await this.#r(async()=>await c(await l(this.#e,`npm/${encodeURIComponent(e)}/${encodeURIComponent(t)}/score`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getSupportedScanFiles(){try{let e=await this.#r(async()=>await c(await l(this.#e,"report/supported",this.#t)));return this.#n(e)}catch(e){return await this.#s(e)}}async listOrgDiffScans(e){try{let t=await this.#r(async()=>await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/diff-scans`,this.#t)));return this.#n(t)}catch(t){return await this.#s(t)}}async postAPIToken(e,t){try{let s=await this.#r(async()=>await c(await y("POST",this.#e,`orgs/${encodeURIComponent(e)}/tokens`,t,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async postAPITokensRevoke(e,t){try{let s=await this.#r(async()=>await c(await y("POST",this.#e,`orgs/${encodeURIComponent(e)}/tokens/${encodeURIComponent(t)}/revoke`,{},this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async postAPITokensRotate(e,t){try{let s=await this.#r(async()=>await c(await y("POST",this.#e,`orgs/${encodeURIComponent(e)}/tokens/${encodeURIComponent(t)}/rotate`,{},this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async postAPITokenUpdate(e,t,s){try{let r=await this.#r(async()=>await c(await y("POST",this.#e,`orgs/${encodeURIComponent(e)}/tokens/${encodeURIComponent(t)}/update`,s,this.#t)));return this.#n(r)}catch(r){return await this.#s(r)}}async postSettings(e){try{let t=await this.#r(async()=>await c(await y("POST",this.#e,"settings",{json:e},this.#t)));return this.#n(t)}catch(t){return await this.#s(t)}}async searchDependencies(e){try{let t=await this.#r(async()=>await c(await y("POST",this.#e,"dependencies/search",e,this.#t)));return this.#n(t)}catch(t){return await this.#s(t)}}async sendApi(e,t){let{body:s,method:r="POST",throws:n=!0}={__proto__:null,...t};try{let o=await y(r,this.#e,e,s,this.#t),i=await c(o);return n?i:{cause:void 0,data:i,error:void 0,status:o.statusCode??200,success:!0}}catch(o){if(n)throw o;if(o instanceof R){let u=await this.#s(o);return{cause:u.cause,data:void 0,error:u.error,status:u.status,success:!1}}return{cause:(o?String(o).trim():"")||X,data:void 0,error:"API request failed",status:0,success:!1}}}async streamFullScan(e,t,s){let{output:r}={__proto__:null,...s};try{let n=P(this.#e).request(`${this.#e}orgs/${encodeURIComponent(e)}/full-scans/${encodeURIComponent(t)}`,{method:"GET",...this.#t}).end(),o=await k(n);if(!O(o))throw new R(o);if(typeof r=="string"){let i=Le(r),u=0;o.on("data",d=>{if(u+=d.length,u>C)throw o.destroy(),i.destroy(),new Error(`Response exceeds maximum stream size of ${C} bytes`)}),o.pipe(i),i.on("error",d=>{throw new Error(`Failed to write to file: ${r}`,{cause:d})})}else if(r===!0){let i=0;o.on("data",u=>{if(i+=u.length,i>C)throw o.destroy(),new Error(`Response exceeds maximum stream size of ${C} bytes`)}),o.pipe(process.stdout),process.stdout.on("error",u=>{throw new Error("Failed to write to stdout",{cause:u})})}return this.#n(o)}catch(n){return await this.#s(n)}}async streamPatchesFromScan(e,t){let s=await this.#r(async()=>await l(this.#e,`orgs/${encodeURIComponent(e)}/patches/scan?scan_id=${encodeURIComponent(t)}`,this.#t));if(!O(s))throw new R(s,"GET Request failed");let r=H.createInterface({input:s,crlfDelay:Number.POSITIVE_INFINITY});return new ReadableStream({async start(n){try{for await(let o of r){let i=o.trim();if(i)try{let u=JSON.parse(i);n.enqueue(u)}catch(u){le("streamPatchesFromScan",`Failed to parse line: ${u}`)}}}catch(o){n.error(o)}finally{n.close()}}})}async updateOrgAlertTriage(e,t,s){try{let r=await this.#r(async()=>await c(await y("PUT",this.#e,`orgs/${encodeURIComponent(e)}/triage/${encodeURIComponent(t)}`,s,this.#t)));return this.#n(r)}catch(r){return await this.#s(r)}}async updateOrgLicensePolicy(e,t,s){try{let r=await this.#r(async()=>await c(await y("POST",this.#e,`orgs/${encodeURIComponent(e)}/settings/license-policy?${S(s)}`,t,this.#t)));return this.#n(r)}catch(r){return await this.#s(r)}}async updateRepository(e,t,s){try{return{cause:void 0,data:await this.#r(async()=>await c(await y("POST",this.#e,`orgs/${encodeURIComponent(e)}/repos/${encodeURIComponent(t)}`,s,this.#t))),error:void 0,status:200,success:!0}}catch(r){let n=await this.#s(r);return{cause:n.cause,data:void 0,error:n.error,status:n.status,success:!1}}}async updateRepositoryLabel(e,t,s){try{return{cause:void 0,data:await this.#r(async()=>await c(await y("PUT",this.#e,`orgs/${encodeURIComponent(e)}/repos/labels/${encodeURIComponent(t)}`,s,this.#t))),error:void 0,status:200,success:!0}}catch(r){let n=await this.#s(r);return{cause:n.cause,data:void 0,error:n.error,status:n.status,success:!1}}}async updateOrgSecurityPolicy(e,t){try{let s=await this.#r(async()=>await c(await y("POST",this.#e,`orgs/${encodeURIComponent(e)}/settings/security-policy`,t,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async uploadManifestFiles(e,t,s){let{pathsRelativeTo:r="."}={__proto__:null,...s},n=E(r),o=U(t,n),{invalidPaths:i,validPaths:u}=Y(o);if(this.#a&&i.length>0){let d=await this.#a(u,i,{operation:"uploadManifestFiles",orgSlug:e});if(!d.shouldContinue)return{error:d.errorMessage??"File validation failed",status:400,success:!1,...d.errorCause?{cause:d.errorCause}:{}}}if(!this.#a&&i.length>0&&console.warn(`Warning: ${i.length} files skipped (unreadable). This may occur with Yarn Berry PnP or pnpm symlinks.`),u.length===0)return{cause:"All files failed validation. This may occur with Yarn Berry PnP virtual filesystem. Try: Run `yarn install` or use `nodeLinker: node-modules` in .yarnrc.yml",error:"No readable manifest files found",status:400,success:!1};try{let d=await this.#r(async()=>await c(await F(this.#e,`orgs/${encodeURIComponent(e)}/upload-manifest-files`,$(u,n),this.#t)));return this.#n(d)}catch(d){return await this.#s(d)}}async viewPatch(e,t){return await c(await l(this.#e,`orgs/${encodeURIComponent(e)}/patches/view/${encodeURIComponent(t)}`,this.#t))}async downloadPatch(e,t){let s=await import("node:https"),r=await import("node:http"),n=`/blob/${encodeURIComponent(e)}`,i=`${t?.baseUrl||se}${n}`,u=i.startsWith("https:");return await new Promise((d,m)=>{(u?s:r).get(i,g=>{if(g.statusCode===404){m(new Error(`Blob not found: ${e}`));return}if(g.statusCode!==200){m(new Error(`Failed to download blob: ${g.statusCode} ${g.statusMessage}`));return}let p="";g.on("data",f=>{p+=f}),g.on("end",()=>{d(p)}),g.on("error",f=>{m(f)})}).on("error",g=>{m(new Error(`Error downloading blob ${e}: ${g.message}`))})})}};if(Me("heap")){let a=process.memoryUsage();le("heap",`heap used: ${Math.round(a.heapUsed/1024/1024)}MB`)}export{_ as DEFAULT_USER_AGENT,R as ResponseError,V as SocketSdk,oe as calculateTotalQuotaCost,I as createDeleteRequest,l as createGetRequest,$ as createRequestBodyForFilepaths,Pe as createRequestBodyForJson,y as createRequestWithJson,F as createUploadRequest,L as createUserAgentFromPkgJson,Ee as getAllMethodRequirements,x as getErrorResponseBody,P as getHttpModule,Ie as getMethodRequirements,Ae as getMethodsByPermissions,Ce as getMethodsByQuotaCost,ie as getQuotaCost,Ue as getQuotaUsageSummary,$e as getRequiredPermissions,k as getResponse,c as getResponseJson,Fe as hasQuotaForMethods,Q as httpAgentNames,O as isResponseOk,G as normalizeBaseUrl,z as promiseWithResolvers,ge as publicPolicy,S as queryToSearchParams,v as reshapeArtifactForPublicPolicy,U as resolveAbsPaths,E as resolveBasePath};
|
|
22
|
+
`,Pe.from(JSON.stringify(o),{highWaterMark:1024*1024}),`\r
|
|
23
|
+
`]}async function F(o,t,e,s){return await new Promise(async(r,n)=>{let a=`NodeMultipartBoundary${Date.now()}`,i=`--${a}\r
|
|
24
|
+
`,c=`--${a}--\r
|
|
25
|
+
`,u=[...e.flatMap(p=>[i,...Array.isArray(p)?p:[p]]),c],l=new URL(t,o),h=P(o).request(l,{method:"POST",...s,headers:{...s?.headers,"Content-Type":`multipart/form-data; boundary=${a}`}});h.flushHeaders(),T(h).then(r,n);let g=!1;h.on("error",()=>g=!0),h.on("close",()=>g=!0);try{for(let p of u){if(g)break;if(typeof p=="string")h.write(p)||await W.once(h,"drain");else if(typeof p?.pipe=="function"){let f=p;try{for await(let S of f){if(g)break;h.write(S)||await W.once(h,"drain")}}catch(S){let w=S,E="Failed to read file during upload";throw w.code==="ENOENT"?E+=`
|
|
26
|
+
\u2192 File was deleted during upload. Ensure files remain accessible during the upload process.`:w.code==="EACCES"?E+=`
|
|
27
|
+
\u2192 Permission denied while reading file. Check file permissions.`:w.code&&(E+=`
|
|
28
|
+
\u2192 Error code: ${w.code}`),new Error(E,{cause:S})}!g&&!h.write(`\r
|
|
29
|
+
`)&&await W.once(h,"drain"),typeof p.destroy=="function"&&p.destroy()}else throw new TypeError('Expected "string" or "stream" type')}}catch(p){h.destroy(p),n(p)}finally{g||h.end()}})}import{existsSync as Oe,readFileSync as be}from"node:fs";import{join as Ie}from"node:path";import{memoize as C,once as Ae}from"@socketsecurity/lib/memoization";var b=Ae(()=>{try{let o=Ie(__dirname,"..","data","api-method-quota-and-permissions.json");if(!Oe(o))throw new Error(`Requirements file not found at: ${o}`);let t=be(o,"utf8");return JSON.parse(t)}catch(o){throw new Error("Failed to load SDK method requirements",{cause:o})}});function ue(o){return o.reduce((t,e)=>t+de(e),0)}function Ce(){let o=b(),t={};return Object.entries(o.api).forEach(([e,s])=>{t[e]={permissions:[...s.permissions],quota:s.quota}}),t}var $e=C(o=>{let e=b().api[o];if(!e)throw new Error(`Unknown SDK method: "${String(o)}"`);return{permissions:[...e.permissions],quota:e.quota}},{name:"getMethodRequirements"}),Ue=C(o=>{let t=b();return Object.entries(t.api).filter(([,e])=>o.some(s=>e.permissions.includes(s))).map(([e])=>e).sort()},{name:"getMethodsByPermissions"}),ve=C(o=>{let t=b();return Object.entries(t.api).filter(([,e])=>e.quota===o).map(([e])=>e).sort()},{name:"getMethodsByQuotaCost"}),de=C(o=>{let e=b().api[o];if(!e)throw new Error(`Unknown SDK method: "${String(o)}"`);return e.quota},{name:"getQuotaCost"}),Fe=C(()=>{let o=b(),t={};return Object.entries(o.api).forEach(([e,s])=>{let r=`${s.quota} units`;t[r]||(t[r]=[]),t[r].push(e)}),Object.keys(t).forEach(e=>{t[e]?.sort()}),t},{name:"getQuotaUsageSummary"}),xe=C(o=>{let e=b().api[o];if(!e)throw new Error(`Unknown SDK method: "${String(o)}"`);return[...e.permissions]},{name:"getRequiredPermissions"});function Le(o,t){let e=ue(t);return o>=e}import{createWriteStream as Me}from"node:fs";import H from"node:readline";import{createTtlCache as _e}from"@socketsecurity/lib/cache-with-ttl";import{UNKNOWN_ERROR as K}from"@socketsecurity/lib/constants/core";import{getAbortSignal as De}from"@socketsecurity/lib/constants/process";import{SOCKET_PUBLIC_API_TOKEN as le}from"@socketsecurity/lib/constants/socket";import{debugLog as ge,isDebugNs as qe}from"@socketsecurity/lib/debug";import{validateFiles as V}from"@socketsecurity/lib/fs";import{jsonParse as pe}from"@socketsecurity/lib/json";import{getOwn as Be,isObjectObject as me}from"@socketsecurity/lib/objects";import{pRetry as Ne}from"@socketsecurity/lib/promises";import{setMaxEventTargetListeners as je}from"@socketsecurity/lib/suppress-warnings";import{urlSearchParamAsBoolean as Ge}from"@socketsecurity/lib/url";var D=De(),Y=class{#a;#e;#i;#o;#t;#c;#u;constructor(t,e){if(typeof t!="string")throw new TypeError('"apiToken" is required and must be a string');let r=t.trim();if(!r)throw new Error('"apiToken" cannot be empty or whitespace-only');if(r.length>1024)throw new Error('"apiToken" exceeds maximum length of 1024 characters');let{agent:n,baseUrl:a="https://api.socket.dev/v0/",cache:i=!1,cacheTtl:c=300*1e3,onFileValidation:u,retries:l=ee,retryDelay:h=te,timeout:g=Z,userAgent:p}={__proto__:null,...e};if(g!==void 0&&(typeof g!="number"||g<N||g>B))throw new TypeError(`"timeout" must be a number between ${N} and ${B} milliseconds`);let f=n?Object.keys(n):[],S=n,w=f.length&&f.every(E=>G.has(E))?S.https||S.http||S.http2:n;this.#a=r,this.#e=Q(a),this.#i=i?_e({memoize:!0,prefix:"socket-sdk",ttl:c}):void 0,this.#o=u,this.#c=l,this.#u=h,this.#t={...w?{agent:w}:{},headers:{Authorization:`Basic ${btoa(`${r}:`)}`,"User-Agent":p??q},signal:D,...g?{timeout:g}:{}}}#p(t){if(!t)return;let e=Array.isArray(t)?t[0]:t;if(!e)return;let s=Number.parseInt(e,10);if(!Number.isNaN(s)&&s>=0)return s*1e3;let r=new Date(e);if(!Number.isNaN(r.getTime())){let n=r.getTime()-Date.now();if(n>0)return n}}async#r(t){let e=await Ne(t,{baseDelayMs:this.#u,onRetry:(s,r,n)=>{if(!(r instanceof R))return;let{statusCode:a}=r.response;if(a===401||a===403)throw r;if(a===429){let i=this.#p(r.response.headers["retry-after"]);if(i!==void 0)return i}},onRetryRethrow:!0,retries:this.#c});if(e===void 0)throw new Error("Request aborted");return e}async#d(t,e){return this.#i?await this.#i.getOrFetch(t,async()=>await this.#r(e)):await this.#r(e)}async*#m(t,e){let s;try{s=await this.#r(()=>this.#l(t,e))}catch(a){yield await this.#s(a);return}if(!s)throw new Error("Failed to get response from batch PURL request");let r=H.createInterface({input:s,crlfDelay:Number.POSITIVE_INFINITY,signal:D}),n=this.#a===le;for await(let a of r){let c=a.trim()?pe(a,{throws:!1}):null;me(c)&&(yield this.#n(n?M(c,!1,e?.actions):c))}}async#l(t,e){let s=P(this.#e).request(`${this.#e}purl?${k(e)}`,{method:"POST",...this.#t}).end(JSON.stringify(t)),r=await T(s);if(!O(r))throw new R(r);return r}#g(t){if(t instanceof SyntaxError){let r=t.originalResponse||"";return r||(r=t.message.match(/Invalid JSON response:\n([\s\S]*?)\n→/)?.[1]||""),{cause:`Please report this. JSON.parse threw an error over the following response: \`${(r.slice(0,100)||"").trim()}${r.length>100?"\u2026":""}\``,data:void 0,error:"Server returned invalid JSON",status:0,success:!1}}return{cause:(t?String(t).trim():"")||K,data:void 0,error:"API request failed",status:0,success:!1}}async#h(t){let e=[],s=0,r=50*1024*1024;for await(let n of t){if(s+=n.length,s>r)throw new Error("Response body exceeds maximum size limit");e.push(n)}return Buffer.concat(e).toString("utf8")}async#s(t){if(!(t instanceof R))throw new Error("Unexpected Socket API error",{cause:t});let{statusCode:e}=t.response;if(e&&e>=500)throw new Error(`Socket API server error (${e})`,{cause:t});let s=await L(t.response),r;try{let u=JSON.parse(s);if(typeof u?.error?.message=="string"&&(r=u.error.message,u.error.details)){let l=typeof u.error.details=="string"?u.error.details:JSON.stringify(u.error.details);r=`${r} - Details: ${l}`}}catch{r=s}let n=t.message??K,a=r?.trim();if(a&&!n.includes(a)){let u=t.response?.statusMessage;u&&n.includes(u)?n=n.replace(u,a):n=`${n}: ${a}`}let i;if(e===401)i=["\u2192 Authentication failed. API token is invalid or expired.","\u2192 Check: Your API token is correct and active.",`\u2192 Generate a new token at: ${oe}`].join(`
|
|
30
|
+
`);else if(e===403)i=["\u2192 Authorization failed. Insufficient permissions.","\u2192 Check: Your API token has required permissions for this operation.","\u2192 Check: You have access to the specified organization/repository.",`\u2192 Verify: Organization settings at ${ne}`].join(`
|
|
31
|
+
`);else if(e===404)i=["\u2192 Resource not found.","\u2192 Verify: Package name, version, or resource ID is correct.","\u2192 Check: Organization or repository exists and is accessible."].join(`
|
|
32
|
+
`);else if(e===429){let u=t.response.headers["retry-after"];i=["\u2192 Rate limit exceeded. Too many requests.",`\u2192 ${u?`Retry after ${u} seconds.`:"Wait before retrying."}`,"\u2192 Try: Implement exponential backoff or enable SDK retry option.",`\u2192 Contact support to increase rate limits: ${re}`].join(`
|
|
33
|
+
`)}else e===400?i=["\u2192 Bad request. Invalid parameters or request body.","\u2192 Check: All required parameters are provided and correctly formatted.","\u2192 Verify: Package URLs (PURLs) follow correct format."].join(`
|
|
34
|
+
`):e===413&&(i=["\u2192 Payload too large. Request exceeds size limits.","\u2192 Try: Reduce the number of files or packages in a single request.","\u2192 Try: Use batch operations with smaller chunks."].join(`
|
|
35
|
+
`));return{cause:i?[a,"",i].filter(Boolean).join(`
|
|
36
|
+
`):r,data:void 0,error:n,status:e??0,success:!1}}#n(t){return{cause:void 0,data:t,error:void 0,status:200,success:!0}}async#f(t,e){return e==="response"?t:e==="text"?await this.#h(t):e==="json"?await d(t):t}async batchPackageFetch(t,e){let s;try{s=await this.#l(t,e)}catch(c){return await this.#s(c)}if(!s)throw new Error("Failed to get response from batch PURL request");let r=H.createInterface({input:s,crlfDelay:Number.POSITIVE_INFINITY,signal:D}),n=this.#a===le,a=[];for await(let c of r){let l=c.trim()?pe(c,{throws:!1}):null;me(l)&&a.push(n?M(l,!1,e?.actions):l)}let i=Ge(Be(e,"compact"));return this.#n(a)}async*batchPackageStream(t,e){let{chunkSize:s=100,concurrencyLimit:r=10,queryParams:n}={__proto__:null,...e},a=r*2;je(D,a);let{components:i}=t,{length:c}=i,u=[],l=0,h=()=>{if(l>=c)return;let p=this.#m({components:i.slice(l,l+s)},n);g(p),l+=s},g=p=>{let{promise:f,reject:S,resolve:w}=z();u.push({generator:p,promise:f}),p.next().then(E=>w({generator:p,iteratorResult:E}),S)};for(;u.length<r&&l<c;)h();for(;u.length>0;){let{generator:p,iteratorResult:f}=await Promise.race(u.map(w=>w.promise)),S=u.findIndex(w=>w.generator===p);S!==-1&&(u.splice(S,1),f.value&&(yield f.value),f.done?h():g(p))}}async createDependenciesSnapshot(t,e){let{pathsRelativeTo:s=".",queryParams:r}={__proto__:null,...e},n=I(s),a=U(t,n),{invalidPaths:i,validPaths:c}=V(a);if(this.#o&&i.length>0){let u=await this.#o(c,i,{operation:"createDependenciesSnapshot"});if(!u.shouldContinue)return{cause:u.errorCause,data:void 0,error:u.errorMessage??"File validation failed",status:400,success:!1}}if(!this.#o&&i.length>0){let u=i.slice(0,3).join(`
|
|
37
|
+
- `),l=i.length>3?`
|
|
38
|
+
... and ${i.length-3} more`:"";console.warn(`Warning: ${i.length} files skipped (unreadable):
|
|
39
|
+
- ${u}${l}
|
|
40
|
+
\u2192 This may occur with Yarn Berry PnP or pnpm symlinks.
|
|
41
|
+
\u2192 Try: Run installation command to ensure files are accessible.`)}if(c.length===0){let u=i.slice(0,5).join(`
|
|
42
|
+
- `),l=i.length>5?`
|
|
43
|
+
... and ${i.length-5} more`:"";return{cause:[`All ${i.length} files failed validation:`,` - ${u}${l}`,"","\u2192 Common causes:"," \u2022 Yarn Berry PnP virtual filesystem (files are not on disk)"," \u2022 pnpm symlinks pointing to inaccessible locations"," \u2022 Incorrect file permissions"," \u2022 Files were deleted after discovery","","\u2192 Solutions:"," \u2022 Yarn Berry: Use `nodeLinker: node-modules` in .yarnrc.yml"," \u2022 pnpm: Use `node-linker=hoisted` in .npmrc"," \u2022 Check file permissions with: ls -la <file>"," \u2022 Run package manager install command"].join(`
|
|
44
|
+
`),data:void 0,error:"No readable manifest files found",status:400,success:!1}}try{let u=await this.#r(async()=>await d(await F(this.#e,`dependencies/upload?${k(r)}`,v(c,n),this.#t)));return this.#n(u)}catch(u){return await this.#s(u)}}async createOrgDiffScanFromIds(t,e){try{let s=await this.#r(async()=>await d(await y("POST",this.#e,`orgs/${encodeURIComponent(t)}/diff-scans?${k(e)}`,{},this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async createFullScan(t,e,s){let{pathsRelativeTo:r=".",...n}={__proto__:null,...s},a=I(r),i=U(e,a),{invalidPaths:c,validPaths:u}=V(i);if(this.#o&&c.length>0){let l=await this.#o(u,c,{operation:"createOrgFullScan",orgSlug:t});if(!l.shouldContinue)return{cause:l.errorCause,data:void 0,error:l.errorMessage??"File validation failed",status:400,success:!1}}if(!this.#o&&c.length>0){let l=c.slice(0,3).join(`
|
|
45
|
+
- `),h=c.length>3?`
|
|
46
|
+
... and ${c.length-3} more`:"";console.warn(`Warning: ${c.length} files skipped (unreadable):
|
|
47
|
+
- ${l}${h}
|
|
48
|
+
\u2192 This may occur with Yarn Berry PnP or pnpm symlinks.
|
|
49
|
+
\u2192 Try: Run installation command to ensure files are accessible.`)}if(u.length===0){let l=c.slice(0,5).join(`
|
|
50
|
+
- `),h=c.length>5?`
|
|
51
|
+
... and ${c.length-5} more`:"";return{cause:[`All ${c.length} files failed validation:`,` - ${l}${h}`,"","\u2192 Common causes:"," \u2022 Yarn Berry PnP virtual filesystem (files are not on disk)"," \u2022 pnpm symlinks pointing to inaccessible locations"," \u2022 Incorrect file permissions"," \u2022 Files were deleted after discovery","","\u2192 Solutions:"," \u2022 Yarn Berry: Use `nodeLinker: node-modules` in .yarnrc.yml"," \u2022 pnpm: Use `node-linker=hoisted` in .npmrc"," \u2022 Check file permissions with: ls -la <file>"," \u2022 Run package manager install command"].join(`
|
|
52
|
+
`),data:void 0,error:"No readable manifest files found",status:400,success:!1}}try{return{cause:void 0,data:await this.#r(async()=>await d(await F(this.#e,`orgs/${encodeURIComponent(t)}/full-scans?${k(n)}`,v(u,a),this.#t))),error:void 0,status:200,success:!0}}catch(l){let h=await this.#s(l);return{cause:h.cause,data:void 0,error:h.error,status:h.status,success:!1}}}async createRepository(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await y("POST",this.#e,`orgs/${encodeURIComponent(t)}/repos`,e,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async createRepositoryLabel(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await y("POST",this.#e,`orgs/${encodeURIComponent(t)}/repos/labels`,e,this.#t))),error:void 0,status:201,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async deleteOrgDiffScan(t,e){try{let s=await this.#r(async()=>await d(await A(this.#e,`orgs/${encodeURIComponent(t)}/diff-scans/${encodeURIComponent(e)}`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async deleteFullScan(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await A(this.#e,`orgs/${encodeURIComponent(t)}/full-scans/${encodeURIComponent(e)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async deleteRepository(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await A(this.#e,`orgs/${encodeURIComponent(t)}/repos/${encodeURIComponent(e)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async deleteRepositoryLabel(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await A(this.#e,`orgs/${encodeURIComponent(t)}/repos/labels/${encodeURIComponent(e)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async exportCDX(t,e){try{let s=await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/full-scans/${encodeURIComponent(e)}/sbom/export/cdx`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async exportSPDX(t,e){try{let s=await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/full-scans/${encodeURIComponent(e)}/sbom/export/spdx`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getApi(t,e){let{responseType:s="response",throws:r=!0}={__proto__:null,...e};try{let n=await m(this.#e,t,this.#t);if(!O(n)){if(r)throw new R(n);let i=await this.#s(new R(n));return{cause:i.cause,data:void 0,error:i.error,status:i.status,success:!1}}let a=await this.#f(n,s);return r?a:{cause:void 0,data:a,error:void 0,status:n.statusCode??200,success:!0}}catch(n){if(r)throw n;if(n instanceof R){let a=await this.#s(n);return{cause:a.cause,data:void 0,error:a.error,status:a.status,success:!1}}return this.#g(n)}}async getAPITokens(t){try{let e=await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/tokens`,this.#t)));return this.#n(e)}catch(e){return await this.#s(e)}}async getAuditLogEvents(t,e){try{let s=await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/audit-log?${k(e)}`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getDiffScanById(t,e){try{let s=await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/diff-scans/${encodeURIComponent(e)}`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getEnabledEntitlements(t){return((await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/entitlements`,this.#t))))?.items||[]).filter(r=>r&&r.enabled===!0&&r.key).map(r=>r.key)}async getEntitlements(t){return(await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/entitlements`,this.#t))))?.items||[]}async getIssuesByNpmPackage(t,e){try{let s=await this.#r(async()=>await d(await m(this.#e,`npm/${encodeURIComponent(t)}/${encodeURIComponent(e)}/issues`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getOrgAnalytics(t){try{let e=await this.#r(async()=>await d(await m(this.#e,`analytics/org/${encodeURIComponent(t)}`,this.#t)));return this.#n(e)}catch(e){return await this.#s(e)}}async listOrganizations(){try{return{cause:void 0,data:await this.#d("organizations",async()=>await d(await m(this.#e,"organizations",this.#t))),error:void 0,status:200,success:!0}}catch(t){let e=await this.#s(t);return{cause:e.cause,data:void 0,error:e.error,status:e.status,success:!1}}}async getFullScan(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/full-scans/${encodeURIComponent(e)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async listFullScans(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/full-scans?${k(e)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async getFullScanMetadata(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/full-scans/${encodeURIComponent(e)}/metadata`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async getOrgLicensePolicy(t){try{let e=await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/settings/license-policy`,this.#t)));return this.#n(e)}catch(e){return await this.#s(e)}}async getRepository(t,e){let s=encodeURIComponent(t),r=encodeURIComponent(e);try{return{cause:void 0,data:await this.#r(async()=>await d(await m(this.#e,`orgs/${s}/repos/${r}`,this.#t))),error:void 0,status:200,success:!0}}catch(n){let a=await this.#s(n);return{cause:a.cause,data:void 0,error:a.error,status:a.status,success:!1}}}async getRepositoryLabel(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/repos/labels/${encodeURIComponent(e)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async listRepositoryLabels(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/repos/labels?${k(e)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async listRepositories(t,e){try{return{cause:void 0,data:await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/repos?${k(e)}`,this.#t))),error:void 0,status:200,success:!0}}catch(s){let r=await this.#s(s);return{cause:r.cause,data:void 0,error:r.error,status:r.status,success:!1}}}async getOrgSecurityPolicy(t){try{let e=await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/settings/security-policy`,this.#t)));return this.#n(e)}catch(e){return await this.#s(e)}}async getOrgTriage(t){try{let e=await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/triage`,this.#t)));return this.#n(e)}catch(e){return await this.#s(e)}}async getQuota(){try{let t=await this.#d("quota",async()=>await d(await m(this.#e,"quota",this.#t)));return this.#n(t)}catch(t){return await this.#s(t)}}async getRepoAnalytics(t,e){try{let s=await this.#r(async()=>await d(await m(this.#e,`analytics/repo/${encodeURIComponent(t)}/${encodeURIComponent(e)}`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getScoreByNpmPackage(t,e){try{let s=await this.#r(async()=>await d(await m(this.#e,`npm/${encodeURIComponent(t)}/${encodeURIComponent(e)}/score`,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async getSupportedScanFiles(){try{let t=await this.#r(async()=>await d(await m(this.#e,"report/supported",this.#t)));return this.#n(t)}catch(t){return await this.#s(t)}}async listOrgDiffScans(t){try{let e=await this.#r(async()=>await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/diff-scans`,this.#t)));return this.#n(e)}catch(e){return await this.#s(e)}}async postAPIToken(t,e){try{let s=await this.#r(async()=>await d(await y("POST",this.#e,`orgs/${encodeURIComponent(t)}/tokens`,e,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async postAPITokensRevoke(t,e){try{let s=await this.#r(async()=>await d(await y("POST",this.#e,`orgs/${encodeURIComponent(t)}/tokens/${encodeURIComponent(e)}/revoke`,{},this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async postAPITokensRotate(t,e){try{let s=await this.#r(async()=>await d(await y("POST",this.#e,`orgs/${encodeURIComponent(t)}/tokens/${encodeURIComponent(e)}/rotate`,{},this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async postAPITokenUpdate(t,e,s){try{let r=await this.#r(async()=>await d(await y("POST",this.#e,`orgs/${encodeURIComponent(t)}/tokens/${encodeURIComponent(e)}/update`,s,this.#t)));return this.#n(r)}catch(r){return await this.#s(r)}}async postSettings(t){try{let e=await this.#r(async()=>await d(await y("POST",this.#e,"settings",{json:t},this.#t)));return this.#n(e)}catch(e){return await this.#s(e)}}async searchDependencies(t){try{let e=await this.#r(async()=>await d(await y("POST",this.#e,"dependencies/search",t,this.#t)));return this.#n(e)}catch(e){return await this.#s(e)}}async sendApi(t,e){let{body:s,method:r="POST",throws:n=!0}={__proto__:null,...e};try{let a=await y(r,this.#e,t,s,this.#t),i=await d(a);return n?i:{cause:void 0,data:i,error:void 0,status:a.statusCode??200,success:!0}}catch(a){if(n)throw a;if(a instanceof R){let c=await this.#s(a);return{cause:c.cause,data:void 0,error:c.error,status:c.status,success:!1}}return{cause:(a?String(a).trim():"")||K,data:void 0,error:"API request failed",status:0,success:!1}}}async streamFullScan(t,e,s){let{output:r}={__proto__:null,...s};try{let n=P(this.#e).request(`${this.#e}orgs/${encodeURIComponent(t)}/full-scans/${encodeURIComponent(e)}`,{method:"GET",...this.#t}).end(),a=await T(n);if(!O(a))throw new R(a);if(typeof r=="string"){let i=Me(r),c=0;a.on("data",u=>{if(c+=u.length,c>$)throw a.destroy(),i.destroy(),new Error(`Response exceeds maximum stream size of ${$} bytes`)}),a.pipe(i),i.on("error",u=>{throw new Error(`Failed to write to file: ${r}`,{cause:u})})}else if(r===!0){let i=0;a.on("data",c=>{if(i+=c.length,i>$)throw a.destroy(),new Error(`Response exceeds maximum stream size of ${$} bytes`)}),a.pipe(process.stdout),process.stdout.on("error",c=>{throw new Error("Failed to write to stdout",{cause:c})})}return this.#n(a)}catch(n){return await this.#s(n)}}async streamPatchesFromScan(t,e){let s=await this.#r(async()=>await m(this.#e,`orgs/${encodeURIComponent(t)}/patches/scan?scan_id=${encodeURIComponent(e)}`,this.#t));if(!O(s))throw new R(s,"GET Request failed");let r=H.createInterface({input:s,crlfDelay:Number.POSITIVE_INFINITY});return new ReadableStream({async start(n){try{for await(let a of r){let i=a.trim();if(i)try{let c=JSON.parse(i);n.enqueue(c)}catch(c){ge("streamPatchesFromScan",`Failed to parse line: ${c}`)}}}catch(a){n.error(a)}finally{n.close()}}})}async updateOrgAlertTriage(t,e,s){try{let r=await this.#r(async()=>await d(await y("PUT",this.#e,`orgs/${encodeURIComponent(t)}/triage/${encodeURIComponent(e)}`,s,this.#t)));return this.#n(r)}catch(r){return await this.#s(r)}}async updateOrgLicensePolicy(t,e,s){try{let r=await this.#r(async()=>await d(await y("POST",this.#e,`orgs/${encodeURIComponent(t)}/settings/license-policy?${k(s)}`,e,this.#t)));return this.#n(r)}catch(r){return await this.#s(r)}}async updateRepository(t,e,s){try{return{cause:void 0,data:await this.#r(async()=>await d(await y("POST",this.#e,`orgs/${encodeURIComponent(t)}/repos/${encodeURIComponent(e)}`,s,this.#t))),error:void 0,status:200,success:!0}}catch(r){let n=await this.#s(r);return{cause:n.cause,data:void 0,error:n.error,status:n.status,success:!1}}}async updateRepositoryLabel(t,e,s){try{return{cause:void 0,data:await this.#r(async()=>await d(await y("PUT",this.#e,`orgs/${encodeURIComponent(t)}/repos/labels/${encodeURIComponent(e)}`,s,this.#t))),error:void 0,status:200,success:!0}}catch(r){let n=await this.#s(r);return{cause:n.cause,data:void 0,error:n.error,status:n.status,success:!1}}}async updateOrgSecurityPolicy(t,e){try{let s=await this.#r(async()=>await d(await y("POST",this.#e,`orgs/${encodeURIComponent(t)}/settings/security-policy`,e,this.#t)));return this.#n(s)}catch(s){return await this.#s(s)}}async uploadManifestFiles(t,e,s){let{pathsRelativeTo:r="."}={__proto__:null,...s},n=I(r),a=U(e,n),{invalidPaths:i,validPaths:c}=V(a);if(this.#o&&i.length>0){let u=await this.#o(c,i,{operation:"uploadManifestFiles",orgSlug:t});if(!u.shouldContinue)return{error:u.errorMessage??"File validation failed",status:400,success:!1,...u.errorCause?{cause:u.errorCause}:{}}}if(!this.#o&&i.length>0){let u=i.slice(0,3).join(`
|
|
53
|
+
- `),l=i.length>3?`
|
|
54
|
+
... and ${i.length-3} more`:"";console.warn(`Warning: ${i.length} files skipped (unreadable):
|
|
55
|
+
- ${u}${l}
|
|
56
|
+
\u2192 This may occur with Yarn Berry PnP or pnpm symlinks.
|
|
57
|
+
\u2192 Try: Run installation command to ensure files are accessible.`)}if(c.length===0){let u=i.slice(0,5).join(`
|
|
58
|
+
- `),l=i.length>5?`
|
|
59
|
+
... and ${i.length-5} more`:"";return{cause:[`All ${i.length} files failed validation:`,` - ${u}${l}`,"","\u2192 Common causes:"," \u2022 Yarn Berry PnP virtual filesystem (files are not on disk)"," \u2022 pnpm symlinks pointing to inaccessible locations"," \u2022 Incorrect file permissions"," \u2022 Files were deleted after discovery","","\u2192 Solutions:"," \u2022 Yarn Berry: Use `nodeLinker: node-modules` in .yarnrc.yml"," \u2022 pnpm: Use `node-linker=hoisted` in .npmrc"," \u2022 Check file permissions with: ls -la <file>"," \u2022 Run package manager install command"].join(`
|
|
60
|
+
`),error:"No readable manifest files found",status:400,success:!1}}try{let u=await this.#r(async()=>await d(await F(this.#e,`orgs/${encodeURIComponent(t)}/upload-manifest-files`,v(c,n),this.#t)));return this.#n(u)}catch(u){return await this.#s(u)}}async viewPatch(t,e){return await d(await m(this.#e,`orgs/${encodeURIComponent(t)}/patches/view/${encodeURIComponent(e)}`,this.#t))}async downloadPatch(t,e){let s=await import("node:https"),r=await import("node:http"),n=`/blob/${encodeURIComponent(t)}`,i=`${e?.baseUrl||se}${n}`,c=i.startsWith("https:");return await new Promise((u,l)=>{(c?s:r).get(i,g=>{if(g.statusCode===404){let f=[`Blob not found: ${t}`,`\u2192 URL: ${i}`,"\u2192 The patch file may have expired or the hash is incorrect.","\u2192 Verify: The blob hash is correct.","\u2192 Note: Blob URLs may expire after a certain time period."].join(`
|
|
61
|
+
`);l(new Error(f));return}if(g.statusCode!==200){let f=[`Failed to download blob: ${g.statusCode} ${g.statusMessage}`,`\u2192 Hash: ${t}`,`\u2192 URL: ${i}`,"\u2192 The blob storage service may be temporarily unavailable.",g.statusCode&&g.statusCode>=500?"\u2192 Try: Retry the download after a short delay.":"\u2192 Verify: The blob hash and URL are correct."].join(`
|
|
62
|
+
`);l(new Error(f));return}let p="";g.on("data",f=>{p+=f}),g.on("end",()=>{u(p)}),g.on("error",f=>{l(f)})}).on("error",g=>{let p=g,f=[`Error downloading blob: ${t}`,`\u2192 URL: ${i}`,`\u2192 Network error: ${p.message}`];p.code==="ENOTFOUND"?f.push("\u2192 DNS lookup failed. Cannot resolve blob storage hostname.","\u2192 Check: Internet connection and DNS settings."):p.code==="ECONNREFUSED"?f.push("\u2192 Connection refused. Blob storage service is unreachable.","\u2192 Check: Network connectivity and firewall settings."):p.code==="ETIMEDOUT"?f.push("\u2192 Connection timed out.","\u2192 Try: Check network connectivity and retry."):p.code&&f.push(`\u2192 Error code: ${p.code}`),l(new Error(f.join(`
|
|
63
|
+
`),{cause:g}))})})}};if(qe("heap")){let o=process.memoryUsage();ge("heap",`heap used: ${Math.round(o.heapUsed/1024/1024)}MB`)}export{q as DEFAULT_USER_AGENT,R as ResponseError,Y as SocketSdk,ue as calculateTotalQuotaCost,A as createDeleteRequest,m as createGetRequest,v as createRequestBodyForFilepaths,Ee as createRequestBodyForJson,y as createRequestWithJson,F as createUploadRequest,x as createUserAgentFromPkgJson,Ce as getAllMethodRequirements,L as getErrorResponseBody,P as getHttpModule,$e as getMethodRequirements,Ue as getMethodsByPermissions,ve as getMethodsByQuotaCost,de as getQuotaCost,Fe as getQuotaUsageSummary,xe as getRequiredPermissions,T as getResponse,d as getResponseJson,Le as hasQuotaForMethods,G as httpAgentNames,O as isResponseOk,Q as normalizeBaseUrl,z as promiseWithResolvers,fe as publicPolicy,k as queryToSearchParams,M as reshapeArtifactForPublicPolicy,U as resolveAbsPaths,I as resolveBasePath};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@socketsecurity/sdk",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.20",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "SDK for the Socket API client",
|
|
6
6
|
"author": {
|
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
"update": "node scripts/update.mjs"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"@socketsecurity/lib": "2.
|
|
57
|
+
"@socketsecurity/lib": "2.9.0"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
60
|
"@babel/parser": "7.26.3",
|