@paklo/core 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{node/azure.d.ts → azure/index.d.ts} +32 -10
- package/dist/{node/azure.js → azure/index.js} +39 -19
- package/dist/azure/index.js.map +1 -0
- package/dist/dependabot/index.d.ts +3 -0
- package/dist/dependabot/index.js +6 -0
- package/dist/{node/dependabot-BteoKZVy.js → dependabot-B5pw4XDa.js} +11 -5
- package/dist/dependabot-B5pw4XDa.js.map +1 -0
- package/dist/{node/environment.d.ts → environment/index.d.ts} +1 -1
- package/dist/environment/index.js +3 -0
- package/dist/environment-DX5CD-dD.js.map +1 -0
- package/dist/{node/github.d.ts → github/index.d.ts} +1 -1
- package/dist/{node/github.js → github/index.js} +4 -4
- package/dist/github/index.js.map +1 -0
- package/dist/{node/http.d.ts → http/index.d.ts} +8 -8
- package/dist/{node/http.js → http/index.js} +2 -2
- package/dist/{node/http-BG_-s47I.js → http-Be3uWaqn.js} +1 -1
- package/dist/http-Be3uWaqn.js.map +1 -0
- package/dist/{node/index-DP9JfUPG.d.ts → index-Dr0PB1As.d.ts} +392 -69
- package/dist/{node/job-Crr4kh3e.js → job-CxYcRj_D.js} +55 -19
- package/dist/job-CxYcRj_D.js.map +1 -0
- package/dist/logger-bWnHxtAf.js.map +1 -0
- package/dist/{node/shared-data.d.ts → shared-data/index.d.ts} +1 -1
- package/dist/{node/shared-data.js → shared-data/index.js} +1 -1
- package/dist/shared-data/index.js.map +1 -0
- package/dist/{node/usage.d.ts → usage.d.ts} +12 -9
- package/dist/{node/usage.js → usage.js} +1 -1
- package/dist/usage.js.map +1 -0
- package/package.json +28 -33
- package/dist/browser/defineProperty-ie4tC-F5.js +0 -43
- package/dist/browser/environment-DinhzwQn.js +0 -139
- package/dist/browser/environment-DinhzwQn.js.map +0 -1
- package/dist/browser/environment.d.ts +0 -33
- package/dist/browser/environment.js +0 -3
- package/dist/browser/github.d.ts +0 -151
- package/dist/browser/github.js +0 -199
- package/dist/browser/github.js.map +0 -1
- package/dist/browser/http.d.ts +0 -121
- package/dist/browser/http.js +0 -248
- package/dist/browser/http.js.map +0 -1
- package/dist/browser/logger-B7HLv660.js +0 -31
- package/dist/browser/logger-B7HLv660.js.map +0 -1
- package/dist/browser/logger.js +0 -4
- package/dist/browser/shared-data.d.ts +0 -22
- package/dist/browser/shared-data.js +0 -23
- package/dist/browser/shared-data.js.map +0 -1
- package/dist/browser/usage.d.ts +0 -99
- package/dist/browser/usage.js +0 -383
- package/dist/browser/usage.js.map +0 -1
- package/dist/node/azure.js.map +0 -1
- package/dist/node/dependabot-BteoKZVy.js.map +0 -1
- package/dist/node/dependabot.d.ts +0 -3
- package/dist/node/dependabot.js +0 -6
- package/dist/node/environment-DX5CD-dD.js.map +0 -1
- package/dist/node/environment.js +0 -3
- package/dist/node/github.js.map +0 -1
- package/dist/node/http-BG_-s47I.js.map +0 -1
- package/dist/node/job-Crr4kh3e.js.map +0 -1
- package/dist/node/logger-bWnHxtAf.js.map +0 -1
- package/dist/node/logger.d.ts +0 -23
- package/dist/node/shared-data.js.map +0 -1
- package/dist/node/usage.js.map +0 -1
- /package/dist/{node/environment-DX5CD-dD.js → environment-DX5CD-dD.js} +0 -0
- /package/dist/{node/index-3wZw74Ah.d.ts → index-3wZw74Ah.d.ts} +0 -0
- /package/dist/{node/logger-bWnHxtAf.js → logger-bWnHxtAf.js} +0 -0
- /package/dist/{browser/logger.d.ts → logger.d.ts} +0 -0
- /package/dist/{node/logger.js → logger.js} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"environment-DX5CD-dD.js","names":[],"sources":["../src/environment/git.ts","../src/environment/platform.ts","../src/environment/site-url.ts","../src/environment/index.ts"],"sourcesContent":["/**\n * Retrieves the name of the current Git branch from the environment variables or from Git itself.\n * The priority order for retrieving the branch name is as follows:\n * 1. `process.env.GITHUB_REF_NAME`\n * 2. `process.env.VERCEL_GIT_COMMIT_REF`\n * 3. `process.env.CF_PAGES_BRANCH`\n * 4. Retrieve the branch name from Git using the `getBranchFromGit` function.\n * @returns The name of the current Git branch, or undefined if it cannot be determined.\n */\nexport function getBranch(): string | undefined {\n // GITHUB_REF_NAME may change on every build and we do not want the turbo cache to be invalidated on every build\n return (\n process.env.GITHUB_REF_NAME ||\n process.env.VERCEL_GIT_COMMIT_REF ||\n process.env.CF_PAGES_BRANCH ||\n getBranchFromGit()\n );\n}\n\n/**\n * Retrieves the Git SHA (commit hash) from the environment variables or from Git itself.\n * The priority order for retrieving the Git SHA is as follows:\n * 1. `process.env.GITHUB_SHA`\n * 2. `process.env.VERCEL_GIT_COMMIT_SHA`\n * 3. `process.env.CF_PAGES_COMMIT_SHA`\n * 4. Retrieve the SHA from Git using the `getShaFromGit` function.\n * @returns The Git SHA (commit hash) if available, otherwise `undefined`.\n */\nexport function getSha(): string | undefined {\n // GITHUB_SHA changes on every build and we do not want the turbo cache to be invalidated on every build\n return (\n process?.env.GITHUB_SHA || process?.env.VERCEL_GIT_COMMIT_SHA || process?.env.CF_PAGES_COMMIT_SHA || getShaFromGit()\n );\n}\n\n/**\n * Retrieves the SHA (commit hash) from the Git repository.\n * @returns The SHA (commit hash) as a string, or undefined if it cannot be retrieved.\n */\nfunction getShaFromGit(): string | undefined {\n try {\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n const { execSync } = require('node:child_process');\n return execSync('git rev-parse HEAD').toString().trim();\n }\n } catch {\n return undefined;\n }\n}\n\n/**\n * Retrieves the current branch name from Git.\n * @returns The name of the current branch, or 'unknown' if an error occurs.\n */\nfunction getBranchFromGit(): string | undefined {\n try {\n if (process.env.NEXT_RUNTIME === 'nodejs') {\n const { execSync } = require('node:child_process');\n return execSync('git rev-parse --abbrev-ref HEAD').toString().trim();\n }\n } catch {\n return undefined;\n }\n}\n","export type Platform =\n | 'azure_app_service'\n | 'azure_container_apps'\n | 'azure_static_web_app'\n | 'cloudflare_pages'\n | 'vercel'\n | undefined;\n\nexport function getPlatform(): Platform {\n if (process.env.CONTAINER_APP_ENV_DNS_SUFFIX) return 'azure_container_apps';\n // SWA is a special case of Azure App Service so we need to check it first\n else if (process.env.WEBSITE_STATICWEBAPP_RESOURCE_ID) return 'azure_static_web_app';\n else if (process.env.WEBSITE_HOSTNAME) return 'azure_app_service';\n else if (process.env.CF_PAGES_URL) return 'cloudflare_pages';\n else if (process.env.VERCEL_BRANCH_URL) return 'vercel';\n\n return undefined;\n}\n","interface SiteUrlOptions {\n /** Whether the current environment is development. */\n development: boolean;\n\n /** Whether the current branch is the main branch. */\n main: boolean;\n\n /** The default URL to use if no other URL is found. */\n defaultValue: string;\n}\n\n/**\n * Get the site URL based on the environment variables.\n * @param options - The options to use.\n * @returns The site URL.\n */\nexport function getSiteUrlCombined({ development, main, defaultValue }: SiteUrlOptions) {\n // if we are in development, use localhost\n if (development) return `http://localhost:${process.env.PORT || 3000}`;\n\n // if we are on the main branch, use the known URL\n if (main) return defaultValue;\n\n // if we are on Azure ContainerApps, use the provided URL\n let value = getSiteUrlForAca();\n if (value && value.length > 0) return value;\n\n // if we are on Azure App Service, use the provided URL\n value = getSiteUrlForAppService();\n if (value && value.length > 0) return value;\n\n // if we are on Azure Static WebApps, use the provided URL\n value = getSiteUrlForSwa();\n if (value && value.length > 0) return value;\n\n // if we are on Vercel, use the provided URL\n value = process.env.VERCEL_BRANCH_URL;\n if (value && value.length > 0) return `https://${value}`;\n\n // if we are on Cloudflare Pages, use the provided URL\n value = process.env.CF_PAGES_URL;\n if (value && value.length > 0) return value;\n\n return defaultValue; // fallback (edge cases)\n}\n\nexport function getSiteUrlForAca(): string | undefined {\n /*\n * Having looked at the available ENV variables when deployed, we can form the URL from\n * combinations of the following variables:\n * CONTAINER_APP_ENV_DNS_SUFFIX (e.g. \"jollyplant-9349db20.westeurope.azurecontainerapps.io\")\n * CONTAINER_APP_NAME (e.g. \"paklo-website\")\n */\n\n const suffix = process.env.CONTAINER_APP_ENV_DNS_SUFFIX;\n const name = process.env.CONTAINER_APP_NAME;\n if (!suffix || !name) return undefined;\n return `https://${name}.${suffix}`;\n}\n\nexport function getSiteUrlForAppService(): string | undefined {\n /*\n * Environment variables for Azure App Service are documented at\n * https://learn.microsoft.com/en-us/azure/app-service/reference-app-settings?tabs=kudu%2Cdotnet#app-environment\n *\n * WEBSITE_HOSTNAME (e.g. \"paklo-website.azurewebsites.net\")\n */\n\n const value = process.env.WEBSITE_HOSTNAME;\n return value ? `https://${value}` : undefined;\n}\n\nexport function getSiteUrlForSwa(): string | undefined {\n /*\n * Having looked at the available ENV variables when deployed to both production and preview environments,\n * only the WEBSITE_AUTH_V2_CONFIG_JSON has values we can use for this.\n *\n * Sample value for production:\n * {\\\"platform\\\":{\\\"enabled\\\":true},\\\"globalValidation\\\":{\\\"excludedPaths\\\":[\\\"/.swa/health.html\\\"]},\\\"identityProviders\\\":{\\\"azureStaticWebApps\\\":{\\\"registration\\\":{\\\"clientId\\\":\\\"black-bush-020715303.5.azurestaticapps.net\\\"}}},\\\"legacyProperties\\\":{\\\"configVersion\\\":\\\"v2\\\",\\\"legacyVersion\\\":\\\"V2\\\"}}\n *\n * Sample value for preview environment (named 331):\n * {\\\"platform\\\":{\\\"enabled\\\":true},\\\"globalValidation\\\":{\\\"excludedPaths\\\":[\\\"/.swa/health.html\\\"]},\\\"identityProviders\\\":{\\\"azureStaticWebApps\\\":{\\\"registration\\\":{\\\"clientId\\\":\\\"black-bush-020715303-331.westeurope.5.azurestaticapps.net\\\"}}},\\\"legacyProperties\\\":{\\\"configVersion\\\":\\\"v2\\\",\\\"legacyVersion\\\":\\\"V2\\\"}}\n *\n * The part we are interested in is the clientId value. We can extract this value and use it as the domain to form the siteUrl.\n */\n\n const config = process.env.WEBSITE_AUTH_V2_CONFIG_JSON;\n const clientIdMatch = config?.match(/\"clientId\":\"([^\"]+)\"/);\n return clientIdMatch ? `https://${clientIdMatch[1]}` : undefined;\n}\n","import { getBranch, getSha } from './git';\nimport { getPlatform, type Platform } from './platform';\nimport { getSiteUrlCombined } from './site-url';\n\nexport type Environment = {\n /** The current environment. */\n name?: 'development' | 'production' | 'test';\n\n /** Whether the current environment is development. */\n development: boolean;\n\n /** Whether the current environment is production. */\n production: boolean;\n\n /** Whether the current environment is test. */\n test: boolean;\n\n /** The current platform. */\n platform: Platform;\n\n /** The current commit SHA. */\n sha?: string;\n\n /** The current branch name. */\n branch?: string;\n\n /** Whether the current branch is the main branch. */\n main: boolean;\n};\n\nfunction getEnvironment(): Environment {\n const env = process.env.NODE_ENV as Environment['name'];\n const branch = getBranch();\n const sha = getSha();\n const platform = getPlatform();\n\n return {\n name: env,\n development: env === 'development',\n production: env === 'production',\n test: env === 'test',\n platform,\n sha,\n branch,\n main: branch === 'main',\n };\n}\n\nexport const environment = getEnvironment();\n\nexport interface SiteUrlOptions {\n /** The default URL to use if no other URL is found. */\n defaultValue: string;\n}\n\nexport function getSiteUrl({ defaultValue }: SiteUrlOptions): string {\n const { development, main } = environment;\n return getSiteUrlCombined({ development, main, defaultValue: defaultValue });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AASA,SAAgB,YAAgC;AAE9C,QACE,QAAQ,IAAI,mBACZ,QAAQ,IAAI,yBACZ,QAAQ,IAAI,mBACZ,kBAAkB;;;;;;;;;;;AAatB,SAAgB,SAA6B;AAE3C,QACE,SAAS,IAAI,cAAc,SAAS,IAAI,yBAAyB,SAAS,IAAI,uBAAuB,eAAe;;;;;;AAQxH,SAAS,gBAAoC;AAC3C,KAAI;AACF,MAAI,QAAQ,IAAI,iBAAiB,UAAU;GACzC,MAAM,EAAE,uBAAqB,qBAAqB;AAClD,UAAO,SAAS,qBAAqB,CAAC,UAAU,CAAC,MAAM;;SAEnD;AACN;;;;;;;AAQJ,SAAS,mBAAuC;AAC9C,KAAI;AACF,MAAI,QAAQ,IAAI,iBAAiB,UAAU;GACzC,MAAM,EAAE,uBAAqB,qBAAqB;AAClD,UAAO,SAAS,kCAAkC,CAAC,UAAU,CAAC,MAAM;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EACL,MAAM;EACN,aAAa,QAAQ;EACrB,YAAY,QAAQ;EACpB,MAAM,QAAQ;EACd;EACA;EACA;EACA,MAAM,WAAW;EAClB;;AAGH,MAAa,cAAc,gBAAgB;AAO3C,SAAgB,WAAW,EAAE,gBAAwC;CACnE,MAAM,EAAE,aAAa,SAAS;AAC9B,QAAO,mBAAmB;EAAE;EAAa;EAAoB;EAAc,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as PackageEcosystemSchema, c as SecurityAdvisoryIdentifierSchema, d as SecurityAdvisorySeverity, f as SecurityAdvisorySeveritySchema, g as getGhsaPackageEcosystemFromDependabotPackageManager, h as filterVulnerabilities, i as PackageEcosystem, l as SecurityAdvisoryIdentifierType, m as SecurityVulnerabilitySchema, n as GitHubGraphClient, o as PackageSchema, p as SecurityVulnerability, r as Package, s as SecurityAdvisory, t as FirstPatchedVersion, u as SecurityAdvisorySchema } from "
|
|
1
|
+
import { a as PackageEcosystemSchema, c as SecurityAdvisoryIdentifierSchema, d as SecurityAdvisorySeverity, f as SecurityAdvisorySeveritySchema, g as getGhsaPackageEcosystemFromDependabotPackageManager, h as filterVulnerabilities, i as PackageEcosystem, l as SecurityAdvisoryIdentifierType, m as SecurityVulnerabilitySchema, n as GitHubGraphClient, o as PackageSchema, p as SecurityVulnerability, r as Package, s as SecurityAdvisory, t as FirstPatchedVersion, u as SecurityAdvisorySchema } from "../index-3wZw74Ah.js";
|
|
2
2
|
export { FirstPatchedVersion, GitHubGraphClient, Package, PackageEcosystem, PackageEcosystemSchema, PackageSchema, SecurityAdvisory, SecurityAdvisoryIdentifierSchema, SecurityAdvisoryIdentifierType, SecurityAdvisorySchema, SecurityAdvisorySeverity, SecurityAdvisorySeveritySchema, SecurityVulnerability, SecurityVulnerabilitySchema, filterVulnerabilities, getGhsaPackageEcosystemFromDependabotPackageManager };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import "
|
|
2
|
-
import { n as logger } from "
|
|
3
|
-
import * as semver from "semver";
|
|
1
|
+
import "../environment-DX5CD-dD.js";
|
|
2
|
+
import { n as logger } from "../logger-bWnHxtAf.js";
|
|
4
3
|
import { z } from "zod/v4";
|
|
4
|
+
import * as semver from "semver";
|
|
5
5
|
|
|
6
6
|
//#region src/github/ghsa.ts
|
|
7
7
|
const GHSA_GRAPHQL_API = "https://api.github.com/graphql";
|
|
@@ -195,4 +195,4 @@ function filterVulnerabilities(securityVulnerabilities) {
|
|
|
195
195
|
|
|
196
196
|
//#endregion
|
|
197
197
|
export { GitHubGraphClient, PackageEcosystemSchema, PackageSchema, SecurityAdvisoryIdentifierSchema, SecurityAdvisorySchema, SecurityAdvisorySeveritySchema, SecurityVulnerabilitySchema, filterVulnerabilities, getGhsaPackageEcosystemFromDependabotPackageManager };
|
|
198
|
-
//# sourceMappingURL=
|
|
198
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["results: T2[]","v"],"sources":["../../src/github/ghsa.ts"],"sourcesContent":["import * as semver from 'semver';\nimport { z } from 'zod/v4';\n\nimport { logger } from '@/logger';\n\n// we use nullish() because it does optional() and allows the value to be set to null\n\nconst GHSA_GRAPHQL_API = 'https://api.github.com/graphql';\n\nconst GHSA_SECURITY_VULNERABILITIES_QUERY = `\n query($ecosystem: SecurityAdvisoryEcosystem, $package: String) {\n securityVulnerabilities(first: 100, ecosystem: $ecosystem, package: $package) {\n nodes {\n advisory {\n identifiers {\n type,\n value\n },\n severity,\n summary,\n description,\n references {\n url\n }\n cvss {\n score\n vectorString\n }\n epss {\n percentage\n percentile\n }\n cwes (first: 100) {\n nodes {\n cweId\n name\n description\n }\n }\n publishedAt\n updatedAt\n withdrawnAt\n permalink\n }\n vulnerableVersionRange\n firstPatchedVersion {\n identifier\n }\n }\n }\n }\n`;\n\nexport const PackageEcosystemSchema = z.enum([\n 'COMPOSER',\n 'ERLANG',\n 'GO',\n 'ACTIONS',\n 'MAVEN',\n 'NPM',\n 'NUGET',\n 'PIP',\n 'PUB',\n 'RUBYGEMS',\n 'RUST',\n 'SWIFT',\n]);\nexport type PackageEcosystem = z.infer<typeof PackageEcosystemSchema>;\n\nexport const PackageSchema = z.object({\n name: z.string(),\n version: z.string().nullish(),\n});\nexport type Package = z.infer<typeof PackageSchema>;\n\nexport const SecurityAdvisoryIdentifierSchema = z.enum(['CVE', 'GHSA']);\nexport type SecurityAdvisoryIdentifierType = z.infer<typeof SecurityAdvisoryIdentifierSchema>;\n\nexport const SecurityAdvisorySeveritySchema = z.enum(['LOW', 'MODERATE', 'HIGH', 'CRITICAL']);\nexport type SecurityAdvisorySeverity = z.infer<typeof SecurityAdvisorySeveritySchema>;\n\nexport const SecurityAdvisorySchema = z.object({\n identifiers: z.array(\n z.object({\n type: z.union([SecurityAdvisoryIdentifierSchema, z.string()]),\n value: z.string(),\n }),\n ),\n severity: SecurityAdvisorySeveritySchema.nullish(),\n summary: z.string(),\n description: z.string().nullish(),\n references: z.array(z.object({ url: z.string() })).nullish(),\n cvss: z\n .object({\n score: z.number(),\n vectorString: z.string(),\n })\n .nullish(),\n epss: z\n .object({\n percentage: z.number(),\n percentile: z.number(),\n })\n .nullish(),\n cwes: z\n .array(\n z.object({\n cweId: z.string(),\n name: z.string(),\n description: z.string(),\n }),\n )\n .nullish(),\n publishedAt: z.string().nullish(),\n updatedAt: z.string().nullish(),\n withdrawnAt: z.string().nullish(),\n permalink: z.string().nullish(),\n});\nexport type SecurityAdvisory = z.infer<typeof SecurityAdvisorySchema>;\n\nconst FirstPatchedVersionSchema = z.object({ identifier: z.string() });\nexport type FirstPatchedVersion = z.infer<typeof FirstPatchedVersionSchema>;\n\nexport const SecurityVulnerabilitySchema = z.object({\n package: PackageSchema,\n advisory: SecurityAdvisorySchema,\n vulnerableVersionRange: z.string(),\n firstPatchedVersion: FirstPatchedVersionSchema.nullish(),\n});\nexport type SecurityVulnerability = z.infer<typeof SecurityVulnerabilitySchema>;\n\nexport function getGhsaPackageEcosystemFromDependabotPackageManager(\n dependabotPackageManager: string,\n): PackageEcosystem {\n switch (dependabotPackageManager) {\n case 'composer':\n return 'COMPOSER';\n case 'elm':\n return 'ERLANG';\n case 'github_actions':\n return 'ACTIONS';\n case 'go_modules':\n return 'GO';\n case 'maven':\n return 'MAVEN';\n case 'npm_and_yarn':\n return 'NPM';\n case 'nuget':\n return 'NUGET';\n case 'pip':\n return 'PIP';\n case 'pub':\n return 'PUB';\n case 'bundler':\n return 'RUBYGEMS';\n case 'cargo':\n return 'RUST';\n case 'swift':\n return 'SWIFT';\n default:\n throw new Error(`Unknown dependabot package manager: ${dependabotPackageManager}`);\n }\n}\n\n/**\n * GitHub GraphQL client\n */\nexport class GitHubGraphClient {\n private readonly accessToken: string;\n\n constructor(accessToken: string) {\n this.accessToken = accessToken;\n }\n\n /**\n * Get the list of security vulnerabilities for a given package ecosystem and list of packages\n * @param packageEcosystem\n * @param packages\n */\n public async getSecurityVulnerabilitiesAsync(\n packageEcosystem: PackageEcosystem,\n packages: Package[],\n ): Promise<SecurityVulnerability[]> {\n // GitHub API doesn't support querying multiple package at once, so we need to make a request for each package individually.\n // To speed up the process, we can make the requests in parallel, 100 at a time. We batch the requests to avoid hitting the rate limit too quickly.\n // https://docs.github.com/en/graphql/overview/rate-limits-and-node-limits-for-the-graphql-api\n const securityVulnerabilities = await this.batchGraphQueryAsync<Package, SecurityVulnerability>(\n 100,\n packages,\n async (pkg) => {\n const variables = {\n ecosystem: packageEcosystem,\n package: pkg.name,\n };\n const response = await fetch(GHSA_GRAPHQL_API, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.accessToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n query: GHSA_SECURITY_VULNERABILITIES_QUERY,\n variables: variables,\n }),\n });\n if (!response.ok) {\n throw new Error(`GHSA GraphQL request failed with response: ${response.status} ${response.statusText}`);\n }\n const responseData = await response.json();\n const errors = responseData?.errors;\n if (errors) {\n throw new Error(`GHSA GraphQL request failed with errors: ${JSON.stringify(errors)}`);\n }\n\n const vulnerabilities = responseData?.data?.securityVulnerabilities?.nodes;\n // biome-ignore lint/suspicious/noExplicitAny: generic\n return vulnerabilities?.filter((v: any) => v?.advisory)?.map((v: any) => ({ package: pkg, ...v }));\n },\n );\n\n return securityVulnerabilities;\n }\n\n /**\n * Batch requests in parallel to speed up the process when we are forced to do a N+1 query\n * @param batchSize\n * @param items\n * @param action\n * @returns\n */\n private async batchGraphQueryAsync<T1, T2>(batchSize: number, items: T1[], action: (item: T1) => Promise<T2[]>) {\n const results: T2[] = [];\n for (let i = 0; i < items.length; i += batchSize) {\n const batch = items.slice(i, i + batchSize);\n if (batch?.length) {\n try {\n const batchResults = await Promise.all(batch.map(action));\n if (batchResults?.length) {\n results.push(...batchResults.flat());\n }\n } catch (error) {\n logger.warn(`Request batch [${i}-${i + batchSize}] failed; The data may be incomplete. ${error}`);\n }\n }\n }\n return results;\n }\n}\n\nexport function filterVulnerabilities(securityVulnerabilities: SecurityVulnerability[]): SecurityVulnerability[] {\n // Filter out vulnerabilities that have been withdrawn or that are not relevant the current version of the package\n const affectedVulnerabilities = securityVulnerabilities\n .filter((v) => !v.advisory.withdrawnAt)\n .filter((v) => {\n const pkg = v.package;\n if (!pkg || !pkg.version || !v.vulnerableVersionRange) {\n return false;\n }\n\n /**\n * The vulnerable version range follows a basic syntax with a few forms:\n * `= 0.2.0` denotes a single vulnerable version\n * `<= 1.0.8` denotes a version range up to and including the specified version\n * `< 0.1.11` denotes a version range up to, but excluding, the specified version\n * `>= 4.3.0, < 4.3.5` denotes a version range with a known minimum and maximum version\n * `>= 0.0.1` denotes a version range with a known minimum, but no known maximum\n */\n const versionRangeRequirements = v.vulnerableVersionRange.split(',').map((v) => v.trim());\n return versionRangeRequirements.every((r) => pkg.version && semver.satisfies(pkg.version, r));\n });\n return affectedVulnerabilities;\n}\n"],"mappings":";;;;;;AAOA,MAAM,mBAAmB;AAEzB,MAAM,sCAAsC;;;;;;;;;;;;;;;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K,OAAY;IAAE,SAAS;IAAK,GAAG;IAAG,EAAE;IAErG;;;;;;;;;CAYH,MAAc,qBAA6B,WAAmB,OAAa,QAAqC;EAC9G,MAAMA,UAAgB,EAAE;AACxB,OAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;GAChD,MAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,UAAU;AAC3C,OAAI,OAAO,OACT,KAAI;IACF,MAAM,eAAe,MAAM,QAAQ,IAAI,MAAM,IAAI,OAAO,CAAC;AACzD,QAAI,cAAc,OAChB,SAAQ,KAAK,GAAG,aAAa,MAAM,CAAC;YAE/B,OAAO;AACd,WAAO,KAAK,kBAAkB,EAAE,GAAG,IAAI,UAAU,wCAAwC,QAAQ;;;AAIvG,SAAO;;;AAIX,SAAgB,sBAAsB,yBAA2E;AAqB/G,QAnBgC,wBAC7B,QAAQ,MAAM,CAAC,EAAE,SAAS,YAAY,CACtC,QAAQ,MAAM;EACb,MAAM,MAAM,EAAE;AACd,MAAI,CAAC,OAAO,CAAC,IAAI,WAAW,CAAC,EAAE,uBAC7B,QAAO;AAYT,SADiC,EAAE,uBAAuB,MAAM,IAAI,CAAC,KAAK,QAAMC,IAAE,MAAM,CAAC,CACzD,OAAO,MAAM,IAAI,WAAW,OAAO,UAAU,IAAI,SAAS,EAAE,CAAC;GAC7F"}
|
|
@@ -39,7 +39,7 @@ interface ProblemDetails {
|
|
|
39
39
|
type CreateInnerApiClientOptions = {
|
|
40
40
|
/**
|
|
41
41
|
* The base URL to use for the API.
|
|
42
|
-
* @example 'https://
|
|
42
|
+
* @example 'https://www.paklo.app/api'
|
|
43
43
|
*/
|
|
44
44
|
baseUrl: string;
|
|
45
45
|
/** The token to use for authentication. This can be a JWT or specialized key. */
|
|
@@ -53,7 +53,7 @@ type RequestOptions = {
|
|
|
53
53
|
*/
|
|
54
54
|
userAgent?: string;
|
|
55
55
|
};
|
|
56
|
-
type ResourceResponse<T
|
|
56
|
+
type ResourceResponse<T = Record<string, unknown>> = {
|
|
57
57
|
/** The headers of the response. */
|
|
58
58
|
headers: Headers;
|
|
59
59
|
/** Whether the request was successful. */
|
|
@@ -63,15 +63,15 @@ type ResourceResponse<T$1 = Record<string, unknown>> = {
|
|
|
63
63
|
/** The status text of the response. */
|
|
64
64
|
statusText: string;
|
|
65
65
|
/** The data of the response. */
|
|
66
|
-
data?: T
|
|
66
|
+
data?: T;
|
|
67
67
|
/** The error of the response. */
|
|
68
68
|
error?: ProblemDetails;
|
|
69
69
|
};
|
|
70
|
-
type InnerRequestOptions<T
|
|
70
|
+
type InnerRequestOptions<T> = RequestOptions & {
|
|
71
71
|
/**
|
|
72
72
|
* The base URL to use for the request.
|
|
73
73
|
* This overrides the default base URL.
|
|
74
|
-
* @example 'https://
|
|
74
|
+
* @example 'https://www.paklo.app/api'
|
|
75
75
|
*/
|
|
76
76
|
baseUrl?: string;
|
|
77
77
|
/** Additional headers to use for the request. */
|
|
@@ -79,9 +79,9 @@ type InnerRequestOptions<T$1> = RequestOptions & {
|
|
|
79
79
|
/** The payload to use for the request. */
|
|
80
80
|
payload?: Record<string, unknown> | MultipartFormDataBody | ReadableStream | XMLHttpRequestBodyInit;
|
|
81
81
|
/** The schema to use when parsing the response. */
|
|
82
|
-
schema?: ZodType<T
|
|
82
|
+
schema?: ZodType<T>;
|
|
83
83
|
};
|
|
84
|
-
type InnerRequestOptionsComplete<T
|
|
84
|
+
type InnerRequestOptionsComplete<T> = InnerRequestOptions<T> & {
|
|
85
85
|
/** The method to use for the request. */
|
|
86
86
|
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
87
87
|
/** The URL to use for the request. */
|
|
@@ -118,4 +118,4 @@ declare function isErrorTemporaryFailure(e?: {
|
|
|
118
118
|
} | null): boolean;
|
|
119
119
|
//#endregion
|
|
120
120
|
export { CreateInnerApiClientOptions, HEADER_NAME_ACCEPT, HEADER_NAME_AUTHORIZATION, HEADER_NAME_CONTENT_DISPOSITION, HEADER_NAME_CONTENT_TYPE, HEADER_NAME_USER_AGENT, HttpRequestError, InnerApiClient, InnerRequestOptions, ProblemDetails, RequestOptions, ResourceResponse, isErrorTemporaryFailure };
|
|
121
|
-
//# sourceMappingURL=
|
|
121
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "
|
|
2
|
-
import { a as HEADER_NAME_AUTHORIZATION, c as HEADER_NAME_USER_AGENT, i as HEADER_NAME_ACCEPT, n as InnerApiClient, o as HEADER_NAME_CONTENT_DISPOSITION, r as isErrorTemporaryFailure, s as HEADER_NAME_CONTENT_TYPE, t as HttpRequestError } from "
|
|
1
|
+
import "../environment-DX5CD-dD.js";
|
|
2
|
+
import { a as HEADER_NAME_AUTHORIZATION, c as HEADER_NAME_USER_AGENT, i as HEADER_NAME_ACCEPT, n as InnerApiClient, o as HEADER_NAME_CONTENT_DISPOSITION, r as isErrorTemporaryFailure, s as HEADER_NAME_CONTENT_TYPE, t as HttpRequestError } from "../http-Be3uWaqn.js";
|
|
3
3
|
|
|
4
4
|
export { HEADER_NAME_ACCEPT, HEADER_NAME_AUTHORIZATION, HEADER_NAME_CONTENT_DISPOSITION, HEADER_NAME_CONTENT_TYPE, HEADER_NAME_USER_AGENT, HttpRequestError, InnerApiClient, isErrorTemporaryFailure };
|
|
@@ -242,4 +242,4 @@ function isErrorTemporaryFailure(e) {
|
|
|
242
242
|
|
|
243
243
|
//#endregion
|
|
244
244
|
export { HEADER_NAME_AUTHORIZATION as a, HEADER_NAME_USER_AGENT as c, HEADER_NAME_ACCEPT as i, InnerApiClient as n, HEADER_NAME_CONTENT_DISPOSITION as o, isErrorTemporaryFailure as r, HEADER_NAME_CONTENT_TYPE as s, HttpRequestError as t };
|
|
245
|
-
//# sourceMappingURL=http-
|
|
245
|
+
//# sourceMappingURL=http-Be3uWaqn.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http-Be3uWaqn.js","names":["data: Array<MultipartFormDataBodyPart['body']>","list: Buffer[]","headers: Record<string, string>","body: BodyInit | undefined","error: ProblemDetails","code: number"],"sources":["../src/http/headers.ts","../src/http/multipart.ts","../src/http/inner.ts"],"sourcesContent":["export const HEADER_NAME_CONTENT_DISPOSITION = 'Content-Disposition';\nexport const HEADER_NAME_CONTENT_TYPE = 'Content-Type';\nexport const HEADER_NAME_ACCEPT = 'Accept';\nexport const HEADER_NAME_USER_AGENT = 'User-Agent';\nexport const HEADER_NAME_AUTHORIZATION = 'Authorization';\n","import { HEADER_NAME_CONTENT_DISPOSITION, HEADER_NAME_CONTENT_TYPE } from './headers';\n\nexport class MultipartFormDataBody {\n private type = 'multipart/form-data';\n private boundary: string = `${Math.random().toString(36).substring(2)}`;\n private parts: Array<MultipartFormDataBodyPart> = [];\n\n public async encode(): Promise<Buffer> {\n if (this.parts.length === 0) {\n throw new Error('MultipartFormDataBody must have at least one part');\n }\n\n const data: Array<MultipartFormDataBodyPart['body']> = [];\n\n for (const part of this.parts) {\n // write boundary\n data.push(`--${this.boundary}\\r\\n`);\n\n // write headers\n for (const [key, value] of Object.entries(part.headers)) {\n data.push(`${key}: ${value}\\r\\n`);\n }\n data.push('\\r\\n');\n\n // write body\n data.push(part.body);\n data.push('\\r\\n');\n }\n\n data.push(`--${this.boundary}--\\r\\n`);\n\n const list: Buffer[] = [];\n for (const item of data) {\n if (item instanceof File) list.push(Buffer.from(await item.arrayBuffer()));\n else if (typeof item === 'string') list.push(Buffer.from(item, 'utf8'));\n else list.push(item);\n }\n return Buffer.concat(list);\n }\n\n public getBoundary(): string {\n return this.boundary;\n }\n\n public getContentType(): string {\n return `${this.type}; boundary=${this.boundary}`;\n }\n\n public add(name: string, value: string) {\n const part = createPart(name, value);\n this.parts.push(part);\n }\n\n public addFile(name: string, file: File) {\n const part = createPart(name, file, file.name, file.type);\n this.parts.push(part);\n }\n}\n\ntype MultipartFormDataBodyPart = {\n name: string;\n headers: Record<string, string>;\n body: Buffer | File | string;\n};\n\nfunction createPart(\n name: string,\n body: MultipartFormDataBodyPart['body'],\n filename?: string,\n contentType?: string,\n): MultipartFormDataBodyPart {\n const headers: Record<string, string> = {};\n headers[HEADER_NAME_CONTENT_DISPOSITION] = `form-data; name=\"${name}\"${filename ? `; filename=\"${filename}\"` : ''}`;\n if (contentType) headers[HEADER_NAME_CONTENT_TYPE] = contentType;\n return { name, headers, body };\n}\n","import type { ZodType } from 'zod/v4';\n\nimport { environment } from '@/environment';\n\nimport {\n HEADER_NAME_ACCEPT,\n HEADER_NAME_AUTHORIZATION,\n HEADER_NAME_CONTENT_TYPE,\n HEADER_NAME_USER_AGENT,\n} from './headers';\nimport { MultipartFormDataBody } from './multipart';\nimport type { ProblemDetails } from './problem';\n\nconst defaultUserAgent = `paklo/${environment.sha?.substring(0, 7) ?? 'dogfood'}`;\n\nexport type CreateInnerApiClientOptions = {\n /**\n * The base URL to use for the API.\n * @example 'https://www.paklo.app/api'\n */\n baseUrl: string;\n\n /** The token to use for authentication. This can be a JWT or specialized key. */\n token?: string;\n};\n\nexport type RequestOptions = {\n /**\n * Value for the `User-Agent` header.\n * This prepends the default value (e.g. `paklo/ab26320`)\n * which is important when we need to propagate the browser information to the server.\n */\n userAgent?: string;\n};\n\nexport type ResourceResponse<T = Record<string, unknown>> = {\n /** The headers of the response. */\n headers: Headers;\n\n /** Whether the request was successful. */\n successful: boolean;\n\n /** The status code of the response. */\n status: number;\n\n /** The status text of the response. */\n statusText: string;\n\n /** The data of the response. */\n data?: T;\n\n /** The error of the response. */\n error?: ProblemDetails;\n};\n\nexport type InnerRequestOptions<T> = RequestOptions & {\n /**\n * The base URL to use for the request.\n * This overrides the default base URL.\n * @example 'https://www.paklo.app/api'\n */\n baseUrl?: string;\n\n /** Additional headers to use for the request. */\n headers?: HeadersInit;\n\n /** The payload to use for the request. */\n payload?: Record<string, unknown> | MultipartFormDataBody | ReadableStream | XMLHttpRequestBodyInit;\n\n /** The schema to use when parsing the response. */\n schema?: ZodType<T>;\n};\n\ntype InnerRequestOptionsComplete<T> = InnerRequestOptions<T> & {\n /** The method to use for the request. */\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n /** The URL to use for the request. */\n url: string;\n};\n\nexport class InnerApiClient {\n private readonly baseUrl: string;\n private readonly headers: Headers;\n private readonly token?: string;\n\n /**\n * Create a new API client.\n * @param options The options to use for the client.\n */\n constructor({ baseUrl, token }: CreateInnerApiClientOptions) {\n this.baseUrl = baseUrl;\n\n this.headers = new Headers({\n [HEADER_NAME_ACCEPT]: 'application/json',\n });\n\n this.token = token;\n }\n\n async get<T>(url: string, options?: InnerRequestOptions<T>) {\n return this.request<T>({\n url: this.makeUrl(url, options),\n method: 'GET',\n ...options,\n });\n }\n\n async post<T>(url: string, options?: InnerRequestOptions<T>) {\n return this.request<T>({\n method: 'POST',\n url: this.makeUrl(url, options),\n ...options,\n });\n }\n\n async put<T>(url: string, options?: InnerRequestOptions<T>) {\n return this.request<T>({\n method: 'PUT',\n url: this.makeUrl(url, options),\n ...options,\n });\n }\n\n async patch<T>(url: string, options?: InnerRequestOptions<T>) {\n return this.request<T>({\n method: 'PATCH',\n url: this.makeUrl(url, options),\n ...options,\n });\n }\n\n async delete<T>(url: string, options?: InnerRequestOptions<T>) {\n return this.request<T>({\n method: 'DELETE',\n url: this.makeUrl(url, options),\n ...options,\n });\n }\n\n async request<T>(options: InnerRequestOptionsComplete<T>): Promise<ResourceResponse<T>> {\n const { method, url, payload, userAgent, headers: additionalHeaders, schema } = options;\n\n // create headers for the request\n const headers = new Headers(this.headers);\n const finalUserAgent = userAgent && userAgent.length > 0 ? `${userAgent} (${defaultUserAgent})` : defaultUserAgent;\n headers.set(HEADER_NAME_USER_AGENT, finalUserAgent);\n\n // populate authorization header\n if (this.token) {\n headers.set(HEADER_NAME_AUTHORIZATION, `Bearer ${this.token}`);\n }\n\n // populate additional headers\n // biome-ignore-start lint/suspicious/useIterableCallbackReturn: not used\n if (additionalHeaders) {\n if (additionalHeaders instanceof Headers) {\n additionalHeaders.forEach((value, key) => headers.set(key, value as string));\n } else if (Array.isArray(additionalHeaders)) {\n additionalHeaders.forEach(([key, value]) => headers.set(key, value));\n } else {\n Object.entries(additionalHeaders).forEach(([key, value]) => headers.set(key, value as string));\n }\n }\n // biome-ignore-end lint/suspicious/useIterableCallbackReturn: not used\n\n // prepare body\n let body: BodyInit | undefined;\n if (skipSerialization(payload)) body = payload;\n else if (payload instanceof MultipartFormDataBody) {\n body = new Uint8Array(await payload.encode());\n headers.set(HEADER_NAME_CONTENT_TYPE, payload.getContentType());\n } else {\n body = JSON.stringify(payload);\n headers.set(HEADER_NAME_CONTENT_TYPE, 'application/json');\n }\n\n // make request\n try {\n const response = await fetch(url, { method, headers, body });\n const { ok: successful, status, statusText } = response;\n\n if (!successful) {\n try {\n const rawError = await response.text();\n return { headers: response.headers, successful, status, statusText, error: JSON.parse(rawError) };\n } catch (err) {\n if (err instanceof SyntaxError) {\n return {\n headers: response.headers,\n successful,\n status,\n statusText,\n error: {\n title: 'Unknown error',\n status,\n statusText: response.statusText,\n },\n };\n }\n\n const error: ProblemDetails = {\n title: (err instanceof Error ? err.message : undefined) ?? 'Unknown error',\n status: response.status,\n statusText: response.statusText,\n };\n\n return { headers: response.headers, successful, status, statusText, error };\n }\n }\n\n const contentLength = response.headers.get('content-length');\n let data = contentLength && contentLength !== '0' ? ((await response.json()) as T) : undefined;\n if (data && schema) {\n const result = await schema.safeParseAsync(data);\n if (!result.success) {\n return {\n headers: response.headers,\n successful: false,\n status,\n statusText,\n data,\n error: {\n title: 'application_error',\n detail: 'Schema validation error',\n errors: result.error.flatten().fieldErrors,\n status: response.status,\n statusText: response.statusText,\n },\n };\n }\n data = result.data;\n }\n\n return { headers: response.headers, data, successful, status, statusText };\n } catch (err) {\n return {\n headers: new Headers(),\n successful: false,\n status: -1,\n statusText: 'Application Error',\n error: {\n title: 'application_error',\n detail: `Unable to fetch data. The request could not be resolved. ${err}`,\n },\n };\n }\n }\n\n private makeUrl<T>(url: string, options?: InnerRequestOptions<T>): string {\n if (url.startsWith('http://') || url.startsWith('https://')) return url;\n const baseUrl = options?.baseUrl ?? this.baseUrl;\n return `${baseUrl}${url}`;\n }\n}\n\n/**\n * Whether to skip serialization of the payload.\n * @param payload The payload to check.\n * @returns true if the payload should not be serialized; otherwise, false.\n */\nfunction skipSerialization(\n payload: InnerRequestOptions<never>['payload'],\n): payload is FormData | URLSearchParams | ReadableStream | Blob | ArrayBuffer | string | undefined {\n return (\n payload instanceof FormData ||\n payload instanceof URLSearchParams ||\n payload instanceof ReadableStream ||\n payload instanceof Blob ||\n payload instanceof ArrayBuffer ||\n payload instanceof Buffer ||\n typeof payload === 'string' ||\n !payload\n );\n}\n\n/** Http request error */\nexport class HttpRequestError extends Error {\n constructor(\n message: string,\n public code: number,\n ) {\n super(message);\n }\n}\n\nexport function isErrorTemporaryFailure(e?: { code?: string | number; message?: string } | null): boolean {\n if (e instanceof HttpRequestError) {\n // Check for common HTTP status codes that indicate a temporary failure\n // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status\n switch (e.code) {\n case 502:\n return true; // 502 Bad Gateway\n case 503:\n return true; // 503 Service Unavailable\n case 504:\n return true; // 504 Gateway Timeout\n default:\n return false;\n }\n } else if (e?.code) {\n // Check for Node.js system errors that indicate a temporary failure\n // See: https://nodejs.org/api/errors.html#errors_common_system_errors\n switch (e.code) {\n case 'ETIMEDOUT':\n return true; // Operation timed out\n default:\n return false;\n }\n } else {\n return false;\n }\n}\n"],"mappings":";;;AAAA,MAAa,kCAAkC;AAC/C,MAAa,2BAA2B;AACxC,MAAa,qBAAqB;AAClC,MAAa,yBAAyB;AACtC,MAAa,4BAA4B;;;;ACFzC,IAAa,wBAAb,MAAmC;CACjC,AAAQ,OAAO;CACf,AAAQ,WAAmB,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,UAAU,EAAE;CACrE,AAAQ,QAA0C,EAAE;CAEpD,MAAa,SAA0B;AACrC,MAAI,KAAK,M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