@paklo/core 0.5.0 → 0.6.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/azure/index.d.mts +15 -15
- package/dist/azure/index.mjs +5 -5
- package/dist/dependabot/index.d.mts +3 -3
- package/dist/dependabot/index.mjs +5 -5
- package/dist/{dependabot-C6dqpHHO.mjs → dependabot-B3kgBX3l.mjs} +8 -10
- package/dist/dependabot-B3kgBX3l.mjs.map +1 -0
- package/dist/environment/index.mjs +1 -1
- package/dist/{environment-Bn2AKsNP.mjs → environment-Bym4B757.mjs} +1 -1
- package/dist/{environment-Bn2AKsNP.mjs.map → environment-Bym4B757.mjs.map} +1 -1
- package/dist/github/index.d.mts +1 -1
- package/dist/github/index.mjs +3 -3
- package/dist/github/index.mjs.map +1 -1
- package/dist/http/index.d.mts +1 -1
- package/dist/http/index.mjs +2 -2
- package/dist/{http-BVlIr273.mjs → http-CVZgS8c2.mjs} +2 -2
- package/dist/http-CVZgS8c2.mjs.map +1 -0
- package/dist/{index-Djd8_Qnk.d.mts → index-CcnWCDDV.d.mts} +125 -38
- package/dist/{index-B5hYujx0.d.mts → index-Z81896Ma.d.mts} +2 -2
- package/dist/{job-CYxNnXAx.mjs → job-N2pOBjBO.mjs} +56 -7
- package/dist/job-N2pOBjBO.mjs.map +1 -0
- package/dist/keygen.d.mts +32 -36
- package/dist/keygen.mjs +43 -50
- package/dist/keygen.mjs.map +1 -1
- package/dist/{logger-BhxvmS3E.mjs → logger-SYCv5hwZ.mjs} +2 -2
- package/dist/{logger-BhxvmS3E.mjs.map → logger-SYCv5hwZ.mjs.map} +1 -1
- package/dist/logger.mjs +2 -2
- package/dist/usage.d.mts +6 -2
- package/dist/usage.mjs +3 -3
- package/dist/usage.mjs.map +1 -1
- package/package.json +5 -5
- package/dist/dependabot-C6dqpHHO.mjs.map +0 -1
- package/dist/http-BVlIr273.mjs.map +0 -1
- package/dist/job-CYxNnXAx.mjs.map +0 -1
package/dist/azure/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { D as DependabotUpdatePullRequest,
|
|
2
|
-
import "../index-
|
|
3
|
-
import * as
|
|
1
|
+
import { D as DependabotUpdatePullRequest, Yt as DependabotConfig, ft as DependabotDependency, gt as DependabotExistingPR, mt as DependabotExistingGroupPR, r as DependabotCreatePullRequest, t as DependabotClosePullRequest, xn as VariableFinderFn } from "../index-CcnWCDDV.mjs";
|
|
2
|
+
import "../index-Z81896Ma.mjs";
|
|
3
|
+
import * as zod0 from "zod";
|
|
4
4
|
import * as zod_v4_core0 from "zod/v4/core";
|
|
5
5
|
|
|
6
6
|
//#region src/azure/types.d.ts
|
|
@@ -363,18 +363,18 @@ declare function getDependabotConfig({
|
|
|
363
363
|
//#region src/azure/utils.d.ts
|
|
364
364
|
declare function normalizeFilePath(path: string): string;
|
|
365
365
|
declare function normalizeBranchName(branch?: string): string | undefined;
|
|
366
|
-
declare const DependenciesPrPropertySchema:
|
|
367
|
-
'dependency-name':
|
|
368
|
-
'dependency-version':
|
|
369
|
-
directory:
|
|
370
|
-
removed:
|
|
371
|
-
}, zod_v4_core0.$strip>>,
|
|
372
|
-
'dependency-group-name':
|
|
373
|
-
dependencies:
|
|
374
|
-
'dependency-name':
|
|
375
|
-
'dependency-version':
|
|
376
|
-
directory:
|
|
377
|
-
removed:
|
|
366
|
+
declare const DependenciesPrPropertySchema: zod0.ZodUnion<[zod0.ZodArray<zod0.ZodObject<{
|
|
367
|
+
'dependency-name': zod0.ZodString;
|
|
368
|
+
'dependency-version': zod0.ZodOptional<zod0.ZodNullable<zod0.ZodString>>;
|
|
369
|
+
directory: zod0.ZodOptional<zod0.ZodNullable<zod0.ZodString>>;
|
|
370
|
+
removed: zod0.ZodOptional<zod0.ZodNullable<zod0.ZodBoolean>>;
|
|
371
|
+
}, zod_v4_core0.$strip>>, zod0.ZodObject<{
|
|
372
|
+
'dependency-group-name': zod0.ZodString;
|
|
373
|
+
dependencies: zod0.ZodArray<zod0.ZodObject<{
|
|
374
|
+
'dependency-name': zod0.ZodString;
|
|
375
|
+
'dependency-version': zod0.ZodOptional<zod0.ZodNullable<zod0.ZodString>>;
|
|
376
|
+
directory: zod0.ZodOptional<zod0.ZodNullable<zod0.ZodString>>;
|
|
377
|
+
removed: zod0.ZodOptional<zod0.ZodNullable<zod0.ZodBoolean>>;
|
|
378
378
|
}, zod_v4_core0.$strip>>;
|
|
379
379
|
}, zod_v4_core0.$strip>]>;
|
|
380
380
|
declare function buildPullRequestProperties(packageManager: string, dependencies: DependabotExistingPR[] | DependabotExistingGroupPR): {
|
package/dist/azure/index.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import "../environment-
|
|
2
|
-
import { t as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import "../dependabot-
|
|
1
|
+
import "../environment-Bym4B757.mjs";
|
|
2
|
+
import { r as isErrorTemporaryFailure, t as HttpRequestError } from "../http-CVZgS8c2.mjs";
|
|
3
|
+
import { t as logger } from "../logger-SYCv5hwZ.mjs";
|
|
4
|
+
import { F as parseDependabotConfig, M as POSSIBLE_CONFIG_FILE_PATHS, c as DependabotExistingGroupPRSchema, l as DependabotExistingPRSchema } from "../job-N2pOBjBO.mjs";
|
|
5
|
+
import "../dependabot-B3kgBX3l.mjs";
|
|
6
6
|
import * as path from "node:path";
|
|
7
7
|
import { existsSync } from "node:fs";
|
|
8
8
|
import { readFile } from "node:fs/promises";
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import "../index-
|
|
3
|
-
export { CertificateAuthority, CertificateAuthoritySchema, CreateApiServerAppOptions, DEFAULT_EXPERIMENTS, DEPENDABOT_DEFAULT_AUTHOR_EMAIL, DEPENDABOT_DEFAULT_AUTHOR_NAME, DependabotAllowCondition, DependabotAllowConditionSchema, DependabotAllowed, DependabotAllowedSchema, DependabotClosePullRequest, DependabotClosePullRequestSchema, DependabotCommand, DependabotCommandSchema, DependabotCommitMessage, DependabotCommitMessageSchema, DependabotCommitOptions, DependabotCommitOptionsSchema, DependabotCondition, DependabotConditionSchema, DependabotConfig, DependabotConfigSchema, DependabotCooldown, DependabotCooldownSchema, DependabotCreatePullRequest, DependabotCreatePullRequestSchema, DependabotCredential, DependabotCredentialSchema, DependabotDependency, DependabotDependencyFile, DependabotDependencyFileSchema, DependabotDependencySchema, DependabotEcosystemMeta, DependabotEcosystemMetaSchema, DependabotEcosystemVersionManager, DependabotEcosystemVersionManagerSchema, DependabotExistingGroupPR, DependabotExistingGroupPRSchema, DependabotExistingPR, DependabotExistingPRSchema, DependabotExperiments, DependabotExperimentsSchema, DependabotGroup, DependabotGroupJob, DependabotGroupJobSchema, DependabotGroupRuleJob, DependabotGroupRuleJobSchema, DependabotGroupSchema, DependabotIgnoreCondition, DependabotIgnoreConditionSchema, DependabotIncrementMetric, DependabotIncrementMetricSchema, DependabotJobBuilder, DependabotJobBuilderOutput, DependabotJobConfig, DependabotJobConfigSchema, DependabotJobFile, DependabotJobFileSchema, DependabotMarkAsProcessed, DependabotMarkAsProcessedSchema, DependabotMetric, DependabotMetricSchema, DependabotMultiEcosystemGroup, DependabotMultiEcosystemGroupSchema, DependabotPackageManager, DependabotPackageManagerSchema, DependabotProxyConfig, DependabotProxyConfigSchema, DependabotPullRequestBranchName, DependabotRecordEcosystemMeta, DependabotRecordEcosystemMetaSchema, DependabotRecordEcosystemVersions, DependabotRecordEcosystemVersionsSchema, DependabotRecordUpdateJobError, DependabotRecordUpdateJobErrorSchema, DependabotRecordUpdateJobUnknownError, DependabotRecordUpdateJobUnknownErrorSchema, DependabotRegistry, DependabotRegistrySchema, DependabotRequest, DependabotRequestSchema, DependabotRequestType, DependabotRequestTypeSchema, DependabotRequirement, DependabotRequirementSchema, DependabotRequirementSource, DependabotRequirementSourceSchema, DependabotSchedule, DependabotScheduleSchema, DependabotSecurityAdvisory, DependabotSecurityAdvisorySchema, DependabotSource, DependabotSourceInfo, DependabotSourceProvider, DependabotSourceProviderSchema, DependabotSourceSchema, DependabotTokenType, DependabotUpdate, DependabotUpdateDependencyList, DependabotUpdateDependencyListSchema, DependabotUpdatePullRequest, DependabotUpdatePullRequestSchema, DependabotUpdateSchema, FetchedFiles, FileFetcherInput, FileUpdaterInput, GitAuthor, POSSIBLE_CONFIG_FILE_PATHS, PackageEcosystem, PackageEcosystemSchema, VariableFinderFn, VersioningStrategy, VersioningStrategySchema, convertPlaceholder, createApiServerApp, extractPlaceholder, getBranchNameForUpdate, makeRandomJobId, mapAllowedUpdatesFromDependabotConfigToJobConfig, mapCredentials, mapExperiments, mapGroupsFromDependabotConfigToJobConfig, mapIgnoreConditionsFromDependabotConfigToJobConfig, mapPackageEcosystemToPackageManager, mapSecurityAdvisories, mapSourceFromDependabotConfigToJobConfig, mapVersionStrategyToRequirementsUpdateStrategy, parseDependabotConfig, parseExperiments, parseRegistries, parseUpdates, sanitizeRef, validateConfiguration };
|
|
1
|
+
import { $ as sanitizeRef, $t as DependabotGroup, A as DependabotRequest, At as DependabotProxyConfig, B as mapAllowedUpdatesFromDependabotConfigToJobConfig, Bt as DependabotSourceProviderSchema, C as DependabotRecordUpdateJobUnknownError, Cn as extractPlaceholder, Ct as DependabotGroupRuleJobSchema, D as DependabotUpdatePullRequest, Dt as DependabotJobFileSchema, E as DependabotUpdateDependencyListSchema, En as GitAuthor, Et as DependabotJobFile, F as createApiServerApp, Ft as DependabotRequirementSourceSchema, G as mapPackageEcosystemToPackageManager, Gt as DependabotAllowCondition, H as mapExperiments, Ht as FetchedFiles, I as DependabotJobBuilder, It as DependabotSecurityAdvisory, J as mapVersionStrategyToRequirementsUpdateStrategy, Jt as DependabotCommitMessageSchema, K as mapSecurityAdvisories, Kt as DependabotAllowConditionSchema, L as DependabotJobBuilderOutput, Lt as DependabotSecurityAdvisorySchema, M as DependabotRequestType, Mt as DependabotRequirement, N as DependabotRequestTypeSchema, Nt as DependabotRequirementSchema, O as DependabotUpdatePullRequestSchema, Ot as DependabotPackageManager, P as DependabotTokenType, Pt as DependabotRequirementSource, Q as getBranchNameForUpdate, Qt as DependabotCooldownSchema, R as DependabotSourceInfo, Rt as DependabotSource, S as DependabotRecordUpdateJobErrorSchema, Sn as convertPlaceholder, St as DependabotGroupRuleJob, T as DependabotUpdateDependencyList, Tn as DEPENDABOT_DEFAULT_AUTHOR_NAME, Tt as DependabotJobConfigSchema, U as mapGroupsFromDependabotConfigToJobConfig, Ut as FileFetcherInput, V as mapCredentials, Vt as DependabotSourceSchema, W as mapIgnoreConditionsFromDependabotConfigToJobConfig, Wt as FileUpdaterInput, X as parseExperiments, Xt as DependabotConfigSchema, Y as DEFAULT_EXPERIMENTS, Yt as DependabotConfig, Z as makeDirectoryKey, Zt as DependabotCooldown, _ as DependabotRecordEcosystemMeta, _n as parseDependabotConfig, _t as DependabotExistingPRSchema, a as DependabotDependencyFile, an as DependabotPullRequestBranchName, at as DependabotCommandSchema, b as DependabotRecordEcosystemVersionsSchema, bn as validateConfiguration, bt as DependabotGroupJob, c as DependabotEcosystemMetaSchema, cn as DependabotSchedule, ct as DependabotCondition, d as DependabotIncrementMetric, dn as DependabotUpdateSchema, dt as DependabotCredentialSchema, en as DependabotGroupSchema, et as CertificateAuthority, f as DependabotIncrementMetricSchema, fn as POSSIBLE_CONFIG_FILE_PATHS, ft as DependabotDependency, g as DependabotMetricSchema, gn as VersioningStrategySchema, gt as DependabotExistingPR, h as DependabotMetric, hn as VersioningStrategy, ht as DependabotExistingGroupPRSchema, i as DependabotCreatePullRequestSchema, in as DependabotMultiEcosystemGroupSchema, it as DependabotCommand, j as DependabotRequestSchema, jt as DependabotProxyConfigSchema, k as CreateApiServerAppOptions, kt as DependabotPackageManagerSchema, l as DependabotEcosystemVersionManager, ln as DependabotScheduleSchema, lt as DependabotConditionSchema, m as DependabotMarkAsProcessedSchema, mn as PackageEcosystemSchema, mt as DependabotExistingGroupPR, n as DependabotClosePullRequestSchema, nn as DependabotIgnoreConditionSchema, nt as DependabotAllowed, o as DependabotDependencyFileSchema, on as DependabotRegistry, ot as DependabotCommitOptions, p as DependabotMarkAsProcessed, pn as PackageEcosystem, pt as DependabotDependencySchema, q as mapSourceFromDependabotConfigToJobConfig, qt as DependabotCommitMessage, r as DependabotCreatePullRequest, rn as DependabotMultiEcosystemGroup, rt as DependabotAllowedSchema, s as DependabotEcosystemMeta, sn as DependabotRegistrySchema, st as DependabotCommitOptionsSchema, t as DependabotClosePullRequest, tn as DependabotIgnoreCondition, tt as CertificateAuthoritySchema, u as DependabotEcosystemVersionManagerSchema, un as DependabotUpdate, ut as DependabotCredential, v as DependabotRecordEcosystemMetaSchema, vn as parseRegistries, vt as DependabotExperiments, w as DependabotRecordUpdateJobUnknownErrorSchema, wn as DEPENDABOT_DEFAULT_AUTHOR_EMAIL, wt as DependabotJobConfig, x as DependabotRecordUpdateJobError, xn as VariableFinderFn, xt as DependabotGroupJobSchema, y as DependabotRecordEcosystemVersions, yn as parseUpdates, yt as DependabotExperimentsSchema, z as makeRandomJobId, zt as DependabotSourceProvider } from "../index-CcnWCDDV.mjs";
|
|
2
|
+
import "../index-Z81896Ma.mjs";
|
|
3
|
+
export { CertificateAuthority, CertificateAuthoritySchema, CreateApiServerAppOptions, DEFAULT_EXPERIMENTS, DEPENDABOT_DEFAULT_AUTHOR_EMAIL, DEPENDABOT_DEFAULT_AUTHOR_NAME, DependabotAllowCondition, DependabotAllowConditionSchema, DependabotAllowed, DependabotAllowedSchema, DependabotClosePullRequest, DependabotClosePullRequestSchema, DependabotCommand, DependabotCommandSchema, DependabotCommitMessage, DependabotCommitMessageSchema, DependabotCommitOptions, DependabotCommitOptionsSchema, DependabotCondition, DependabotConditionSchema, DependabotConfig, DependabotConfigSchema, DependabotCooldown, DependabotCooldownSchema, DependabotCreatePullRequest, DependabotCreatePullRequestSchema, DependabotCredential, DependabotCredentialSchema, DependabotDependency, DependabotDependencyFile, DependabotDependencyFileSchema, DependabotDependencySchema, DependabotEcosystemMeta, DependabotEcosystemMetaSchema, DependabotEcosystemVersionManager, DependabotEcosystemVersionManagerSchema, DependabotExistingGroupPR, DependabotExistingGroupPRSchema, DependabotExistingPR, DependabotExistingPRSchema, DependabotExperiments, DependabotExperimentsSchema, DependabotGroup, DependabotGroupJob, DependabotGroupJobSchema, DependabotGroupRuleJob, DependabotGroupRuleJobSchema, DependabotGroupSchema, DependabotIgnoreCondition, DependabotIgnoreConditionSchema, DependabotIncrementMetric, DependabotIncrementMetricSchema, DependabotJobBuilder, DependabotJobBuilderOutput, DependabotJobConfig, DependabotJobConfigSchema, DependabotJobFile, DependabotJobFileSchema, DependabotMarkAsProcessed, DependabotMarkAsProcessedSchema, DependabotMetric, DependabotMetricSchema, DependabotMultiEcosystemGroup, DependabotMultiEcosystemGroupSchema, DependabotPackageManager, DependabotPackageManagerSchema, DependabotProxyConfig, DependabotProxyConfigSchema, DependabotPullRequestBranchName, DependabotRecordEcosystemMeta, DependabotRecordEcosystemMetaSchema, DependabotRecordEcosystemVersions, DependabotRecordEcosystemVersionsSchema, DependabotRecordUpdateJobError, DependabotRecordUpdateJobErrorSchema, DependabotRecordUpdateJobUnknownError, DependabotRecordUpdateJobUnknownErrorSchema, DependabotRegistry, DependabotRegistrySchema, DependabotRequest, DependabotRequestSchema, DependabotRequestType, DependabotRequestTypeSchema, DependabotRequirement, DependabotRequirementSchema, DependabotRequirementSource, DependabotRequirementSourceSchema, DependabotSchedule, DependabotScheduleSchema, DependabotSecurityAdvisory, DependabotSecurityAdvisorySchema, DependabotSource, DependabotSourceInfo, DependabotSourceProvider, DependabotSourceProviderSchema, DependabotSourceSchema, DependabotTokenType, DependabotUpdate, DependabotUpdateDependencyList, DependabotUpdateDependencyListSchema, DependabotUpdatePullRequest, DependabotUpdatePullRequestSchema, DependabotUpdateSchema, FetchedFiles, FileFetcherInput, FileUpdaterInput, GitAuthor, POSSIBLE_CONFIG_FILE_PATHS, PackageEcosystem, PackageEcosystemSchema, VariableFinderFn, VersioningStrategy, VersioningStrategySchema, convertPlaceholder, createApiServerApp, extractPlaceholder, getBranchNameForUpdate, makeDirectoryKey, makeRandomJobId, mapAllowedUpdatesFromDependabotConfigToJobConfig, mapCredentials, mapExperiments, mapGroupsFromDependabotConfigToJobConfig, mapIgnoreConditionsFromDependabotConfigToJobConfig, mapPackageEcosystemToPackageManager, mapSecurityAdvisories, mapSourceFromDependabotConfigToJobConfig, mapVersionStrategyToRequirementsUpdateStrategy, parseDependabotConfig, parseExperiments, parseRegistries, parseUpdates, sanitizeRef, validateConfiguration };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "../environment-
|
|
2
|
-
import "../logger-
|
|
3
|
-
import { A as DependabotScheduleSchema, B as extractPlaceholder, C as DependabotCommitMessageSchema, D as DependabotIgnoreConditionSchema, E as DependabotGroupSchema, F as parseDependabotConfig, I as parseRegistries, L as parseUpdates, M as POSSIBLE_CONFIG_FILE_PATHS, N as PackageEcosystemSchema, O as DependabotMultiEcosystemGroupSchema, P as VersioningStrategySchema, R as validateConfiguration, S as DependabotAllowConditionSchema, T as DependabotCooldownSchema, _ as DependabotRequirementSchema, a as DependabotConditionSchema, b as DependabotSourceProviderSchema, c as DependabotExistingGroupPRSchema, d as DependabotGroupJobSchema, f as DependabotGroupRuleJobSchema, g as DependabotProxyConfigSchema, h as DependabotPackageManagerSchema, i as DependabotCommitOptionsSchema, j as DependabotUpdateSchema, k as DependabotRegistrySchema, l as DependabotExistingPRSchema, m as DependabotJobFileSchema, n as DependabotAllowedSchema, o as DependabotCredentialSchema, p as DependabotJobConfigSchema, r as DependabotCommandSchema, s as DependabotDependencySchema, t as CertificateAuthoritySchema, u as DependabotExperimentsSchema, v as DependabotRequirementSourceSchema, w as DependabotConfigSchema, x as DependabotSourceSchema, y as DependabotSecurityAdvisorySchema, z as convertPlaceholder } from "../job-
|
|
4
|
-
import { A as parseExperiments, C as mapGroupsFromDependabotConfigToJobConfig, D as mapSourceFromDependabotConfigToJobConfig, E as mapSecurityAdvisories, M as sanitizeRef, N as DEPENDABOT_DEFAULT_AUTHOR_EMAIL, O as mapVersionStrategyToRequirementsUpdateStrategy, P as DEPENDABOT_DEFAULT_AUTHOR_NAME, S as mapExperiments, T as mapPackageEcosystemToPackageManager, _ as DependabotUpdatePullRequestSchema, a as DependabotCreatePullRequestSchema, b as mapAllowedUpdatesFromDependabotConfigToJobConfig, c as DependabotEcosystemVersionManagerSchema, d as DependabotMetricSchema, f as DependabotRecordEcosystemMetaSchema, g as DependabotUpdateDependencyListSchema, h as DependabotRecordUpdateJobUnknownErrorSchema, i as DependabotClosePullRequestSchema, j as getBranchNameForUpdate, k as DEFAULT_EXPERIMENTS, l as DependabotIncrementMetricSchema, m as DependabotRecordUpdateJobErrorSchema, n as DependabotRequestTypeSchema, o as DependabotDependencyFileSchema, p as DependabotRecordEcosystemVersionsSchema, r as createApiServerApp, s as DependabotEcosystemMetaSchema, t as DependabotRequestSchema, u as DependabotMarkAsProcessedSchema, v as DependabotJobBuilder, w as mapIgnoreConditionsFromDependabotConfigToJobConfig, x as mapCredentials, y as makeRandomJobId } from "../dependabot-
|
|
1
|
+
import "../environment-Bym4B757.mjs";
|
|
2
|
+
import "../logger-SYCv5hwZ.mjs";
|
|
3
|
+
import { A as DependabotScheduleSchema, B as extractPlaceholder, C as DependabotCommitMessageSchema, D as DependabotIgnoreConditionSchema, E as DependabotGroupSchema, F as parseDependabotConfig, I as parseRegistries, L as parseUpdates, M as POSSIBLE_CONFIG_FILE_PATHS, N as PackageEcosystemSchema, O as DependabotMultiEcosystemGroupSchema, P as VersioningStrategySchema, R as validateConfiguration, S as DependabotAllowConditionSchema, T as DependabotCooldownSchema, V as makeDirectoryKey, _ as DependabotRequirementSchema, a as DependabotConditionSchema, b as DependabotSourceProviderSchema, c as DependabotExistingGroupPRSchema, d as DependabotGroupJobSchema, f as DependabotGroupRuleJobSchema, g as DependabotProxyConfigSchema, h as DependabotPackageManagerSchema, i as DependabotCommitOptionsSchema, j as DependabotUpdateSchema, k as DependabotRegistrySchema, l as DependabotExistingPRSchema, m as DependabotJobFileSchema, n as DependabotAllowedSchema, o as DependabotCredentialSchema, p as DependabotJobConfigSchema, r as DependabotCommandSchema, s as DependabotDependencySchema, t as CertificateAuthoritySchema, u as DependabotExperimentsSchema, v as DependabotRequirementSourceSchema, w as DependabotConfigSchema, x as DependabotSourceSchema, y as DependabotSecurityAdvisorySchema, z as convertPlaceholder } from "../job-N2pOBjBO.mjs";
|
|
4
|
+
import { A as parseExperiments, C as mapGroupsFromDependabotConfigToJobConfig, D as mapSourceFromDependabotConfigToJobConfig, E as mapSecurityAdvisories, M as sanitizeRef, N as DEPENDABOT_DEFAULT_AUTHOR_EMAIL, O as mapVersionStrategyToRequirementsUpdateStrategy, P as DEPENDABOT_DEFAULT_AUTHOR_NAME, S as mapExperiments, T as mapPackageEcosystemToPackageManager, _ as DependabotUpdatePullRequestSchema, a as DependabotCreatePullRequestSchema, b as mapAllowedUpdatesFromDependabotConfigToJobConfig, c as DependabotEcosystemVersionManagerSchema, d as DependabotMetricSchema, f as DependabotRecordEcosystemMetaSchema, g as DependabotUpdateDependencyListSchema, h as DependabotRecordUpdateJobUnknownErrorSchema, i as DependabotClosePullRequestSchema, j as getBranchNameForUpdate, k as DEFAULT_EXPERIMENTS, l as DependabotIncrementMetricSchema, m as DependabotRecordUpdateJobErrorSchema, n as DependabotRequestTypeSchema, o as DependabotDependencyFileSchema, p as DependabotRecordEcosystemVersionsSchema, r as createApiServerApp, s as DependabotEcosystemMetaSchema, t as DependabotRequestSchema, u as DependabotMarkAsProcessedSchema, v as DependabotJobBuilder, w as mapIgnoreConditionsFromDependabotConfigToJobConfig, x as mapCredentials, y as makeRandomJobId } from "../dependabot-B3kgBX3l.mjs";
|
|
5
5
|
|
|
6
|
-
export { CertificateAuthoritySchema, DEFAULT_EXPERIMENTS, DEPENDABOT_DEFAULT_AUTHOR_EMAIL, DEPENDABOT_DEFAULT_AUTHOR_NAME, DependabotAllowConditionSchema, DependabotAllowedSchema, DependabotClosePullRequestSchema, DependabotCommandSchema, DependabotCommitMessageSchema, DependabotCommitOptionsSchema, DependabotConditionSchema, DependabotConfigSchema, DependabotCooldownSchema, DependabotCreatePullRequestSchema, DependabotCredentialSchema, DependabotDependencyFileSchema, DependabotDependencySchema, DependabotEcosystemMetaSchema, DependabotEcosystemVersionManagerSchema, DependabotExistingGroupPRSchema, DependabotExistingPRSchema, DependabotExperimentsSchema, DependabotGroupJobSchema, DependabotGroupRuleJobSchema, DependabotGroupSchema, DependabotIgnoreConditionSchema, DependabotIncrementMetricSchema, DependabotJobBuilder, DependabotJobConfigSchema, DependabotJobFileSchema, DependabotMarkAsProcessedSchema, DependabotMetricSchema, DependabotMultiEcosystemGroupSchema, DependabotPackageManagerSchema, DependabotProxyConfigSchema, DependabotRecordEcosystemMetaSchema, DependabotRecordEcosystemVersionsSchema, DependabotRecordUpdateJobErrorSchema, DependabotRecordUpdateJobUnknownErrorSchema, DependabotRegistrySchema, DependabotRequestSchema, DependabotRequestTypeSchema, DependabotRequirementSchema, DependabotRequirementSourceSchema, DependabotScheduleSchema, DependabotSecurityAdvisorySchema, DependabotSourceProviderSchema, DependabotSourceSchema, DependabotUpdateDependencyListSchema, DependabotUpdatePullRequestSchema, DependabotUpdateSchema, POSSIBLE_CONFIG_FILE_PATHS, PackageEcosystemSchema, VersioningStrategySchema, convertPlaceholder, createApiServerApp, extractPlaceholder, getBranchNameForUpdate, makeRandomJobId, mapAllowedUpdatesFromDependabotConfigToJobConfig, mapCredentials, mapExperiments, mapGroupsFromDependabotConfigToJobConfig, mapIgnoreConditionsFromDependabotConfigToJobConfig, mapPackageEcosystemToPackageManager, mapSecurityAdvisories, mapSourceFromDependabotConfigToJobConfig, mapVersionStrategyToRequirementsUpdateStrategy, parseDependabotConfig, parseExperiments, parseRegistries, parseUpdates, sanitizeRef, validateConfiguration };
|
|
6
|
+
export { CertificateAuthoritySchema, DEFAULT_EXPERIMENTS, DEPENDABOT_DEFAULT_AUTHOR_EMAIL, DEPENDABOT_DEFAULT_AUTHOR_NAME, DependabotAllowConditionSchema, DependabotAllowedSchema, DependabotClosePullRequestSchema, DependabotCommandSchema, DependabotCommitMessageSchema, DependabotCommitOptionsSchema, DependabotConditionSchema, DependabotConfigSchema, DependabotCooldownSchema, DependabotCreatePullRequestSchema, DependabotCredentialSchema, DependabotDependencyFileSchema, DependabotDependencySchema, DependabotEcosystemMetaSchema, DependabotEcosystemVersionManagerSchema, DependabotExistingGroupPRSchema, DependabotExistingPRSchema, DependabotExperimentsSchema, DependabotGroupJobSchema, DependabotGroupRuleJobSchema, DependabotGroupSchema, DependabotIgnoreConditionSchema, DependabotIncrementMetricSchema, DependabotJobBuilder, DependabotJobConfigSchema, DependabotJobFileSchema, DependabotMarkAsProcessedSchema, DependabotMetricSchema, DependabotMultiEcosystemGroupSchema, DependabotPackageManagerSchema, DependabotProxyConfigSchema, DependabotRecordEcosystemMetaSchema, DependabotRecordEcosystemVersionsSchema, DependabotRecordUpdateJobErrorSchema, DependabotRecordUpdateJobUnknownErrorSchema, DependabotRegistrySchema, DependabotRequestSchema, DependabotRequestTypeSchema, DependabotRequirementSchema, DependabotRequirementSourceSchema, DependabotScheduleSchema, DependabotSecurityAdvisorySchema, DependabotSourceProviderSchema, DependabotSourceSchema, DependabotUpdateDependencyListSchema, DependabotUpdatePullRequestSchema, DependabotUpdateSchema, POSSIBLE_CONFIG_FILE_PATHS, PackageEcosystemSchema, VersioningStrategySchema, convertPlaceholder, createApiServerApp, extractPlaceholder, getBranchNameForUpdate, makeDirectoryKey, makeRandomJobId, mapAllowedUpdatesFromDependabotConfigToJobConfig, mapCredentials, mapExperiments, mapGroupsFromDependabotConfigToJobConfig, mapIgnoreConditionsFromDependabotConfigToJobConfig, mapPackageEcosystemToPackageManager, mapSecurityAdvisories, mapSourceFromDependabotConfigToJobConfig, mapVersionStrategyToRequirementsUpdateStrategy, parseDependabotConfig, parseExperiments, parseRegistries, parseUpdates, sanitizeRef, validateConfiguration };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as logger } from "./logger-
|
|
2
|
-
import { s as DependabotDependencySchema } from "./job-
|
|
3
|
-
import { z } from "zod
|
|
1
|
+
import { t as logger } from "./logger-SYCv5hwZ.mjs";
|
|
2
|
+
import { s as DependabotDependencySchema } from "./job-N2pOBjBO.mjs";
|
|
3
|
+
import { z } from "zod";
|
|
4
4
|
import * as crypto$1 from "node:crypto";
|
|
5
5
|
import { zValidator } from "@hono/zod-validator";
|
|
6
6
|
import { Hono } from "hono";
|
|
@@ -105,7 +105,6 @@ var DependabotJobBuilder = class {
|
|
|
105
105
|
forDependenciesList({ id, command }) {
|
|
106
106
|
id ??= makeRandomJobId();
|
|
107
107
|
return {
|
|
108
|
-
jobId: id,
|
|
109
108
|
job: {
|
|
110
109
|
id,
|
|
111
110
|
command,
|
|
@@ -160,7 +159,6 @@ var DependabotJobBuilder = class {
|
|
|
160
159
|
vulnerabilities = securityVulnerabilities;
|
|
161
160
|
}
|
|
162
161
|
return {
|
|
163
|
-
jobId: id,
|
|
164
162
|
job: {
|
|
165
163
|
id,
|
|
166
164
|
command,
|
|
@@ -329,7 +327,7 @@ function mapCredentials({ sourceHostname, systemAccessUser, systemAccessToken, g
|
|
|
329
327
|
function makeRandomJobId() {
|
|
330
328
|
const array = new Uint32Array(1);
|
|
331
329
|
crypto.getRandomValues(array);
|
|
332
|
-
return array[0] % 1e10
|
|
330
|
+
return `${array[0] % 1e10}`;
|
|
333
331
|
}
|
|
334
332
|
|
|
335
333
|
//#endregion
|
|
@@ -487,7 +485,7 @@ const DependabotRequestSchema = z.discriminatedUnion("type", [
|
|
|
487
485
|
function createApiServerApp({ basePath = `/api/update_jobs`, authenticate, getJob, getCredentials, handle }) {
|
|
488
486
|
const app = new Hono().basePath(basePath);
|
|
489
487
|
function operation(type, schema, method) {
|
|
490
|
-
app.on(method || "post", `/:id/${type}`, zValidator("param", z.object({ id: z.
|
|
488
|
+
app.on(method || "post", `/:id/${type}`, zValidator("param", z.object({ id: z.string() })), async (context, next) => {
|
|
491
489
|
if (new URL(context.req.url).protocol === "https:") {
|
|
492
490
|
const { id } = context.req.valid("param");
|
|
493
491
|
const value = context.req.header("Authorization");
|
|
@@ -516,7 +514,7 @@ function createApiServerApp({ basePath = `/api/update_jobs`, authenticate, getJo
|
|
|
516
514
|
operation("record_ecosystem_meta", DependabotRecordEcosystemMetaSchema.array());
|
|
517
515
|
operation("increment_metric", DependabotIncrementMetricSchema);
|
|
518
516
|
operation("record_metrics", DependabotMetricSchema.array());
|
|
519
|
-
app.on("get", "/:id/details", zValidator("param", z.object({ id: z.
|
|
517
|
+
app.on("get", "/:id/details", zValidator("param", z.object({ id: z.string() })), async (context, next) => {
|
|
520
518
|
const { id } = context.req.valid("param");
|
|
521
519
|
const value = context.req.header("Authorization");
|
|
522
520
|
if (!value) return context.body(null, 401);
|
|
@@ -528,7 +526,7 @@ function createApiServerApp({ basePath = `/api/update_jobs`, authenticate, getJo
|
|
|
528
526
|
if (!job) return context.body(null, 204);
|
|
529
527
|
return context.json(job);
|
|
530
528
|
});
|
|
531
|
-
app.on("get", "/:id/credentials", zValidator("param", z.object({ id: z.
|
|
529
|
+
app.on("get", "/:id/credentials", zValidator("param", z.object({ id: z.string() })), async (context, next) => {
|
|
532
530
|
const { id } = context.req.valid("param");
|
|
533
531
|
const value = context.req.header("Authorization");
|
|
534
532
|
if (!value) return context.body(null, 401);
|
|
@@ -545,4 +543,4 @@ function createApiServerApp({ basePath = `/api/update_jobs`, authenticate, getJo
|
|
|
545
543
|
|
|
546
544
|
//#endregion
|
|
547
545
|
export { parseExperiments as A, mapGroupsFromDependabotConfigToJobConfig as C, mapSourceFromDependabotConfigToJobConfig as D, mapSecurityAdvisories as E, sanitizeRef as M, DEPENDABOT_DEFAULT_AUTHOR_EMAIL as N, mapVersionStrategyToRequirementsUpdateStrategy as O, DEPENDABOT_DEFAULT_AUTHOR_NAME as P, mapExperiments as S, mapPackageEcosystemToPackageManager as T, DependabotUpdatePullRequestSchema as _, DependabotCreatePullRequestSchema as a, mapAllowedUpdatesFromDependabotConfigToJobConfig as b, DependabotEcosystemVersionManagerSchema as c, DependabotMetricSchema as d, DependabotRecordEcosystemMetaSchema as f, DependabotUpdateDependencyListSchema as g, DependabotRecordUpdateJobUnknownErrorSchema as h, DependabotClosePullRequestSchema as i, getBranchNameForUpdate as j, DEFAULT_EXPERIMENTS as k, DependabotIncrementMetricSchema as l, DependabotRecordUpdateJobErrorSchema as m, DependabotRequestTypeSchema as n, DependabotDependencyFileSchema as o, DependabotRecordEcosystemVersionsSchema as p, createApiServerApp as r, DependabotEcosystemMetaSchema as s, DependabotRequestSchema as t, DependabotMarkAsProcessedSchema as u, DependabotJobBuilder as v, mapIgnoreConditionsFromDependabotConfigToJobConfig as w, mapCredentials as x, makeRandomJobId as y };
|
|
548
|
-
//# sourceMappingURL=dependabot-
|
|
546
|
+
//# sourceMappingURL=dependabot-B3kgBX3l.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dependabot-B3kgBX3l.mjs","names":["branchName: string","crypto","DEFAULT_EXPERIMENTS: DependabotExperiments","updatingPullRequest: boolean","updateDependencyGroupName: string | null","updateDependencyNames: string[] | null","vulnerabilities: SecurityVulnerability[] | undefined","success: boolean"],"sources":["../src/dependabot/author.ts","../src/dependabot/branch-name.ts","../src/dependabot/experiments.ts","../src/dependabot/job-builder.ts","../src/dependabot/update.ts","../src/dependabot/server.ts"],"sourcesContent":["export type GitAuthor = {\n name: string;\n email: string;\n};\n\nexport const DEPENDABOT_DEFAULT_AUTHOR_EMAIL = 'noreply@github.com';\nexport const DEPENDABOT_DEFAULT_AUTHOR_NAME = 'dependabot[bot]';\n","import * as crypto from 'node:crypto';\nimport type { PackageEcosystem } from './config';\nimport type { DependabotExistingPR } from './job';\n\n// TODO: figure out how to handle IDENTIFIER field (in a group) in branch naming\n// Docs: https://docs.github.com/en/code-security/dependabot/working-with-dependabot/dependabot-options-reference#groups--\n// -> An identifier for a group is used in branch names and pull request titles.\n\nexport function getBranchNameForUpdate(\n packageEcosystem: PackageEcosystem,\n targetBranchName: string | undefined,\n directory: string | undefined,\n dependencyGroupName: string | undefined,\n dependencies: DependabotExistingPR[],\n separator: string = '/',\n): string {\n // Based on dependabot-core implementation:\n // https://github.com/dependabot/dependabot-core/blob/main/common/lib/dependabot/pull_request_creator/branch_namer/solo_strategy.rb\n // https://github.com/dependabot/dependabot-core/blob/main/common/lib/dependabot/pull_request_creator/branch_namer/dependency_group_strategy.rb\n let branchName: string;\n const branchNameMightBeTooLong = dependencyGroupName || dependencies.length > 1;\n if (branchNameMightBeTooLong) {\n // Group/multi dependency update\n // e.g. dependabot/nuget/main/microsoft-3b49c54d9e\n const dependencyDigest = crypto\n .createHash('md5')\n .update(dependencies.map((d) => `${d['dependency-name']}-${d['dependency-version']}`).join(','))\n .digest('hex')\n .substring(0, 10);\n branchName = `${dependencyGroupName || 'multi'}-${dependencyDigest}`;\n } else {\n // Single dependency update\n // e.g. dependabot/nuget/main/Microsoft.Extensions.Logging-1.0.0\n const dependencyNames = dependencies\n .map((d) => d['dependency-name'])\n .join('-and-')\n .replace(/[:[]]/g, '-') // Replace `:` and `[]` with `-`\n .replace(/@/g, ''); // Remove `@`\n const versionSuffix = dependencies[0]?.removed ? 'removed' : dependencies[0]?.['dependency-version'];\n branchName = `${dependencyNames}-${versionSuffix}`;\n }\n\n return sanitizeRef(\n [\n 'dependabot',\n packageEcosystem,\n targetBranchName,\n // normalize directory to remove leading/trailing slashes and replace remaining ones with the separator\n directory\n ?.replace(/^\\/+|\\/+$/g, '')\n .replace(/\\//g, separator),\n branchName,\n ],\n separator,\n );\n}\n\nexport function sanitizeRef(refParts: (string | undefined)[], separator: string): string {\n // Based on dependabot-core implementation:\n // https://github.com/dependabot/dependabot-core/blob/fc31ae64f492dc977cfe6773ab13fb6373aabec4/common/lib/dependabot/pull_request_creator/branch_namer/base.rb#L99\n\n // This isn't a complete implementation of git's ref validation, but it\n // covers most cases that crop up. Its list of allowed characters is a\n // bit stricter than git's, but that's for cosmetic reasons.\n return (\n refParts\n // Join the parts with the separator, ignore empty parts\n .filter((p) => p && p.trim().length > 0)\n .join(separator)\n // Remove forbidden characters (those not already replaced elsewhere)\n .replace(/[^A-Za-z0-9/\\-_.(){}]/g, '')\n // Slashes can't be followed by periods\n .replace(/\\/\\./g, '/dot-')\n // Squeeze out consecutive periods and slashes\n .replace(/\\.+/g, '.')\n .replace(/\\/+/g, '/')\n // Trailing periods are forbidden\n .replace(/\\.$/, '')\n );\n}\n","import type { DependabotExperiments } from './job';\n\n// The default experiments known to be used by the GitHub Dependabot service.\n// This changes often, update as needed by extracting them from a Dependabot GitHub Action run.\n// e.g. https://github.com/mburumaxwell/dependabot-azure-devops/actions/workflows/dependabot/dependabot-updates\nexport const DEFAULT_EXPERIMENTS: DependabotExperiments = {\n 'record-ecosystem-versions': true,\n 'record-update-job-unknown-error': true,\n 'proxy-cached': true,\n 'move-job-token': true,\n 'dependency-change-validation': true,\n 'enable-file-parser-python-local': true,\n 'npm-fallback-version-above-v6': true,\n 'enable-record-ecosystem-meta': true,\n 'enable-corepack-for-npm-and-yarn': true,\n 'enable-shared-helpers-command-timeout': true,\n 'enable-dependabot-setting-up-cronjob': true,\n 'enable-engine-version-detection': true,\n 'avoid-duplicate-updates-package-json': true,\n 'allow-refresh-for-existing-pr-dependencies': true,\n 'allow-refresh-group-with-all-dependencies': true,\n 'exclude-local-composer-packages': true,\n 'enable-enhanced-error-details-for-updater': true,\n 'gradle-lockfile-updater': true,\n 'enable-exclude-paths-subdirectory-manifest-files': true,\n 'group-membership-enforcement': true,\n 'deprecate-close-command': true,\n 'deprecate-reopen-command': true,\n 'deprecate-merge-command': true,\n 'deprecate-cancel-merge-command': true,\n 'deprecate-squash-merge-command': true,\n};\n\n/**\n * Parses a comma-separated list of key=value pairs representing experiments.\n * @param raw A comma-separated list of key=value pairs representing experiments.\n * @returns A map of experiment names to their values.\n */\nexport function parseExperiments(raw?: string): DependabotExperiments | undefined {\n return raw\n ?.split(',')\n .filter((entry) => entry.trim() !== '') // <-- filter out empty entries\n .reduce((acc, cur) => {\n const [key, value] = cur.split('=', 2);\n acc[key!] = value || true;\n return acc;\n }, {} as DependabotExperiments);\n}\n","import type { SecurityVulnerability } from '@/github';\nimport type {\n DependabotAllowCondition,\n DependabotConfig,\n DependabotGroup,\n DependabotIgnoreCondition,\n DependabotRegistry,\n DependabotUpdate,\n PackageEcosystem,\n VersioningStrategy,\n} from './config';\nimport type {\n DependabotAllowed,\n DependabotCondition,\n DependabotCredential,\n DependabotExistingGroupPR,\n DependabotExistingPR,\n DependabotExperiments,\n DependabotGroupJob,\n DependabotJobConfig,\n DependabotPackageManager,\n DependabotSecurityAdvisory,\n DependabotSource,\n DependabotSourceProvider,\n} from './job';\n\nexport type DependabotSourceInfo = {\n provider: DependabotSourceProvider;\n hostname: string;\n 'api-endpoint': string;\n 'repository-slug': string;\n};\n\nexport type DependabotJobBuilderOutput = {\n job: DependabotJobConfig;\n credentials: DependabotCredential[];\n};\n\n/**\n * Class for building dependabot job objects\n */\nexport class DependabotJobBuilder {\n private readonly config: DependabotConfig;\n private readonly update: DependabotUpdate;\n private readonly experiments: DependabotExperiments;\n private readonly debug: boolean;\n\n private readonly packageManager: DependabotPackageManager;\n private readonly source: DependabotSource;\n private readonly credentials: DependabotCredential[];\n\n constructor({\n source,\n config,\n update,\n systemAccessUser,\n systemAccessToken,\n githubToken,\n experiments,\n debug,\n }: {\n source: DependabotSourceInfo;\n config: DependabotConfig;\n update: DependabotUpdate;\n experiments: DependabotExperiments;\n systemAccessUser?: string;\n systemAccessToken?: string;\n githubToken?: string;\n /** Determines if verbose log messages are logged */\n debug: boolean;\n }) {\n this.config = config;\n this.update = update;\n this.experiments = experiments;\n this.debug = debug;\n\n this.packageManager = mapPackageEcosystemToPackageManager(update['package-ecosystem']);\n this.source = mapSourceFromDependabotConfigToJobConfig(source, update);\n this.credentials = mapCredentials({\n sourceHostname: source.hostname,\n systemAccessUser,\n systemAccessToken,\n githubToken,\n registries: config.registries,\n });\n }\n\n /**\n * Create a dependabot update job that updates nothing, but will discover the dependency list for a package ecosystem\n */\n public forDependenciesList({\n id,\n command,\n }: {\n id?: string;\n command: DependabotJobConfig['command'];\n }): DependabotJobBuilderOutput {\n id ??= makeRandomJobId();\n return {\n job: {\n id: id,\n command: command,\n 'package-manager': this.packageManager,\n 'updating-a-pull-request': false,\n dependencies: null,\n 'allowed-updates': [{ 'dependency-type': 'direct', 'update-type': 'all' }],\n 'ignore-conditions': [{ 'dependency-name': '*' }],\n 'security-updates-only': false,\n 'security-advisories': [],\n source: this.source,\n 'update-subdependencies': false,\n 'existing-pull-requests': [],\n 'existing-group-pull-requests': [],\n experiments: this.experiments,\n 'requirements-update-strategy': null,\n 'lockfile-only': false,\n 'commit-message-options': {\n prefix: null,\n 'prefix-development': null,\n 'include-scope': null,\n },\n 'vendor-dependencies': false,\n 'repo-private': true,\n debug: this.debug,\n },\n credentials: this.credentials,\n };\n }\n\n /**\n * Create a dependabot update job that updates all dependencies for a package ecosystem\n */\n public forUpdate({\n id,\n command,\n dependencyNamesToUpdate,\n existingPullRequests,\n pullRequestToUpdate,\n securityVulnerabilities,\n }: {\n id?: string;\n command: DependabotJobConfig['command'];\n dependencyNamesToUpdate?: string[];\n existingPullRequests: (DependabotExistingPR[] | DependabotExistingGroupPR)[];\n pullRequestToUpdate?: DependabotExistingPR[] | DependabotExistingGroupPR;\n securityVulnerabilities?: SecurityVulnerability[];\n }): DependabotJobBuilderOutput {\n id ??= makeRandomJobId();\n const securityOnlyUpdate = this.update['open-pull-requests-limit'] === 0;\n\n let updatingPullRequest: boolean;\n let updateDependencyGroupName: string | null = null;\n let updateDependencyNames: string[] | null;\n let vulnerabilities: SecurityVulnerability[] | undefined;\n\n if (pullRequestToUpdate) {\n updatingPullRequest = true;\n updateDependencyGroupName = Array.isArray(pullRequestToUpdate)\n ? null\n : pullRequestToUpdate['dependency-group-name'];\n updateDependencyNames = (\n Array.isArray(pullRequestToUpdate) ? pullRequestToUpdate : pullRequestToUpdate.dependencies\n )?.map((d) => d['dependency-name']);\n vulnerabilities = securityVulnerabilities?.filter((v) => updateDependencyNames?.includes(v.package.name));\n } else {\n updatingPullRequest = false;\n const names = dependencyNamesToUpdate?.length ? dependencyNamesToUpdate : null;\n updateDependencyNames =\n securityOnlyUpdate && names\n ? names?.filter((d) => securityVulnerabilities?.find((v) => v.package.name === d))\n : names;\n vulnerabilities = securityVulnerabilities;\n }\n\n return {\n job: {\n id: id,\n command: command,\n 'package-manager': this.packageManager,\n 'updating-a-pull-request': updatingPullRequest || false,\n 'dependency-group-to-refresh': updateDependencyGroupName,\n 'dependency-groups': mapGroupsFromDependabotConfigToJobConfig(this.update.groups),\n dependencies: updateDependencyNames,\n 'allowed-updates': mapAllowedUpdatesFromDependabotConfigToJobConfig(this.update.allow, securityOnlyUpdate),\n 'ignore-conditions': mapIgnoreConditionsFromDependabotConfigToJobConfig(this.update.ignore),\n 'security-updates-only': securityOnlyUpdate,\n 'security-advisories': mapSecurityAdvisories(vulnerabilities),\n source: this.source,\n 'update-subdependencies': false,\n 'existing-pull-requests': existingPullRequests.filter((pr) => Array.isArray(pr)),\n 'existing-group-pull-requests': existingPullRequests.filter(\n (pr): pr is DependabotExistingGroupPR => !Array.isArray(pr),\n ),\n 'commit-message-options': {\n prefix: this.update['commit-message']?.prefix ?? null,\n 'prefix-development': this.update['commit-message']?.['prefix-development'] ?? null,\n 'include-scope':\n this.update['commit-message']?.include?.toLocaleLowerCase()?.trim() === 'scope' ? true : null,\n },\n cooldown: this.update.cooldown,\n experiments: mapExperiments(this.experiments),\n 'reject-external-code':\n this.update['insecure-external-code-execution']?.toLocaleLowerCase()?.trim() === 'allow',\n 'requirements-update-strategy': mapVersionStrategyToRequirementsUpdateStrategy(\n this.update['versioning-strategy'],\n ),\n 'lockfile-only': this.update['versioning-strategy'] === 'lockfile-only',\n 'vendor-dependencies': this.update.vendor ?? false,\n 'repo-private': true,\n debug: this.debug,\n 'proxy-log-response-body-on-auth-failure': true,\n 'max-updater-run-time': 2700,\n 'enable-beta-ecosystems': this.config['enable-beta-ecosystems'] || false,\n // Updates across ecosystems is still in development\n // See https://github.com/dependabot/dependabot-core/issues/8126\n // https://github.com/dependabot/dependabot-core/pull/12339\n // It needs to merged in the core repo first before we support it\n // However, to match current job configs and to prevent surprises, we disable it\n 'multi-ecosystem-update': false,\n 'exclude-paths': this.update['exclude-paths'],\n },\n credentials: this.credentials,\n };\n }\n}\n\nexport function mapPackageEcosystemToPackageManager(ecosystem: PackageEcosystem): DependabotPackageManager {\n // Map the dependabot config \"package ecosystem\" to the equivalent dependabot-core/cli \"package manager\".\n // Config values: https://docs.github.com/en/code-security/dependabot/working-with-dependabot/dependabot-options-reference#package-ecosystem-\n // Core/CLI values: https://github.com/dependabot/dependabot-core/blob/main/common/lib/dependabot/config/file.rb#L60-L81\n switch (ecosystem) {\n case 'docker-compose':\n return 'docker_compose';\n case 'dotnet-sdk':\n return 'dotnet_sdk';\n case 'github-actions':\n return 'github_actions';\n case 'gitsubmodule':\n return 'submodules';\n case 'gomod':\n return 'go_modules';\n case 'mix':\n return 'hex';\n case 'npm':\n return 'npm_and_yarn';\n // Additional aliases, sometimes used for convenience\n case 'pipenv':\n return 'pip';\n case 'pip-compile':\n return 'pip';\n case 'poetry':\n return 'pip';\n case 'pnpm':\n return 'npm_and_yarn';\n case 'rust-toolchain':\n return 'rust_toolchain';\n case 'yarn':\n return 'npm_and_yarn';\n default:\n return ecosystem;\n }\n}\n\nexport function mapSourceFromDependabotConfigToJobConfig(\n source: DependabotSourceInfo,\n update: DependabotUpdate,\n): DependabotSource {\n return {\n provider: source.provider,\n 'api-endpoint': source['api-endpoint'],\n hostname: source.hostname,\n repo: source['repository-slug'],\n branch: update['target-branch'],\n commit: null, // use latest commit of target branch\n directory: update.directory,\n directories: update.directories,\n };\n}\n\nexport function mapVersionStrategyToRequirementsUpdateStrategy(strategy?: VersioningStrategy): string | null {\n if (!strategy) return null;\n switch (strategy) {\n case 'auto':\n return null;\n case 'increase':\n return 'bump_versions';\n case 'increase-if-necessary':\n return 'bump_versions_if_necessary';\n case 'lockfile-only':\n return 'lockfile_only';\n case 'widen':\n return 'widen_ranges';\n default:\n throw new Error(`Invalid dependabot.yaml versioning strategy option '${strategy}'`);\n }\n}\n\nexport function mapGroupsFromDependabotConfigToJobConfig(\n dependencyGroups?: Record<string, DependabotGroup | null>,\n): DependabotGroupJob[] {\n if (!dependencyGroups || !Object.keys(dependencyGroups).length) return [];\n return Object.keys(dependencyGroups)\n .filter((name) => dependencyGroups[name])\n .map((name) => {\n const group = dependencyGroups[name]!;\n return {\n name: name,\n 'applies-to': group['applies-to'],\n rules: {\n patterns: group.patterns?.length ? group.patterns : ['*'],\n 'exclude-patterns': group['exclude-patterns'],\n 'dependency-type': group['dependency-type'],\n 'update-types': group['update-types'],\n },\n } satisfies DependabotGroupJob;\n });\n}\n\nexport function mapAllowedUpdatesFromDependabotConfigToJobConfig(\n allowedUpdates?: DependabotAllowCondition[],\n securityOnlyUpdate?: boolean,\n): DependabotAllowed[] {\n // If no allow conditions are specified, update direct dependencies by default; This is what GitHub does.\n // NOTE: 'update-type' appears to be a deprecated config, but still appears in the dependabot-core model and GitHub Dependabot job logs.\n // See: https://github.com/dependabot/dependabot-core/blob/b3a0c1f86c20729494097ebc695067099f5b4ada/updater/lib/dependabot/job.rb#L253C1-L257C78\n if (!allowedUpdates) {\n return [\n {\n 'dependency-type': 'direct',\n 'update-type': securityOnlyUpdate ? 'security' : 'all',\n },\n ];\n }\n return allowedUpdates.map((allow) => {\n return {\n 'dependency-name': allow['dependency-name'],\n 'dependency-type': allow['dependency-type'],\n 'update-type': allow['update-type'],\n };\n });\n}\n\nexport function mapIgnoreConditionsFromDependabotConfigToJobConfig(\n ignoreConditions?: DependabotIgnoreCondition[],\n): DependabotCondition[] {\n if (!ignoreConditions) return [];\n return ignoreConditions.map((ignore) => {\n return {\n source: ignore.source,\n 'updated-at': ignore['updated-at'],\n 'dependency-name': ignore['dependency-name'] ?? '*',\n 'update-types': ignore['update-types'],\n\n // The dependabot.yml config docs are not very clear about acceptable values; after scanning dependabot-core and dependabot-cli,\n // this could either be a single version string (e.g. '>1.0.0'), or multiple version strings separated by commas (e.g. '>1.0.0, <2.0.0')\n 'version-requirement': Array.isArray(ignore.versions) ? (<string[]>ignore.versions)?.join(', ') : ignore.versions,\n } satisfies DependabotCondition;\n });\n}\n\nexport function mapExperiments(experiments?: DependabotExperiments): DependabotExperiments {\n experiments ??= {};\n return Object.keys(experiments).reduce((acc, key) => {\n // Experiment values are known to be either 'true', 'false', or a string value.\n // If the value is 'true' or 'false', convert it to a boolean type so that dependabot-core handles it correctly.\n const value = experiments[key];\n if (typeof value === 'string' && value?.toLocaleLowerCase() === 'true') {\n acc[key] = true;\n } else if (typeof value === 'string' && value?.toLocaleLowerCase() === 'false') {\n acc[key] = false;\n } else {\n if (typeof value === 'string' || typeof value === 'boolean') acc[key] = value;\n }\n return acc;\n }, {} as DependabotExperiments);\n}\n\nexport function mapSecurityAdvisories(securityVulnerabilities?: SecurityVulnerability[]): DependabotSecurityAdvisory[] {\n if (!securityVulnerabilities) return [];\n\n // A single security advisory can cause a vulnerability in multiple versions of a package.\n // We need to map each unique security advisory to a list of affected-versions and patched-versions.\n const vulnerabilitiesGroupedByPackageNameAndAdvisoryId = new Map<string, SecurityVulnerability[]>();\n for (const vuln of securityVulnerabilities) {\n const key = `${vuln.package.name}/${vuln.advisory.identifiers.map((i) => `${i.type}:${i.value}`).join('/')}`;\n if (!vulnerabilitiesGroupedByPackageNameAndAdvisoryId.has(key)) {\n vulnerabilitiesGroupedByPackageNameAndAdvisoryId.set(key, []);\n }\n vulnerabilitiesGroupedByPackageNameAndAdvisoryId.get(key)!.push(vuln);\n }\n return Array.from(vulnerabilitiesGroupedByPackageNameAndAdvisoryId.values()).map((vulns) => {\n return {\n 'dependency-name': vulns[0]!.package.name,\n 'affected-versions': vulns.map((v) => v.vulnerableVersionRange).filter((v) => v && v.length > 0),\n 'patched-versions': vulns\n .map((v) => v.firstPatchedVersion?.identifier)\n .filter((v) => v && v.length > 0)\n .map((v) => v!),\n 'unaffected-versions': [],\n } satisfies DependabotSecurityAdvisory;\n });\n}\n\nexport function mapCredentials({\n sourceHostname,\n systemAccessUser,\n systemAccessToken,\n githubToken,\n registries,\n}: {\n sourceHostname: string;\n systemAccessUser?: string;\n systemAccessToken?: string;\n githubToken?: string;\n registries?: Record<string, DependabotRegistry>;\n}): DependabotCredential[] {\n const credentials = [];\n\n // Required to authenticate with the git repository when cloning the source code\n if (systemAccessToken) {\n credentials.push({\n type: 'git_source',\n host: sourceHostname,\n username: (systemAccessUser ?? '').trim()?.length > 0 ? systemAccessUser : 'x-access-token',\n password: systemAccessToken,\n });\n }\n\n // Required to avoid rate-limiting errors when generating pull request descriptions (e.g. fetching release notes, commit messages, etc)\n if (githubToken) {\n credentials.push({\n type: 'git_source',\n host: 'github.com',\n username: 'x-access-token',\n password: githubToken,\n });\n }\n if (registries) {\n // TODO: only registries for the current update should be set\n // Required to authenticate with private package feeds when finding the latest version of dependencies.\n // The registries have already been worked on (see parseRegistries) so there is no need to do anything else.\n credentials.push(...Object.values(registries));\n }\n\n return credentials;\n}\n\nexport function makeRandomJobId(): string {\n const array = new Uint32Array(1);\n crypto.getRandomValues(array);\n return `${array[0]! % 10000000000}`; // Limit to 10 digits to match GitHub's job IDs\n}\n","import { z } from 'zod';\nimport { DependabotDependencySchema } from './job';\n\n// we use nullish() because it does optional() and allows the value to be set to null\n\nexport const DependabotDependencyFileSchema = z.object({\n content: z.string(),\n content_encoding: z.string().nullish(),\n deleted: z.boolean().nullish(),\n directory: z.string(),\n name: z.string(),\n operation: z.string(), // TODO: convert to enum?\n support_file: z.boolean().nullish(),\n symlink_target: z.string().nullish(),\n type: z.string().nullish(), // TODO: convert to enum?\n mode: z.string().nullish(),\n});\nexport type DependabotDependencyFile = z.infer<typeof DependabotDependencyFileSchema>;\n\nexport const DependabotUpdateDependencyListSchema = z.object({\n dependencies: DependabotDependencySchema.array(),\n dependency_files: z.string().array().nullish(),\n});\nexport type DependabotUpdateDependencyList = z.infer<typeof DependabotUpdateDependencyListSchema>;\n\nexport const DependabotCreatePullRequestSchema = z.object({\n 'base-commit-sha': z.string(),\n dependencies: DependabotDependencySchema.array(),\n 'updated-dependency-files': DependabotDependencyFileSchema.array(),\n 'pr-title': z.string(),\n 'pr-body': z.string().nullish(),\n 'commit-message': z.string(),\n 'dependency-group': z.record(z.string(), z.any()).nullish(),\n});\nexport type DependabotCreatePullRequest = z.infer<typeof DependabotCreatePullRequestSchema>;\n\nexport const DependabotUpdatePullRequestSchema = z.object({\n 'base-commit-sha': z.string(),\n 'dependency-names': z.string().array(),\n 'updated-dependency-files': DependabotDependencyFileSchema.array(),\n 'pr-title': z.string().nullish(), // this is usually excluded when working with dependabot-cli and an empty string if the API\n 'pr-body': z.string().nullish(), // this is usually excluded when working with dependabot-cli and an empty string if the API\n 'commit-message': z.string().nullish(), // this is usually excluded when working with dependabot-cli and an empty string if the API\n 'dependency-group': z.record(z.string(), z.any()).nullish(),\n});\nexport type DependabotUpdatePullRequest = z.infer<typeof DependabotUpdatePullRequestSchema>;\n\nexport const DependabotClosePullRequestSchema = z.object({\n 'dependency-names': z.string().array(),\n reason: z.string().nullish(), // TODO: convert to enum?\n});\nexport type DependabotClosePullRequest = z.infer<typeof DependabotClosePullRequestSchema>;\n\nexport const DependabotMarkAsProcessedSchema = z.object({\n 'base-commit-sha': z.string().nullish(),\n});\nexport type DependabotMarkAsProcessed = z.infer<typeof DependabotMarkAsProcessedSchema>;\n\nexport const DependabotRecordUpdateJobErrorSchema = z.object({\n 'error-type': z.string(),\n 'error-details': z.record(z.string(), z.any()).nullish(),\n});\nexport type DependabotRecordUpdateJobError = z.infer<typeof DependabotRecordUpdateJobErrorSchema>;\n\nexport const DependabotRecordUpdateJobUnknownErrorSchema = z.object({\n 'error-type': z.string(),\n 'error-details': z.record(z.string(), z.any()).nullish(),\n});\nexport type DependabotRecordUpdateJobUnknownError = z.infer<typeof DependabotRecordUpdateJobUnknownErrorSchema>;\n\nexport const DependabotRecordEcosystemVersionsSchema = z.object({\n ecosystem_versions: z.record(z.string(), z.any()).nullish(),\n});\nexport type DependabotRecordEcosystemVersions = z.infer<typeof DependabotRecordEcosystemVersionsSchema>;\n\nexport const DependabotEcosystemVersionManagerSchema = z.object({\n name: z.string(),\n version: z.string(),\n raw_version: z.string(),\n requirement: z.record(z.string(), z.any()).nullish(),\n});\nexport type DependabotEcosystemVersionManager = z.infer<typeof DependabotEcosystemVersionManagerSchema>;\n\nexport const DependabotEcosystemMetaSchema = z.object({\n name: z.string(),\n package_manager: DependabotEcosystemVersionManagerSchema.nullish(),\n version: DependabotEcosystemVersionManagerSchema.nullish(),\n});\nexport type DependabotEcosystemMeta = z.infer<typeof DependabotEcosystemMetaSchema>;\n\nexport const DependabotRecordEcosystemMetaSchema = z.object({\n ecosystem: DependabotEcosystemMetaSchema,\n});\nexport type DependabotRecordEcosystemMeta = z.infer<typeof DependabotRecordEcosystemMetaSchema>;\n\nexport const DependabotIncrementMetricSchema = z.object({\n metric: z.string(),\n tags: z.record(z.string(), z.any()).nullish(),\n});\nexport type DependabotIncrementMetric = z.infer<typeof DependabotIncrementMetricSchema>;\n\nexport const DependabotMetricSchema = z.object({\n metric: z.string(),\n type: z.enum(['increment', 'gauge', 'distribution', 'histogram']),\n value: z.number().nullish(),\n values: z.number().array().nullish(),\n tags: z.record(z.string(), z.string()).nullish(),\n});\nexport type DependabotMetric = z.infer<typeof DependabotMetricSchema>;\n","import { zValidator } from '@hono/zod-validator';\nimport { Hono } from 'hono';\nimport { type ZodType, z } from 'zod';\nimport { logger } from '@/logger';\nimport type { DependabotCredential, DependabotJobConfig } from './job';\nimport {\n DependabotClosePullRequestSchema,\n DependabotCreatePullRequestSchema,\n DependabotIncrementMetricSchema,\n DependabotMarkAsProcessedSchema,\n DependabotMetricSchema,\n DependabotRecordEcosystemMetaSchema,\n DependabotRecordEcosystemVersionsSchema,\n DependabotRecordUpdateJobErrorSchema,\n DependabotRecordUpdateJobUnknownErrorSchema,\n DependabotUpdateDependencyListSchema,\n DependabotUpdatePullRequestSchema,\n} from './update';\n\nexport const DependabotRequestTypeSchema = z.enum([\n 'create_pull_request',\n 'update_pull_request',\n 'close_pull_request',\n 'record_update_job_error',\n 'record_update_job_unknown_error',\n 'mark_as_processed',\n 'update_dependency_list',\n 'record_ecosystem_versions',\n 'record_ecosystem_meta',\n 'increment_metric',\n 'record_metrics',\n]);\nexport type DependabotRequestType = z.infer<typeof DependabotRequestTypeSchema>;\n\nexport const DependabotRequestSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('create_pull_request'), data: DependabotCreatePullRequestSchema }),\n z.object({ type: z.literal('update_pull_request'), data: DependabotUpdatePullRequestSchema }),\n z.object({ type: z.literal('close_pull_request'), data: DependabotClosePullRequestSchema }),\n z.object({ type: z.literal('record_update_job_error'), data: DependabotRecordUpdateJobErrorSchema }),\n z.object({ type: z.literal('record_update_job_unknown_error'), data: DependabotRecordUpdateJobUnknownErrorSchema }),\n z.object({ type: z.literal('mark_as_processed'), data: DependabotMarkAsProcessedSchema }),\n z.object({ type: z.literal('update_dependency_list'), data: DependabotUpdateDependencyListSchema }),\n z.object({ type: z.literal('record_ecosystem_versions'), data: DependabotRecordEcosystemVersionsSchema }),\n z.object({ type: z.literal('record_ecosystem_meta'), data: DependabotRecordEcosystemMetaSchema.array() }),\n z.object({ type: z.literal('increment_metric'), data: DependabotIncrementMetricSchema }),\n z.object({ type: z.literal('record_metrics'), data: DependabotMetricSchema.array() }),\n]);\nexport type DependabotRequest = z.infer<typeof DependabotRequestSchema>;\n\nexport type DependabotTokenType = 'job' | 'credentials';\n\n/**\n * Function type for authenticating requests.\n * @param type - The type of authentication ('job' or 'credentials').\n * @param id - The ID of the dependabot job.\n * @param value - The authentication value (e.g., API key).\n * @returns A promise that resolves to a boolean indicating whether the authentication was successful.\n */\ntype AuthenticatorFunc = (type: DependabotTokenType, id: string, value: string) => Promise<boolean>;\n\n/**\n * Handler function for processing dependabot requests.\n * @param id - The ID of the dependabot job.\n * @param request - The dependabot request to handle.\n * @returns A promise that resolves to the result of handling the request.\n */\ntype HandlerFunc = (id: string, request: DependabotRequest) => Promise<boolean>;\n\n/**\n * Function for getting a dependabot job config by ID.\n * @param id - The ID of the dependabot job.\n * @returns A promise that resolves to the dependabot job config, or undefined if not found.\n */\ntype GetJobFunc = (id: string) => Promise<DependabotJobConfig | undefined>;\n\n/**\n * Function for getting dependabot credentials by job ID.\n * @param id - The ID of the dependabot job.\n * @returns A promise that resolves to an array of dependabot credentials, or undefined if not found.\n */\ntype GetCredentialsFunc = (id: string) => Promise<DependabotCredential[] | undefined>;\n\nexport type CreateApiServerAppOptions = {\n /**\n * Base path for the endpoints.\n * @default `/api/update_jobs`\n */\n basePath?: string;\n\n /** Handler function for authenticating requests. */\n authenticate: AuthenticatorFunc;\n\n /** Function for getting a dependabot job by ID. */\n getJob: GetJobFunc;\n\n /** Function for getting dependabot credentials by job ID. */\n getCredentials: GetCredentialsFunc;\n\n /** Handler function for processing the operations. */\n handle: HandlerFunc;\n};\n\n/**\n * Creates an API server application for handling dependabot update jobs.\n * The endpoints in the server application have paths in the format: `/api/update_jobs/:id/{operation}`,\n * where `:id` is the job ID and `{operation}` is one of the defined operations e.g. `create_pull_request`.\n *\n * You should set the job endpoint URL in the job container to\n * `http://<host>:<port>/api/update_jobs/:id` where `<host>` and `<port>` are the host and port\n *\n * These endpoints are protected using the provided API key.\n * @param params - The parameters for creating the API server application.\n * @returns The created API server application.\n */\nexport function createApiServerApp({\n basePath = `/api/update_jobs`,\n authenticate,\n getJob,\n getCredentials,\n handle,\n}: CreateApiServerAppOptions): Hono {\n // Setup app with base path and middleware\n const app = new Hono().basePath(basePath);\n\n // Handle endpoints:\n // - POST request to /create_pull_request\n // - POST request to /update_pull_request\n // - POST request to /close_pull_request\n // - POST request to /record_update_job_error\n // - POST request to /record_update_job_unknown_error\n // - PATCH request to /mark_as_processed\n // - POST request to /update_dependency_list\n // - POST request to /record_ecosystem_versions\n // - POST request to /record_ecosystem_meta\n // - POST request to /increment_metric\n\n function operation<T extends ZodType>(type: DependabotRequestType, schema: T, method?: string) {\n app.on(\n method || 'post',\n `/:id/${type}`,\n zValidator('param', z.object({ id: z.string() })),\n async (context, next) => {\n /**\n * Do not authenticate in scenarios where the server is not using HTTPS because the\n * dependabot proxy will not send the job token over HTTP, yet trying to get HTTPS to work\n * with localhost (self-signed certs) against docker (host.docker.internal) is complicated.\n */\n const url = new URL(context.req.url);\n const isHTTPS = url.protocol === 'https:';\n if (isHTTPS) {\n const { id } = context.req.valid('param');\n const value = context.req.header('Authorization');\n if (!value) return context.body(null, 401);\n const valid = await authenticate('job', id, value);\n if (!valid) return context.body(null, 403);\n } else {\n logger.trace(`Skipping authentication because it is not secure ${context.req.url}`);\n }\n await next();\n },\n zValidator('json', z.object({ data: schema })),\n async (context) => {\n const { id } = context.req.valid('param');\n const { data } = context.req.valid('json') as { data: z.infer<typeof schema> };\n // biome-ignore lint/suspicious/noExplicitAny: generic\n const success: boolean = await handle(id, { type, data: data as any });\n return context.body(null, success ? 204 : 400);\n },\n );\n }\n\n operation('create_pull_request', DependabotCreatePullRequestSchema);\n operation('update_pull_request', DependabotUpdatePullRequestSchema);\n operation('close_pull_request', DependabotClosePullRequestSchema);\n operation('record_update_job_error', DependabotRecordUpdateJobErrorSchema);\n operation('record_update_job_unknown_error', DependabotRecordUpdateJobUnknownErrorSchema);\n operation('mark_as_processed', DependabotMarkAsProcessedSchema, 'patch');\n operation('update_dependency_list', DependabotUpdateDependencyListSchema);\n operation('record_ecosystem_versions', DependabotRecordEcosystemVersionsSchema);\n operation('record_ecosystem_meta', DependabotRecordEcosystemMetaSchema.array());\n operation('increment_metric', DependabotIncrementMetricSchema);\n operation('record_metrics', DependabotMetricSchema.array());\n\n // Handle endpoints:\n // - GET request to /details\n // - GET request to /credentials\n app.on(\n 'get',\n '/:id/details',\n zValidator('param', z.object({ id: z.string() })),\n async (context, next) => {\n const { id } = context.req.valid('param');\n const value = context.req.header('Authorization');\n if (!value) return context.body(null, 401);\n const valid = await authenticate('job', id, value);\n if (!valid) return context.body(null, 403);\n await next();\n },\n async (context) => {\n const { id } = context.req.valid('param');\n const job = await getJob(id);\n if (!job) return context.body(null, 204);\n return context.json(job);\n },\n );\n app.on(\n 'get',\n '/:id/credentials',\n zValidator('param', z.object({ id: z.string() })),\n async (context, next) => {\n const { id } = context.req.valid('param');\n const value = context.req.header('Authorization');\n if (!value) return context.body(null, 401);\n const valid = await authenticate('credentials', id, value);\n if (!valid) return context.body(null, 403);\n await next();\n },\n async (context) => {\n const { id } = context.req.valid('param');\n const credentials = await getCredentials(id);\n if (!credentials) return context.body(null, 204);\n return context.json(credentials);\n },\n );\n\n return app;\n}\n"],"mappings":";;;;;;;;AAKA,MAAa,kCAAkC;AAC/C,MAAa,iCAAiC;;;;ACE9C,SAAgB,uBACd,kBACA,kBACA,WACA,qBACA,cACA,YAAoB,KACZ;CAIR,IAAIA;AAEJ,KADiC,uBAAuB,aAAa,SAAS,GAChD;EAG5B,MAAM,mBAAmBC,SACtB,WAAW,MAAM,CACjB,OAAO,aAAa,KAAK,MAAM,GAAG,EAAE,mBAAmB,GAAG,EAAE,wBAAwB,CAAC,KAAK,IAAI,CAAC,CAC/F,OAAO,MAAM,CACb,UAAU,GAAG,GAAG;AACnB,eAAa,GAAG,uBAAuB,QAAQ,GAAG;OAUlD,cAAa,GANW,aACrB,KAAK,MAAM,EAAE,mBAAmB,CAChC,KAAK,QAAQ,CACb,QAAQ,UAAU,IAAI,CACtB,QAAQ,MAAM,GAAG,CAEY,GADV,aAAa,IAAI,UAAU,YAAY,aAAa,KAAK;AAIjF,QAAO,YACL;EACE;EACA;EACA;EAEA,WACI,QAAQ,cAAc,GAAG,CAC1B,QAAQ,OAAO,UAAU;EAC5B;EACD,EACD,UACD;;AAGH,SAAgB,YAAY,UAAkC,WAA2B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I,GACF,OACA,oBACA,WAAW,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,EACjD,OAAO,SAAS,SAAS;EACvB,MAAM,EAAE,OAAO,QAAQ,IAAI,MAAM,QAAQ;EACzC,MAAM,QAAQ,QAAQ,IAAI,OAAO,gBAAgB;AACjD,MAAI,CAAC,MAAO,QAAO,QAAQ,KAAK,MAAM,IAAI;AAE1C,MAAI,CADU,MAAM,aAAa,eAAe,IAAI,MAAM,CAC9C,QAAO,QAAQ,KAAK,MAAM,IAAI;AAC1C,QAAM,MAAM;IAEd,OAAO,YAAY;EACjB,MAAM,EAAE,OAAO,QAAQ,IAAI,MAAM,QAAQ;EACzC,MAAM,cAAc,MAAM,eAAe,GAAG;AAC5C,MAAI,CAAC,YAAa,QAAO,QAAQ,KAAK,MAAM,IAAI;AAChD,SAAO,QAAQ,KAAK,YAAY;GAEnC;AAED,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"environment-Bn2AKsNP.mjs","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;;SAEhE;AACN;;;;;;ACrDJ,SAAgB,cAAwB;AACtC,KAAI,QAAQ,IAAI,6BAA8B,QAAO;UAE5C,QAAQ,IAAI,iCAAkC,QAAO;UACrD,QAAQ,IAAI,iBAAkB,QAAO;UACrC,QAAQ,IAAI,aAAc,QAAO;UACjC,QAAQ,IAAI,kBAAmB,QAAO;;;;;;;;;;ACEjD,SAAgB,mBAAmB,EAAE,aAAa,MAAM,gBAAgC;AAEtF,KAAI,YAAa,QAAO,oBAAoB,QAAQ,IAAI,QAAQ;AAGhE,KAAI,KAAM,QAAO;CAGjB,IAAI,QAAQ,kBAAkB;AAC9B,KAAI,SAAS,MAAM,SAAS,EAAG,QAAO;AAGtC,SAAQ,yBAAyB;AACjC,KAAI,SAAS,MAAM,SAAS,EAAG,QAAO;AAGtC,SAAQ,kBAAkB;AAC1B,KAAI,SAAS,MAAM,SAAS,EAAG,QAAO;AAGtC,SAAQ,QAAQ,IAAI;AACpB,KAAI,SAAS,MAAM,SAAS,EAAG,QAAO,WAAW;AAGjD,SAAQ,QAAQ,IAAI;AACpB,KAAI,SAAS,MAAM,SAAS,EAAG,QAAO;AAEtC,QAAO;;AAGT,SAAgB,mBAAuC;CAQrD,MAAM,SAAS,QAAQ,IAAI;CAC3B,MAAM,OAAO,QAAQ,IAAI;AACzB,KAAI,CAAC,UAAU,CAAC,KAAM,QAAO;AAC7B,QAAO,WAAW,KAAK,GAAG;;AAG5B,SAAgB,0BAA8C;CAQ5D,MAAM,QAAQ,QAAQ,IAAI;AAC1B,QAAO,QAAQ,WAAW,UAAU;;AAGtC,SAAgB,mBAAuC;CAerD,MAAM,gBADS,QAAQ,IAAI,6BACG,MAAM,uBAAuB;AAC3D,QAAO,gBAAgB,WAAW,cAAc,OAAO;;;;;AC1DzD,SAAS,iBAA8B;CACrC,MAAM,MAAM,QAAQ,IAAI;CACxB,MAAM,SAAS,WAAW;CAC1B,MAAM,MAAM,QAAQ;CACpB,MAAM,WAAW,aAAa;AAE9B,QAAO;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
|
+
{"version":3,"file":"environment-Bym4B757.mjs","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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,MAAM,QAAQ,IAAI;CACxB,MAAM,SAAS,WAAW;CAC1B,MAAM,MAAM,QAAQ;CACpB,MAAM,WAAW,aAAa;AAE9B,QAAO;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"}
|
package/dist/github/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { _ as createGitHubClient, 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 GitHubSecurityAdvisoryClient, o as PackageSchema, p as SecurityVulnerability, r as Package, s as SecurityAdvisory, t as FirstPatchedVersion, u as SecurityAdvisorySchema } from "../index-
|
|
1
|
+
import { _ as createGitHubClient, 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 GitHubSecurityAdvisoryClient, o as PackageSchema, p as SecurityVulnerability, r as Package, s as SecurityAdvisory, t as FirstPatchedVersion, u as SecurityAdvisorySchema } from "../index-Z81896Ma.mjs";
|
|
2
2
|
export { FirstPatchedVersion, GitHubSecurityAdvisoryClient, Package, PackageEcosystem, PackageEcosystemSchema, PackageSchema, SecurityAdvisory, SecurityAdvisoryIdentifierSchema, SecurityAdvisoryIdentifierType, SecurityAdvisorySchema, SecurityAdvisorySeverity, SecurityAdvisorySeveritySchema, SecurityVulnerability, SecurityVulnerabilitySchema, createGitHubClient, filterVulnerabilities, getGhsaPackageEcosystemFromDependabotPackageManager };
|
package/dist/github/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import "../environment-
|
|
2
|
-
import { t as logger } from "../logger-
|
|
3
|
-
import { z } from "zod
|
|
1
|
+
import "../environment-Bym4B757.mjs";
|
|
2
|
+
import { t as logger } from "../logger-SYCv5hwZ.mjs";
|
|
3
|
+
import { z } from "zod";
|
|
4
4
|
import { Octokit } from "octokit";
|
|
5
5
|
import * as semver from "semver";
|
|
6
6
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["results: T2[]","v"],"sources":["../../src/github/client.ts","../../src/github/ghsa.ts"],"sourcesContent":["import { Octokit } from 'octokit';\n\n/**\n * Creates an authenticated GitHub API client using Octokit.\n *\n * @param token - GitHub personal access token or fine-grained token with appropriate permissions\n * @returns Configured Octokit instance ready for API calls\n */\nexport function createGitHubClient({ token }: { token: string }): Octokit {\n return new Octokit({\n auth: token,\n // could add retry here perhaps?\n });\n}\n","import type { Octokit } from 'octokit';\nimport * as semver from 'semver';\nimport { z } from 'zod/v4';\n\nimport { logger } from '@/logger';\nimport { createGitHubClient } from './client';\n\n// we use nullish() because it does optional() and allows the value to be set to null\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 cvssSeverities {\n cvssV3 {\n score\n vectorString\n }\n cvssV4 {\n score\n vectorString\n }\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\nconst CweSchema = z.object({\n cweId: z.string(),\n name: z.string(),\n description: z.string(),\n});\n\nconst CvssSchema = z.object({\n score: z.number(),\n vectorString: z.string().nullish(),\n});\ntype Cvss = z.infer<typeof CvssSchema>;\n\nexport const SecurityAdvisorySchema = z.object({\n identifiers: z\n .object({\n type: z.union([SecurityAdvisoryIdentifierSchema, z.string()]),\n value: z.string(),\n })\n .array(),\n severity: SecurityAdvisorySeveritySchema.nullish(),\n summary: z.string(),\n description: z.string().nullish(),\n references: z.object({ url: z.string() }).array().nullish(),\n cvss: CvssSchema.nullish(),\n epss: z\n .object({\n percentage: z.number().nullish(),\n percentile: z.number().nullish(),\n })\n .nullish(),\n cwes: CweSchema.array().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\nconst CvssSeveritiesSchema = z.object({\n cvssV3: CvssSchema.nullish(),\n cvssV4: CvssSchema.nullish(),\n});\ntype CvssSeverities = z.infer<typeof CvssSeveritiesSchema>;\n\nconst GitHubSecurityVulnerabilitiesResponseSchema = z.object({\n securityVulnerabilities: z.object({\n nodes: z\n .object({\n advisory: SecurityAdvisorySchema.omit({ cvss: true /* incoming is cvssSeverities */ }).extend({\n cvssSeverities: CvssSeveritiesSchema,\n cwes: z.object({ nodes: CweSchema.array() }).nullish(),\n }),\n firstPatchedVersion: FirstPatchedVersionSchema.nullish(),\n vulnerableVersionRange: z.string(),\n })\n .array(),\n }),\n});\ntype GitHubSecurityVulnerabilitiesResponse = z.infer<typeof GitHubSecurityVulnerabilitiesResponseSchema>;\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 Security Advisory client\n */\nexport class GitHubSecurityAdvisoryClient {\n private readonly octokit: Octokit;\n\n /**\n * @param token GitHub personal access token with access to the GHSA API\n */\n constructor(token: string) {\n this.octokit = createGitHubClient({ token });\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\n function pickCvss(value: CvssSeverities): Cvss | undefined {\n // Pick the one with a non-zero score\n if (value.cvssV4 && value.cvssV4.score > 0) return value.cvssV4;\n if (value.cvssV3 && value.cvssV3.score > 0) return value.cvssV3;\n }\n\n try {\n const response = await this.octokit.graphql<GitHubSecurityVulnerabilitiesResponse>(\n GHSA_SECURITY_VULNERABILITIES_QUERY,\n variables,\n );\n const parsed = GitHubSecurityVulnerabilitiesResponseSchema.parse(response);\n const vulnerabilities = parsed.securityVulnerabilities.nodes;\n return (\n vulnerabilities\n ?.filter((v) => v.advisory != null)\n ?.map(\n (v) =>\n ({\n ...v,\n package: pkg,\n advisory: {\n ...v.advisory,\n cwes: v.advisory.cwes?.nodes,\n cvss: pickCvss(v.advisory.cvssSeverities),\n },\n }) satisfies SecurityVulnerability,\n ) || []\n );\n } catch (error) {\n logger.warn(`GHSA GraphQL request failed for package ${pkg.name}: ${error}. Continuing with other packages.`);\n return [];\n }\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":";;;;;;;;;;;;;AAQA,SAAgB,mBAAmB,EAAE,SAAqC;AACxE,QAAO,IAAI,QAAQ,EACjB,MAAM,OAEP,CAAC;;;;;ACHJ,MAAM,sCAAsC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD5C,MAAa,yBAAyB,EAAE,KAAK;CAC3C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAGF,MAAa,gBAAgB,EAAE,OAAO;CACpC,MAAM,EAAE,QAAQ;CAChB,SAAS,EAAE,QAAQ,CAAC,SAAS;CAC9B,CAAC;AAGF,MAAa,mCAAmC,EAAE,KAAK,CAAC,OAAO,OAAO,CAAC;AAGvE,MAAa,iCA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S,CAC3C,wBAAwB,OAGjD,QAAQ,MAAM,EAAE,YAAY,KAAK,EACjC,KACC,OACE;KACC,GAAG;KACH,SAAS;KACT,UAAU;MACR,GAAG,EAAE;MACL,MAAM,EAAE,SAAS,MAAM;MACvB,MAAM,SAAS,EAAE,SAAS,eAAe;MAC1C;KACF,EACJ,IAAI,EAAE;YAEJ,OAAO;AACd,WAAO,KAAK,2CAA2C,IAAI,KAAK,IAAI,MAAM,mCAAmC;AAC7G,WAAO,EAAE;;IAGd;;;;;;;;;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"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["results: T2[]","v"],"sources":["../../src/github/client.ts","../../src/github/ghsa.ts"],"sourcesContent":["import { Octokit } from 'octokit';\n\n/**\n * Creates an authenticated GitHub API client using Octokit.\n *\n * @param token - GitHub personal access token or fine-grained token with appropriate permissions\n * @returns Configured Octokit instance ready for API calls\n */\nexport function createGitHubClient({ token }: { token: string }): Octokit {\n return new Octokit({\n auth: token,\n // could add retry here perhaps?\n });\n}\n","import type { Octokit } from 'octokit';\nimport * as semver from 'semver';\nimport { z } from 'zod';\n\nimport { logger } from '@/logger';\nimport { createGitHubClient } from './client';\n\n// we use nullish() because it does optional() and allows the value to be set to null\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 cvssSeverities {\n cvssV3 {\n score\n vectorString\n }\n cvssV4 {\n score\n vectorString\n }\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\nconst CweSchema = z.object({\n cweId: z.string(),\n name: z.string(),\n description: z.string(),\n});\n\nconst CvssSchema = z.object({\n score: z.number(),\n vectorString: z.string().nullish(),\n});\ntype Cvss = z.infer<typeof CvssSchema>;\n\nexport const SecurityAdvisorySchema = z.object({\n identifiers: z\n .object({\n type: z.union([SecurityAdvisoryIdentifierSchema, z.string()]),\n value: z.string(),\n })\n .array(),\n severity: SecurityAdvisorySeveritySchema.nullish(),\n summary: z.string(),\n description: z.string().nullish(),\n references: z.object({ url: z.string() }).array().nullish(),\n cvss: CvssSchema.nullish(),\n epss: z\n .object({\n percentage: z.number().nullish(),\n percentile: z.number().nullish(),\n })\n .nullish(),\n cwes: CweSchema.array().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\nconst CvssSeveritiesSchema = z.object({\n cvssV3: CvssSchema.nullish(),\n cvssV4: CvssSchema.nullish(),\n});\ntype CvssSeverities = z.infer<typeof CvssSeveritiesSchema>;\n\nconst GitHubSecurityVulnerabilitiesResponseSchema = z.object({\n securityVulnerabilities: z.object({\n nodes: z\n .object({\n advisory: SecurityAdvisorySchema.omit({ cvss: true /* incoming is cvssSeverities */ }).extend({\n cvssSeverities: CvssSeveritiesSchema,\n cwes: z.object({ nodes: CweSchema.array() }).nullish(),\n }),\n firstPatchedVersion: FirstPatchedVersionSchema.nullish(),\n vulnerableVersionRange: z.string(),\n })\n .array(),\n }),\n});\ntype GitHubSecurityVulnerabilitiesResponse = z.infer<typeof GitHubSecurityVulnerabilitiesResponseSchema>;\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 Security Advisory client\n */\nexport class GitHubSecurityAdvisoryClient {\n private readonly octokit: Octokit;\n\n /**\n * @param token GitHub personal access token with access to the GHSA API\n */\n constructor(token: string) {\n this.octokit = createGitHubClient({ token });\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\n function pickCvss(value: CvssSeverities): Cvss | undefined {\n // Pick the one with a non-zero score\n if (value.cvssV4 && value.cvssV4.score > 0) return value.cvssV4;\n if (value.cvssV3 && value.cvssV3.score > 0) return value.cvssV3;\n }\n\n try {\n const response = await this.octokit.graphql<GitHubSecurityVulnerabilitiesResponse>(\n GHSA_SECURITY_VULNERABILITIES_QUERY,\n variables,\n );\n const parsed = GitHubSecurityVulnerabilitiesResponseSchema.parse(response);\n const vulnerabilities = parsed.securityVulnerabilities.nodes;\n return (\n vulnerabilities\n ?.filter((v) => v.advisory != null)\n ?.map(\n (v) =>\n ({\n ...v,\n package: pkg,\n advisory: {\n ...v.advisory,\n cwes: v.advisory.cwes?.nodes,\n cvss: pickCvss(v.advisory.cvssSeverities),\n },\n }) satisfies SecurityVulnerability,\n ) || []\n );\n } catch (error) {\n logger.warn(`GHSA GraphQL request failed for package ${pkg.name}: ${error}. Continuing with other packages.`);\n return [];\n }\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":";;;;;;;;;;;;;AAQA,SAAgB,mBAAmB,EAAE,SAAqC;AACxE,QAAO,IAAI,QAAQ,EACjB,MAAM,OAEP,CAAC;;;;;ACHJ,MAAM,sCAAsC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD5C,MAAa,yBAAyB,EAAE,KAAK;CAC3C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAGF,MAAa,gBAAgB,EAAE,OAAO;CACpC,MAAM,EAAE,QAAQ;CAChB,SAAS,EAAE,QAAQ,CAAC,SAAS;CAC9B,CAAC;AAGF,MAAa,mCAAmC,EAAE,KAAK,CAAC,OAAO,OAAO,CAAC;AAGvE,MAAa,iCAAiC,EAAE,KAAK;CAAC;CAAO;CAAY;CAAQ;CAAW,CAAC;AAG7F,MAAM,YAAY,EAAE,OAAO;CACzB,OAAO,EAAE,QAAQ;CACjB,MAAM,EAAE,QAAQ;CAChB,aAAa,EAAE,QAAQ;CACxB,CAAC;AAEF,MAAM,aAAa,EAAE,OAAO;CAC1B,OAAO,EAAE,QAAQ;CACjB,cAAc,EAAE,QAAQ,CAAC,SAAS;CACnC,CAAC;AAGF,MAAa,yBAAyB,EAAE,OAAO;CAC7C,aAAa,EACV,OAAO;EACN,MAAM,EAAE,MAAM,CAAC,kCAAkC,EAAE,QAAQ,CAAC,CAAC;EAC7D,OAAO,EAAE,QAAQ;EAClB,CAAC,CACD,OAAO;CACV,UAAU,+BAA+B,SAAS;CAClD,SAAS,EAAE,QAAQ;CACnB,aAAa,EAAE,QAAQ,CAAC,SAAS;CACjC,YAAY,EAAE,OAAO,EAAE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AAI,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"}
|
package/dist/http/index.d.mts
CHANGED
package/dist/http/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "../environment-
|
|
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-
|
|
1
|
+
import "../environment-Bym4B757.mjs";
|
|
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-CVZgS8c2.mjs";
|
|
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 };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as environment } from "./environment-
|
|
1
|
+
import { t as environment } from "./environment-Bym4B757.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/http/headers.ts
|
|
4
4
|
const HEADER_NAME_CONTENT_DISPOSITION = "Content-Disposition";
|
|
@@ -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-CVZgS8c2.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http-CVZgS8c2.mjs","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';\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,MAAM,WAAW,EACxB,OAAM,IAAI,MAAM,oDAAoD;EAGtE,MAAMA,OAAiD,EAAE;AAEzD,OAAK,MAAM,QAAQ,KAAK,OAAO;AAE7B,QAAK,KAAK,KAAK,KAAK,SAAS,MAAM;AAGnC,QAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,QAAQ,CACrD,MAAK,KAAK,GAAG,IAAI,IAAI,MAAM,MAAM;AAEnC,QAAK,KAAK,OAAO;AAGjB,QAAK,KAAK,KAAK,KAAK;AACpB,QAAK,KAAK,OAAO;;AAGnB,OAAK,KAAK,KAAK,KAAK,SAAS,QAAQ;EAErC,MAAMC,OAAiB,EAAE;AACzB,OAAK,MAAM,QAAQ,KACjB,KAAI,gBAAgB,KAAM,MAAK,KAAK,OAAO,KAAK,MAAM,KAAK,aAAa,CAAC,CAAC;WACjE,OAAO,SAAS,SAAU,MAAK,KAAK,OAAO,KAAK,MAAM,OAAO,CAAC;MAClE,MAAK,KAAK,KAAK;AAEtB,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