From 311292c28fcad4d4c3efb0b85ec3f23b2785a19f Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 3 Jun 2026 16:39:55 -0500 Subject: [PATCH 01/26] Cache the output of `codeql resolve languages` Repeated calls to `resolveLanguages()` will only pay the performance penalty of executing `codeql resolve languages` once. --- src/codeql.ts | 41 ++++++++++++++------------ src/environment.ts | 6 ++++ src/util.ts | 71 +++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 99 insertions(+), 19 deletions(-) diff --git a/src/codeql.ts b/src/codeql.ts index 5d78337d2e..0747830d09 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -731,26 +731,31 @@ async function getCodeQLForCmd( filterToLanguagesWithQueries: boolean; } = { filterToLanguagesWithQueries: false }, ) { - const codeqlArgs = [ - "resolve", - "languages", - "--format=betterjson", - "--extractor-options-verbosity=4", - "--extractor-include-aliases", - ...(filterToLanguagesWithQueries - ? ["--filter-to-languages-with-queries"] - : []), - ...getExtraOptionsFromEnv(["resolve", "languages"]), - ]; - const output = await runCli(cmd, codeqlArgs); + let result = util.getCachedCodeQlResolveLanguages(cmd); + if (result === undefined) { + const codeqlArgs = [ + "resolve", + "languages", + "--format=betterjson", + "--extractor-options-verbosity=4", + "--extractor-include-aliases", + ...(filterToLanguagesWithQueries + ? ["--filter-to-languages-with-queries"] + : []), + ...getExtraOptionsFromEnv(["resolve", "languages"]), + ]; + const output = await runCli(cmd, codeqlArgs); - try { - return JSON.parse(output) as ResolveLanguagesOutput; - } catch (e) { - throw new Error( - `Unexpected output from codeql resolve languages with --format=betterjson: ${e}`, - ); + try { + result = JSON.parse(output) as ResolveLanguagesOutput; + } catch (e) { + throw new Error( + `Unexpected output from codeql resolve languages with --format=betterjson: ${e}`, + ); + } + util.cacheCodeQlResolveLanguages(cmd, result); } + return result; }, async resolveBuildEnvironment( workingDir: string | undefined, diff --git a/src/environment.ts b/src/environment.ts index c3f54ebd27..1324abf280 100644 --- a/src/environment.ts +++ b/src/environment.ts @@ -23,6 +23,12 @@ export enum EnvVar { */ CODEQL_VERSION_INFO = "CODEQL_ACTION_CLI_VERSION_INFO", + /** + * `ResolveLanguagesOutput` for the CodeQL CLI, so later Actions steps can reuse it instead of + * invoking `codeql resolve languages` again. + */ + CODEQL_RESOLVE_LANGUAGES = "CODEQL_ACTION_CLI_RESOLVE_LANGUAGES", + /** Whether the CodeQL Action has invoked the Go autobuilder. */ DID_AUTOBUILD_GOLANG = "CODEQL_ACTION_DID_AUTOBUILD_GOLANG", diff --git a/src/util.ts b/src/util.ts index 200d68d2c2..a7833b2df3 100644 --- a/src/util.ts +++ b/src/util.ts @@ -10,7 +10,7 @@ import * as yaml from "js-yaml"; import * as semver from "semver"; import * as apiCompatibility from "./api-compatibility.json"; -import type { CodeQL, VersionInfo } from "./codeql"; +import type { CodeQL, VersionInfo, ResolveLanguagesOutput } from "./codeql"; import type { Pack } from "./config/db-config"; import type { Config } from "./config-utils"; import { EnvVar } from "./environment"; @@ -701,6 +701,75 @@ export function getCachedCodeQlVersion(cmd?: string): undefined | VersionInfo { return cachedCodeQlVersion; } +let cachedCodeQlResolveLanguages: undefined | ResolveLanguagesOutput = + undefined; + +interface PersistedResolveLanguagesOutput { + cmd: string; + output: ResolveLanguagesOutput; +} + +export function cacheCodeQlResolveLanguages( + cmd: string, + output: ResolveLanguagesOutput, +): void { + if (cachedCodeQlResolveLanguages !== undefined) { + throw new Error("cacheCodeQlResolveLanguages() should be called only once"); + } + cachedCodeQlResolveLanguages = output; + // Persist the output so that subsequent Actions steps, which run in separate + // processes, can reuse it rather than invoking `codeql resolve languages` again. We + // record the CLI path so that a different step using a different CodeQL bundle + // doesn't pick up a stale output. + core.exportVariable( + EnvVar.CODEQL_RESOLVE_LANGUAGES, + JSON.stringify({ cmd, output }), + ); +} + +function isPersistedResolveLanguagesOutput( + value: unknown, +): value is PersistedResolveLanguagesOutput { + return ( + typeof value === "object" && + value !== null && + typeof (value as Record).cmd === "string" && + typeof (value as Record).output === "object" && + (value as Record).output !== null + ); +} + +export function getCachedCodeQlResolveLanguages( + cmd?: string, +): undefined | ResolveLanguagesOutput { + if (cachedCodeQlResolveLanguages !== undefined) { + return cachedCodeQlResolveLanguages; + } + // Fall back to the value persisted by an earlier Actions step, if any. This is + // best-effort: any malformed or mismatched value is ignored so that the caller + // invokes `codeql resolve languages` instead. + const serialized = process.env[EnvVar.CODEQL_RESOLVE_LANGUAGES]; + if (!serialized) { + return undefined; + } + let persisted: unknown; + try { + persisted = JSON.parse(serialized); + } catch { + return undefined; + } + if ( + !isPersistedResolveLanguagesOutput(persisted) || + (cmd !== undefined && persisted.cmd !== cmd) + ) { + return undefined; + } + // Memoize the parsed value so that subsequent calls in this process don't + // re-parse the environment variable. + cachedCodeQlResolveLanguages = persisted.output; + return cachedCodeQlResolveLanguages; +} + export async function codeQlVersionAtLeast( codeql: CodeQL, requiredVersion: string, From 6010f85d81311aee3e4d090b444e82855e90740b Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 3 Jun 2026 16:41:50 -0500 Subject: [PATCH 02/26] Reimplement `resolveExtractor()` as wrapper over `resolveLanguages()` By wrapping `resolveLanguages()`, which is memoized, we can avoid executing `codeql resolve extractor` several times over the course of an analysis. --- src/codeql.ts | 31 +++++-------------------------- 1 file changed, 5 insertions(+), 26 deletions(-) diff --git a/src/codeql.ts b/src/codeql.ts index 0747830d09..626d1021a7 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -946,32 +946,11 @@ async function getCodeQLForCmd( await new toolrunner.ToolRunner(cmd, args).exec(); }, async resolveExtractor(language: Language): Promise { - // Request it using `format=json` so we don't need to strip the trailing new line generated by - // the CLI. - let extractorPath = ""; - await new toolrunner.ToolRunner( - cmd, - [ - "resolve", - "extractor", - "--format=json", - `--language=${language}`, - "--extractor-include-aliases", - ...getExtraOptionsFromEnv(["resolve", "extractor"]), - ], - { - silent: true, - listeners: { - stdout: (data) => { - extractorPath += data.toString(); - }, - stderr: (data) => { - process.stderr.write(data); - }, - }, - }, - ).exec(); - return JSON.parse(extractorPath) as string; + // A previous implementation executed `codeql resolve extractor`. + // This can be a bit slow due to the JVM startup cost. Instead, get + // the extractor path from resolveLanguages(), which caches its output. + const extractors = await this.resolveLanguages(); + return extractors[language][0]; }, async resolveQueriesStartingPacks(queries: string[]): Promise { const codeqlArgs = [ From 445107e23af9b5ae4b0e0d68e638eaf4da59d014 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Tue, 16 Jun 2026 17:11:58 -0500 Subject: [PATCH 03/26] Validate numbers, objects, and undefinables in the `json` module This commit adds a `number` validator`, an `object` validator, an `isNumber` predicate, and `undefinable()` to test optional-but-not-null properties. --- src/json/index.test.ts | 23 +++++++++++++++++++++++ src/json/index.ts | 35 ++++++++++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/json/index.test.ts b/src/json/index.test.ts index 825bbc0e70..d37a86c370 100644 --- a/src/json/index.test.ts +++ b/src/json/index.test.ts @@ -44,3 +44,26 @@ test("validateSchema - optional properties are optional", async (t) => { t.true(json.validateSchema(optionalSchema, { optionalKey: "" })); t.true(json.validateSchema(optionalSchema, { optionalKey: "foo" })); }); + +const undefinableSchema = { + optionalKey: json.undefinable(json.string), +}; + +test("validateSchema - undefinable properties are optional but reject null", async (t) => { + // Optional fields may be absent or explicitly undefined + t.true(json.validateSchema(undefinableSchema, {})); + t.true(json.validateSchema(undefinableSchema, { optionalKey: undefined })); + + // But, unlike `optional`, `null` is rejected + t.false(json.validateSchema(undefinableSchema, { optionalKey: null })); + + // And, if present, should have the expected type + t.false(json.validateSchema(undefinableSchema, { optionalKey: 0 })); + t.false(json.validateSchema(undefinableSchema, { optionalKey: 123 })); + t.false(json.validateSchema(undefinableSchema, { optionalKey: false })); + t.false(json.validateSchema(undefinableSchema, { optionalKey: true })); + t.false(json.validateSchema(undefinableSchema, { optionalKey: [] })); + t.false(json.validateSchema(undefinableSchema, { optionalKey: {} })); + t.true(json.validateSchema(undefinableSchema, { optionalKey: "" })); + t.true(json.validateSchema(undefinableSchema, { optionalKey: "foo" })); +}); diff --git a/src/json/index.ts b/src/json/index.ts index 8a1b60a178..4a3f65947a 100644 --- a/src/json/index.ts +++ b/src/json/index.ts @@ -30,6 +30,11 @@ export function isString(value: unknown): value is string { return typeof value === "string"; } +/** Asserts that `value` is a number. */ +export function isNumber(value: unknown): value is number { + return typeof value === "number"; +} + /** Asserts that `value` is either a string or undefined. */ export function isStringOrUndefined( value: unknown, @@ -55,7 +60,22 @@ export const string = { required: true, } as const satisfies Validator; -/** Transforms a validator to be optional. */ +/** A validator for number fields in schemas. */ +export const number = { + validate: isNumber, + required: true, +} as const satisfies Validator; + +/** A validator for object fields in schemas. */ +export const object = { + validate: isObject, + required: true, +} as const satisfies Validator>; + +/** + * Transforms a validator to be optional, accepting `undefined` or `null` for an + * absent value. + */ export function optional(validator: Validator) { return { validate: (val: unknown) => { @@ -65,6 +85,19 @@ export function optional(validator: Validator) { } as const satisfies Validator; } +/** + * Transforms a validator to be optional, accepting `undefined` for an absent + * value but, unlike `optional`, rejecting `null`. + */ +export function undefinable(validator: Validator) { + return { + validate: (val: unknown): val is T | undefined => { + return val === undefined || validator.validate(val); + }, + required: false, + } as const satisfies Validator; +} + /** Represents an arbitrary object schema. */ export type Schema = Record>; From 587fcb33c738fe65109c7fbcda01b693e9b9614a Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Tue, 16 Jun 2026 17:17:10 -0500 Subject: [PATCH 04/26] Refactor `isVersionInfo()`` to use `json` module --- src/util.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/util.ts b/src/util.ts index a7833b2df3..3bf0c0d61d 100644 --- a/src/util.ts +++ b/src/util.ts @@ -634,16 +634,16 @@ interface PersistedVersionInfo { } function isVersionInfo(x: unknown): x is VersionInfo { - const candidate = x as Partial | null; return ( - typeof candidate === "object" && - candidate !== null && - typeof candidate.version === "string" && - (candidate.features === undefined || - (typeof candidate.features === "object" && - candidate.features !== null)) && - (candidate.overlayVersion === undefined || - typeof candidate.overlayVersion === "number") + json.isObject(x) && + json.validateSchema( + { + version: json.string, + features: json.undefinable(json.object), + overlayVersion: json.undefinable(json.number), + }, + x, + ) ); } From 889ae42672fcfc9f2570842bca674d6989c02f69 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 17 Jun 2026 16:11:40 -0500 Subject: [PATCH 05/26] Refactor CLI executions into helper functions This provides a separation of concerns between the memoization and the execution. --- src/codeql.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/codeql.ts b/src/codeql.ts index 626d1021a7..23de25a7aa 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -731,8 +731,7 @@ async function getCodeQLForCmd( filterToLanguagesWithQueries: boolean; } = { filterToLanguagesWithQueries: false }, ) { - let result = util.getCachedCodeQlResolveLanguages(cmd); - if (result === undefined) { + async function runCliResolveLanguages() { const codeqlArgs = [ "resolve", "languages", @@ -747,12 +746,16 @@ async function getCodeQLForCmd( const output = await runCli(cmd, codeqlArgs); try { - result = JSON.parse(output) as ResolveLanguagesOutput; + return JSON.parse(output) as ResolveLanguagesOutput; } catch (e) { throw new Error( `Unexpected output from codeql resolve languages with --format=betterjson: ${e}`, ); } + } + let result = util.getCachedCodeQlResolveLanguages(cmd); + if (result === undefined) { + result = await runCliResolveLanguages(); util.cacheCodeQlResolveLanguages(cmd, result); } return result; From dc8e1e9aa030ff727aca68fda116800bf38b8eb3 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 17 Jun 2026 16:38:10 -0500 Subject: [PATCH 06/26] Refactor CLI JSON handling into a dedicated `runCliJson` function --- src/codeql.ts | 66 ++++++++++++++++++++++----------------------------- 1 file changed, 29 insertions(+), 37 deletions(-) diff --git a/src/codeql.ts b/src/codeql.ts index 23de25a7aa..0aa386a2d7 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -512,18 +512,17 @@ async function getCodeQLForCmd( return cmd; }, async getVersion() { + async function runCliVersion() { + return await runCliJson( + cmd, + ["version", "--format=json"], + { noStreamStdout: true }, + ); + } + let result = util.getCachedCodeQlVersion(cmd); if (result === undefined) { - const output = await runCli(cmd, ["version", "--format=json"], { - noStreamStdout: true, - }); - try { - result = JSON.parse(output) as VersionInfo; - } catch { - throw Error( - `Invalid JSON output from \`version --format=json\`: ${output}`, - ); - } + result = await runCliVersion(); util.cacheCodeQlVersion(cmd, result); } return result; @@ -774,15 +773,7 @@ async function getCodeQLForCmd( if (workingDir !== undefined) { codeqlArgs.push("--working-dir", workingDir); } - const output = await runCli(cmd, codeqlArgs); - - try { - return JSON.parse(output) as ResolveBuildEnvironmentOutput; - } catch (e) { - throw new Error( - `Unexpected output from codeql resolve build-environment: ${e} in\n${output}`, - ); - } + return await runCliJson(cmd, codeqlArgs); }, async databaseRunQueries( databasePath: string, @@ -963,15 +954,9 @@ async function getCodeQLForCmd( ...getExtraOptionsFromEnv(["resolve", "queries"]), ...queries, ]; - const output = await runCli(cmd, codeqlArgs, { noStreamStdout: true }); - - try { - return JSON.parse(output) as string[]; - } catch (e) { - throw new Error( - `Unexpected output from codeql resolve queries --format=startingpacks: ${e}`, - ); - } + return await runCliJson(cmd, codeqlArgs, { + noStreamStdout: true, + }); }, async resolveDatabase( databasePath: string, @@ -983,15 +968,9 @@ async function getCodeQLForCmd( "--format=json", ...getExtraOptionsFromEnv(["resolve", "database"]), ]; - const output = await runCli(cmd, codeqlArgs, { noStreamStdout: true }); - - try { - return JSON.parse(output) as ResolveDatabaseOutput; - } catch (e) { - throw new Error( - `Unexpected output from codeql resolve database --format=json: ${e}`, - ); - } + return await runCliJson(cmd, codeqlArgs, { + noStreamStdout: true, + }); }, async mergeResults( sarifFiles: string[], @@ -1147,6 +1126,19 @@ async function runCli( } } +async function runCliJson( + cmd: string, + args: string[] = [], + opts: { stdin?: string; noStreamStdout?: boolean } = {}, +): Promise { + const output = await runCli(cmd, args, opts); + try { + return JSON.parse(output) as T; + } catch { + throw Error(`Invalid JSON output from \`${args.join(" ")}\`: ${output}`); + } +} + /** * Writes the code scanning configuration that is to be used by the CLI. * From a602287f735f45c60ac6df611e76a9e54a28347b Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 17 Jun 2026 23:45:01 -0500 Subject: [PATCH 07/26] Refactor CLI caching with in-memory and file storage --- src/cache.test.ts | 226 +++++++++++++++++++++++++++++++++++++++++++ src/cache.ts | 147 ++++++++++++++++++++++++++++ src/codeql.ts | 82 +++++++++------- src/environment.ts | 12 --- src/status-report.ts | 9 +- src/testing-utils.ts | 8 +- src/util.test.ts | 55 ----------- src/util.ts | 155 +---------------------------- 8 files changed, 432 insertions(+), 262 deletions(-) create mode 100644 src/cache.test.ts create mode 100644 src/cache.ts diff --git a/src/cache.test.ts b/src/cache.test.ts new file mode 100644 index 0000000000..b4b72ecea2 --- /dev/null +++ b/src/cache.test.ts @@ -0,0 +1,226 @@ +import * as fs from "fs"; +import * as os from "os"; +import path from "path"; + +import test from "ava"; + +import { + cacheCommandOutput, + getCachedCommandOutput, + resetCachedCommandOutputs, + CommandCacheKey, +} from "./cache"; +import { isVersionInfo } from "./codeql"; +import { setupTests } from "./testing-utils"; + +setupTests(test); + +const COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; + +/** + * Runs `body` with a temporary directory configured as the cache's backing + * store (`RUNNER_TEMP`). `CODEQL_ACTION_TEMP` is cleared so that + * `getTemporaryDirectory()` falls back to `RUNNER_TEMP`. + * + * `setupTests` snapshots and restores `process.env` around every test, so we + * don't restore the environment variables we set here ourselves. + */ +async function withCacheDir( + body: (cacheFilePath: string) => Promise | void, +): Promise { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "cache-test-")); + process.env["RUNNER_TEMP"] = tmpDir; + delete process.env["CODEQL_ACTION_TEMP"]; + resetCachedCommandOutputs(); + try { + await body(path.join(tmpDir, COMMAND_CACHE_FILENAME)); + } finally { + await fs.promises.rm(tmpDir, { force: true, recursive: true }); + } +} + +function writeCacheFile( + cacheFilePath: string, + contents: Record, +): void { + fs.writeFileSync(cacheFilePath, JSON.stringify(contents)); +} + +test.serial( + "getCachedCommandOutput reuses an output persisted by an earlier step", + async (t) => { + await withCacheDir((cacheFilePath) => { + writeCacheFile(cacheFilePath, { + [CommandCacheKey.Version]: { + cmd: "/path/to/codeql", + output: { version: "2.20.0" }, + }, + }); + t.deepEqual( + getCachedCommandOutput( + CommandCacheKey.Version, + "/path/to/codeql", + isVersionInfo, + ), + { version: "2.20.0" }, + ); + }); + }, +); + +test.serial( + "getCachedCommandOutput ignores an output persisted from a different CLI", + async (t) => { + await withCacheDir((cacheFilePath) => { + writeCacheFile(cacheFilePath, { + [CommandCacheKey.Version]: { + cmd: "/path/to/other-codeql", + output: { version: "2.20.0" }, + }, + }); + t.is( + getCachedCommandOutput( + CommandCacheKey.Version, + "/path/to/codeql", + isVersionInfo, + ), + undefined, + ); + }); + }, +); + +test.serial( + "getCachedCommandOutput ignores a malformed cache file", + async (t) => { + await withCacheDir((cacheFilePath) => { + fs.writeFileSync(cacheFilePath, "not valid json"); + t.is( + getCachedCommandOutput( + CommandCacheKey.Version, + "/path/to/codeql", + isVersionInfo, + ), + undefined, + ); + }); + }, +); + +test.serial( + "getCachedCommandOutput returns undefined when there is no cache file", + async (t) => { + await withCacheDir(() => { + t.is( + getCachedCommandOutput( + CommandCacheKey.Version, + "/path/to/codeql", + isVersionInfo, + ), + undefined, + ); + }); + }, +); + +test.serial( + "getCachedCommandOutput ignores an output that fails validation", + async (t) => { + await withCacheDir((cacheFilePath) => { + for (const output of [ + {}, + { version: 2 }, + { version: "2.20.0", overlayVersion: "1" }, + { version: "2.20.0", features: "nope" }, + ]) { + resetCachedCommandOutputs(); + writeCacheFile(cacheFilePath, { + [CommandCacheKey.Version]: { cmd: "/path/to/codeql", output }, + }); + t.is( + getCachedCommandOutput( + CommandCacheKey.Version, + "/path/to/codeql", + isVersionInfo, + ), + undefined, + JSON.stringify(output), + ); + } + }); + }, +); + +test.serial( + "getCachedCommandOutput ignores an entry missing the cmd field", + async (t) => { + await withCacheDir((cacheFilePath) => { + writeCacheFile(cacheFilePath, { + [CommandCacheKey.Version]: { output: { version: "2.20.0" } }, + }); + t.is( + getCachedCommandOutput( + CommandCacheKey.Version, + "/path/to/codeql", + isVersionInfo, + ), + undefined, + ); + }); + }, +); + +test.serial( + "cacheCommandOutput persists the output to both the memo and the file", + async (t) => { + await withCacheDir((cacheFilePath) => { + cacheCommandOutput("some-command", "/path/to/codeql", { + hello: "world", + }); + + // Tier 2: the temporary file contains the entry. + const onDisk = JSON.parse( + fs.readFileSync(cacheFilePath, "utf8"), + ) as Record; + t.deepEqual(onDisk["some-command"], { + cmd: "/path/to/codeql", + output: { hello: "world" }, + }); + + // Tier 1: the value is served from the memo even after the file is gone. + fs.rmSync(cacheFilePath); + t.deepEqual(getCachedCommandOutput("some-command", "/path/to/codeql"), { + hello: "world", + }); + }); + }, +); + +test.serial( + "getCachedCommandOutput prefers the in-memory memo over the file", + async (t) => { + await withCacheDir((cacheFilePath) => { + cacheCommandOutput("some-command", "/path/to/codeql", { value: 1 }); + + // Overwrite the file with a different value; the memo (tier 1) should win. + writeCacheFile(cacheFilePath, { + "some-command": { cmd: "/path/to/codeql", output: { value: 2 } }, + }); + t.deepEqual(getCachedCommandOutput("some-command", "/path/to/codeql"), { + value: 1, + }); + }); + }, +); + +test.serial( + "cacheCommandOutput throws if called twice for the same key", + async (t) => { + await withCacheDir(() => { + cacheCommandOutput("some-command", "/path/to/codeql", { value: 1 }); + t.throws(() => + cacheCommandOutput("some-command", "/path/to/codeql", { value: 2 }), + ); + }); + }, +); diff --git a/src/cache.ts b/src/cache.ts new file mode 100644 index 0000000000..f14583a982 --- /dev/null +++ b/src/cache.ts @@ -0,0 +1,147 @@ +import * as fs from "fs"; +import * as path from "path"; + +import { getTemporaryDirectory } from "./actions-util"; +import * as json from "./json"; + +/** The name of the temporary file backing the cache (tier 2). */ +const COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; + +/** + * The keys under which the output of cached `codeql` commands is stored. Each + * key is shared by the producer (the corresponding method in `codeql.ts`) and + * any consumers (e.g. `status-report.ts`, which peeks the cached version + * without invoking the CLI). + */ +export enum CommandCacheKey { + Version = "version", + ResolveLanguages = "resolveLanguages", +} + +/** A single cached command output together with the CLI path it came from. */ +interface CacheEntry { + /** + * The path to the CodeQL CLI that produced `output`. Persisted so that a + * different step using a different CodeQL bundle doesn't pick up a stale + * value. + */ + cmd: string; + output: unknown; +} + +/** + * Tier 1: the in-process memo. Consulted first on every lookup and populated + * whenever a value is read from the file (tier 2) or computed via the CLI + * (tier 3). + */ +const inMemoryCache = new Map(); + +function getCommandCacheFilePath(): string { + return path.join(getTemporaryDirectory(), COMMAND_CACHE_FILENAME); +} + +/** + * Reads and parses the temporary cache file. Best-effort: a missing, malformed, + * or otherwise unreadable file is treated as an empty cache. + */ +function readCommandCacheFile(): Record { + let contents: string; + try { + contents = fs.readFileSync(getCommandCacheFilePath(), "utf8"); + } catch { + return {}; + } + try { + const parsed = json.parseString(contents); + if (json.isObject(parsed)) { + return parsed; + } + } catch { + // Fall through and treat a malformed file as empty. + } + return {}; +} + +/** + * Persists the cache to the temporary file. Best-effort: a failure to write + * just means a later step re-runs the CLI. + */ +function writeCommandCacheFile(data: Record): void { + try { + fs.writeFileSync(getCommandCacheFilePath(), JSON.stringify(data)); + } catch { + // Best-effort; ignore write failures. + } +} + +/** + * Stores the output of a command under `key`, writing it to both the in-memory + * memo (tier 1) and the temporary file (tier 2). + * + * Should only be called once per key within a single process; doing otherwise + * indicates a logic error, since a value that has already been cached should be + * served from the memo rather than recomputed. + */ +export function cacheCommandOutput( + key: string, + cmd: string, + output: unknown, +): void { + if (inMemoryCache.has(key)) { + throw new Error( + `cacheCommandOutput() should be called only once per key, but was called more than once for '${key}'.`, + ); + } + const entry: CacheEntry = { cmd, output }; + inMemoryCache.set(key, entry); + + const data = readCommandCacheFile(); + data[key] = entry; + writeCommandCacheFile(data); +} + +/** + * Returns the cached output for `key`, or `undefined` if it isn't cached. + * + * Resolves tier 1 (in-memory memo) first, then tier 2 (temporary file). A value + * loaded from the file is ignored unless its `cmd` matches the optional `cmd` + * argument, and it satisfies the optional `validate` type guard; valid values + * are memoized into tier 1 before being returned. + * + * A return value of `undefined` signals the caller to fall back to tier 3 (the + * CLI). + */ +export function getCachedCommandOutput( + key: string, + cmd?: string, + validate?: (output: unknown) => output is T, +): T | undefined { + // Tier 1: the in-memory variable. + const memoized = inMemoryCache.get(key); + if (memoized !== undefined) { + return memoized.output as T; + } + + // Tier 2: the temporary file persisted by an earlier step, if any. + const entry = readCommandCacheFile()[key] as unknown; + if ( + !json.isObject(entry) || + !json.isString(entry.cmd) || + (cmd !== undefined && entry.cmd !== cmd) || + (validate !== undefined && !validate(entry.output)) + ) { + return undefined; + } + + // Memoize so subsequent lookups in this process hit tier 1. + inMemoryCache.set(key, { cmd: entry.cmd, output: entry.output }); + return entry.output as T; +} + +/** + * Clears the in-process memo (tier 1). Only for use in tests, which exercise + * multiple "steps" within a single process. + */ +export function resetCachedCommandOutputs(): void { + inMemoryCache.clear(); +} diff --git a/src/codeql.ts b/src/codeql.ts index 0aa386a2d7..04b4685ad2 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -12,6 +12,11 @@ import { runTool, } from "./actions-util"; import * as api from "./api-client"; +import { + cacheCommandOutput, + getCachedCommandOutput, + CommandCacheKey, +} from "./cache"; import { CliError, wrapCliConfigurationError } from "./cli-errors"; import { appendExtraQueryExclusions, type Config } from "./config-utils"; import { DocUrl } from "./doc-url"; @@ -22,6 +27,7 @@ import { FeatureEnablement, } from "./feature-flags"; import { isAnalyzingDefaultBranch } from "./git-utils"; +import * as json from "./json"; import { Language } from "./languages"; import { Logger } from "./logging"; import { writeBaseDatabaseOidsFile, writeOverlayChangesFile } from "./overlay"; @@ -230,6 +236,20 @@ export interface VersionInfo { overlayVersion?: number; } +export function isVersionInfo(x: unknown): x is VersionInfo { + return ( + json.isObject(x) && + json.validateSchema( + { + version: json.string, + features: json.undefinable(json.object), + overlayVersion: json.undefinable(json.number), + }, + x, + ) + ); +} + export interface ResolveDatabaseOutput { overlayBaseSpecifier?: string; } @@ -246,6 +266,15 @@ export interface ResolveLanguagesOutput { }; } +export function isResolveLanguagesOutput( + x: unknown, +): x is ResolveLanguagesOutput { + return ( + json.isObject(x) + // TODO: finish this with Copilot + ); +} + export interface ResolveBuildEnvironmentOutput { configuration?: { [language: string]: { @@ -723,41 +752,24 @@ async function getCodeQLForCmd( ]; await runCli(cmd, args); }, - async resolveLanguages( - { - filterToLanguagesWithQueries, - }: { - filterToLanguagesWithQueries: boolean; - } = { filterToLanguagesWithQueries: false }, - ) { - async function runCliResolveLanguages() { - const codeqlArgs = [ - "resolve", - "languages", - "--format=betterjson", - "--extractor-options-verbosity=4", - "--extractor-include-aliases", - ...(filterToLanguagesWithQueries - ? ["--filter-to-languages-with-queries"] - : []), - ...getExtraOptionsFromEnv(["resolve", "languages"]), - ]; - const output = await runCli(cmd, codeqlArgs); - - try { - return JSON.parse(output) as ResolveLanguagesOutput; - } catch (e) { - throw new Error( - `Unexpected output from codeql resolve languages with --format=betterjson: ${e}`, - ); - } - } - let result = util.getCachedCodeQlResolveLanguages(cmd); - if (result === undefined) { - result = await runCliResolveLanguages(); - util.cacheCodeQlResolveLanguages(cmd, result); - } - return result; + async resolveLanguages() { + return getCachedOrRun( + CommandCacheKey.ResolveLanguages, + cmd, + () => + runCliJson(cmd, [ + "resolve", + "languages", + "--format=betterjson", + "--extractor-options-verbosity=4", + "--extractor-include-aliases", + ...(filterToLanguagesWithQueries + ? ["--filter-to-languages-with-queries"] + : []), + ...getExtraOptionsFromEnv(["resolve", "languages"]), + ]), + isResolveLanguagesOutput, + ); }, async resolveBuildEnvironment( workingDir: string | undefined, diff --git a/src/environment.ts b/src/environment.ts index 1324abf280..ed44ddcff2 100644 --- a/src/environment.ts +++ b/src/environment.ts @@ -17,18 +17,6 @@ export enum EnvVar { */ CLI_VERBOSITY = "CODEQL_VERBOSITY", - /** - * `PersistedVersionInfo` for the CodeQL CLI, so later Actions steps can reuse it instead of - * invoking `codeql version` again. - */ - CODEQL_VERSION_INFO = "CODEQL_ACTION_CLI_VERSION_INFO", - - /** - * `ResolveLanguagesOutput` for the CodeQL CLI, so later Actions steps can reuse it instead of - * invoking `codeql resolve languages` again. - */ - CODEQL_RESOLVE_LANGUAGES = "CODEQL_ACTION_CLI_RESOLVE_LANGUAGES", - /** Whether the CodeQL Action has invoked the Go autobuilder. */ DID_AUTOBUILD_GOLANG = "CODEQL_ACTION_DID_AUTOBUILD_GOLANG", diff --git a/src/status-report.ts b/src/status-report.ts index b3e3628b36..e6a489c5cc 100644 --- a/src/status-report.ts +++ b/src/status-report.ts @@ -12,6 +12,8 @@ import { isSelfHostedRunner, } from "./actions-util"; import { getAnalysisKey, getApiClient } from "./api-client"; +import { getCachedCommandOutput, CommandCacheKey } from "./cache"; +import { isVersionInfo } from "./codeql"; import { parseRegistriesWithoutCredentials, type Config } from "./config-utils"; import { DependencyCacheRestoreStatusReport } from "./dependency-caching"; import { DocUrl } from "./doc-url"; @@ -24,7 +26,6 @@ import { ToolsSource } from "./setup-codeql"; import { ConfigurationError, getRequiredEnvParam, - getCachedCodeQlVersion, isInTestMode, GITHUB_DOTCOM_URL, DiskUsage, @@ -283,7 +284,11 @@ export async function createStatusReportBase( core.exportVariable(EnvVar.WORKFLOW_STARTED_AT, workflowStartedAt); } const runnerOs = getRequiredEnvParam("RUNNER_OS"); - const codeQlCliVersion = getCachedCodeQlVersion(); + const codeQlCliVersion = getCachedCommandOutput( + CommandCacheKey.Version, + undefined, + isVersionInfo, + ); const actionRef = process.env["GITHUB_ACTION_REF"] || ""; const testingEnvironment = getTestingEnvironment(); // re-export the testing environment variable so that it is available to subsequent steps, diff --git a/src/testing-utils.ts b/src/testing-utils.ts index 2660c21a69..b62242b267 100644 --- a/src/testing-utils.ts +++ b/src/testing-utils.ts @@ -14,6 +14,7 @@ import { ActionsEnv, getActionVersion } from "./actions-util"; import { AnalysisKind } from "./analyses"; import * as apiClient from "./api-client"; import { GitHubApiDetails } from "./api-client"; +import { resetCachedCommandOutputs } from "./cache"; import { CachingKind } from "./caching-utils"; import * as codeql from "./codeql"; import { Config } from "./config-utils"; @@ -32,7 +33,6 @@ import { GitHubVariant, GitHubVersion, HTTPError, - resetCachedCodeQlVersion, } from "./util"; export const SAMPLE_DOTCOM_API_DETAILS = { @@ -102,9 +102,9 @@ export function setupTests(testFn: TestFn) { // unless the test explicitly sets one up. codeql.setCodeQL({}); - // Reset the in-process CodeQL version cache so that it doesn't leak between - // tests, which each represent a separate Actions step in production. - resetCachedCodeQlVersion(); + // Reset the in-process CodeQL command-output cache so that it doesn't leak + // between tests, which each represent a separate Actions step in production. + resetCachedCommandOutputs(); // Replace stdout and stderr so we can record output during tests t.context.testOutput = ""; diff --git a/src/util.test.ts b/src/util.test.ts index 3d27e952af..cca457cbe6 100644 --- a/src/util.test.ts +++ b/src/util.test.ts @@ -532,58 +532,3 @@ test("Failure.orElse returns the default value for a failure result", (t) => { const result = new util.Failure(new Error("test error")); t.is(result.orElse("default value"), "default value"); }); - -test.serial( - "getCachedCodeQlVersion reuses a version persisted by an earlier step", - (t) => { - process.env[EnvVar.CODEQL_VERSION_INFO] = JSON.stringify({ - cmd: "/path/to/codeql", - version: { version: "2.20.0" }, - }); - t.deepEqual(util.getCachedCodeQlVersion("/path/to/codeql"), { - version: "2.20.0", - }); - }, -); - -test.serial( - "getCachedCodeQlVersion ignores a persisted version from a different CLI", - (t) => { - process.env[EnvVar.CODEQL_VERSION_INFO] = JSON.stringify({ - cmd: "/path/to/other-codeql", - version: { version: "2.20.0" }, - }); - t.is(util.getCachedCodeQlVersion("/path/to/codeql"), undefined); - }, -); - -test.serial( - "getCachedCodeQlVersion ignores a malformed persisted value", - (t) => { - process.env[EnvVar.CODEQL_VERSION_INFO] = "not valid json"; - t.is(util.getCachedCodeQlVersion("/path/to/codeql"), undefined); - }, -); - -test.serial( - "getCachedCodeQlVersion ignores a persisted value with the wrong structure", - (t) => { - for (const value of [ - JSON.stringify({ cmd: "/path/to/codeql" }), - JSON.stringify({ cmd: "/path/to/codeql", version: {} }), - JSON.stringify({ cmd: "/path/to/codeql", version: { version: 2 } }), - JSON.stringify({ version: { version: "2.20.0" } }), - JSON.stringify({ - cmd: "/path/to/codeql", - version: { version: "2.20.0", overlayVersion: "1" }, - }), - JSON.stringify({ - cmd: "/path/to/codeql", - version: { version: "2.20.0", features: "nope" }, - }), - ]) { - process.env[EnvVar.CODEQL_VERSION_INFO] = value; - t.is(util.getCachedCodeQlVersion("/path/to/codeql"), undefined, value); - } - }, -); diff --git a/src/util.ts b/src/util.ts index 3bf0c0d61d..4dc7df12c1 100644 --- a/src/util.ts +++ b/src/util.ts @@ -10,7 +10,7 @@ import * as yaml from "js-yaml"; import * as semver from "semver"; import * as apiCompatibility from "./api-compatibility.json"; -import type { CodeQL, VersionInfo, ResolveLanguagesOutput } from "./codeql"; +import type { CodeQL } from "./codeql"; import type { Pack } from "./config/db-config"; import type { Config } from "./config-utils"; import { EnvVar } from "./environment"; @@ -617,159 +617,6 @@ export function asHTTPError(arg: any): HTTPError | undefined { return undefined; } -let cachedCodeQlVersion: undefined | VersionInfo = undefined; - -/** - * Resets the in-process cache of the CodeQL CLI version. Only for use in tests, - * which exercise multiple "steps" within a single process. - */ -export function resetCachedCodeQlVersion(): void { - cachedCodeQlVersion = undefined; -} - -/** The persisted version together with the CLI path it was obtained from. */ -interface PersistedVersionInfo { - cmd: string; - version: VersionInfo; -} - -function isVersionInfo(x: unknown): x is VersionInfo { - return ( - json.isObject(x) && - json.validateSchema( - { - version: json.string, - features: json.undefinable(json.object), - overlayVersion: json.undefinable(json.number), - }, - x, - ) - ); -} - -function isPersistedVersionInfo(x: unknown): x is PersistedVersionInfo { - const candidate = x as Partial | null; - return ( - typeof candidate === "object" && - candidate !== null && - typeof candidate.cmd === "string" && - isVersionInfo(candidate.version) - ); -} - -export function cacheCodeQlVersion(cmd: string, version: VersionInfo): void { - if (cachedCodeQlVersion !== undefined) { - throw new Error("cacheCodeQlVersion() should be called only once"); - } - cachedCodeQlVersion = version; - // Persist the version so that subsequent Actions steps, which run in separate - // processes, can reuse it rather than invoking `codeql version` again. We - // record the CLI path so that a different step using a different CodeQL bundle - // doesn't pick up a stale version. - core.exportVariable( - EnvVar.CODEQL_VERSION_INFO, - JSON.stringify({ cmd, version }), - ); -} - -export function getCachedCodeQlVersion(cmd?: string): undefined | VersionInfo { - if (cachedCodeQlVersion !== undefined) { - return cachedCodeQlVersion; - } - // Fall back to the value persisted by an earlier Actions step, if any. This is - // best-effort: any malformed or mismatched value is ignored so that the caller - // invokes `codeql version` instead. - const serialized = process.env[EnvVar.CODEQL_VERSION_INFO]; - if (!serialized) { - return undefined; - } - let persisted: unknown; - try { - persisted = JSON.parse(serialized); - } catch { - return undefined; - } - if ( - !isPersistedVersionInfo(persisted) || - (cmd !== undefined && persisted.cmd !== cmd) - ) { - return undefined; - } - // Memoize the parsed value so that subsequent calls in this process don't - // re-parse the environment variable. - cachedCodeQlVersion = persisted.version; - return cachedCodeQlVersion; -} - -let cachedCodeQlResolveLanguages: undefined | ResolveLanguagesOutput = - undefined; - -interface PersistedResolveLanguagesOutput { - cmd: string; - output: ResolveLanguagesOutput; -} - -export function cacheCodeQlResolveLanguages( - cmd: string, - output: ResolveLanguagesOutput, -): void { - if (cachedCodeQlResolveLanguages !== undefined) { - throw new Error("cacheCodeQlResolveLanguages() should be called only once"); - } - cachedCodeQlResolveLanguages = output; - // Persist the output so that subsequent Actions steps, which run in separate - // processes, can reuse it rather than invoking `codeql resolve languages` again. We - // record the CLI path so that a different step using a different CodeQL bundle - // doesn't pick up a stale output. - core.exportVariable( - EnvVar.CODEQL_RESOLVE_LANGUAGES, - JSON.stringify({ cmd, output }), - ); -} - -function isPersistedResolveLanguagesOutput( - value: unknown, -): value is PersistedResolveLanguagesOutput { - return ( - typeof value === "object" && - value !== null && - typeof (value as Record).cmd === "string" && - typeof (value as Record).output === "object" && - (value as Record).output !== null - ); -} - -export function getCachedCodeQlResolveLanguages( - cmd?: string, -): undefined | ResolveLanguagesOutput { - if (cachedCodeQlResolveLanguages !== undefined) { - return cachedCodeQlResolveLanguages; - } - // Fall back to the value persisted by an earlier Actions step, if any. This is - // best-effort: any malformed or mismatched value is ignored so that the caller - // invokes `codeql resolve languages` instead. - const serialized = process.env[EnvVar.CODEQL_RESOLVE_LANGUAGES]; - if (!serialized) { - return undefined; - } - let persisted: unknown; - try { - persisted = JSON.parse(serialized); - } catch { - return undefined; - } - if ( - !isPersistedResolveLanguagesOutput(persisted) || - (cmd !== undefined && persisted.cmd !== cmd) - ) { - return undefined; - } - // Memoize the parsed value so that subsequent calls in this process don't - // re-parse the environment variable. - cachedCodeQlResolveLanguages = persisted.output; - return cachedCodeQlResolveLanguages; -} - export async function codeQlVersionAtLeast( codeql: CodeQL, requiredVersion: string, From b18df17ee7608277c4d8ac617d62bd3878135de1 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 18 Jun 2026 10:25:23 -0500 Subject: [PATCH 08/26] Rebased onto main; fixups were needed --- lib/entry-points.js | 2420 ++++++++++++++++++++++--------------------- src/codeql.ts | 76 +- 2 files changed, 1278 insertions(+), 1218 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 709bc26f1d..d450071b50 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -213,7 +213,7 @@ var require_file_command = __commonJS({ exports2.issueFileCommand = issueFileCommand; exports2.prepareKeyValueMessage = prepareKeyValueMessage; var crypto3 = __importStar2(require("crypto")); - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var os7 = __importStar2(require("os")); var utils_1 = require_utils(); function issueFileCommand(command, message) { @@ -221,10 +221,10 @@ var require_file_command = __commonJS({ if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } - if (!fs30.existsSync(filePath)) { + if (!fs31.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs30.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os7.EOL}`, { + fs31.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os7.EOL}`, { encoding: "utf8" }); } @@ -1301,16 +1301,16 @@ var require_util = __commonJS({ function isStream(obj) { return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function"; } - function isBlobLike(object) { - if (object === null) { + function isBlobLike(object2) { + if (object2 === null) { return false; - } else if (object instanceof Blob2) { + } else if (object2 instanceof Blob2) { return true; - } else if (typeof object !== "object") { + } else if (typeof object2 !== "object") { return false; } else { - const sTag = object[Symbol.toStringTag]; - return (sTag === "Blob" || sTag === "File") && ("stream" in object && typeof object.stream === "function" || "arrayBuffer" in object && typeof object.arrayBuffer === "function"); + const sTag = object2[Symbol.toStringTag]; + return (sTag === "Blob" || sTag === "File") && ("stream" in object2 && typeof object2.stream === "function" || "arrayBuffer" in object2 && typeof object2.arrayBuffer === "function"); } } function buildURL(url2, queryParams) { @@ -1362,14 +1362,14 @@ var require_util = __commonJS({ } const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80; let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`; - let path28 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`; + let path29 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`; if (origin[origin.length - 1] === "/") { origin = origin.slice(0, origin.length - 1); } - if (path28 && path28[0] !== "/") { - path28 = `/${path28}`; + if (path29 && path29[0] !== "/") { + path29 = `/${path29}`; } - return new URL(`${origin}${path28}`); + return new URL(`${origin}${path29}`); } if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) { throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`."); @@ -1592,8 +1592,8 @@ var require_util = __commonJS({ } ); } - function isFormDataLike(object) { - return object && typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && object[Symbol.toStringTag] === "FormData"; + function isFormDataLike(object2) { + return object2 && typeof object2 === "object" && typeof object2.append === "function" && typeof object2.delete === "function" && typeof object2.get === "function" && typeof object2.getAll === "function" && typeof object2.has === "function" && typeof object2.set === "function" && object2[Symbol.toStringTag] === "FormData"; } function addAbortListener(signal, listener) { if ("addEventListener" in signal) { @@ -1820,39 +1820,39 @@ var require_diagnostics = __commonJS({ }); diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => { const { - request: { method, path: path28, origin } + request: { method, path: path29, origin } } = evt; - debuglog("sending request to %s %s/%s", method, origin, path28); + debuglog("sending request to %s %s/%s", method, origin, path29); }); diagnosticsChannel.channel("undici:request:headers").subscribe((evt) => { const { - request: { method, path: path28, origin }, + request: { method, path: path29, origin }, response: { statusCode } } = evt; debuglog( "received response to %s %s/%s - HTTP %d", method, origin, - path28, + path29, statusCode ); }); diagnosticsChannel.channel("undici:request:trailers").subscribe((evt) => { const { - request: { method, path: path28, origin } + request: { method, path: path29, origin } } = evt; - debuglog("trailers received from %s %s/%s", method, origin, path28); + debuglog("trailers received from %s %s/%s", method, origin, path29); }); diagnosticsChannel.channel("undici:request:error").subscribe((evt) => { const { - request: { method, path: path28, origin }, + request: { method, path: path29, origin }, error: error3 } = evt; debuglog( "request to %s %s/%s errored - %s", method, origin, - path28, + path29, error3.message ); }); @@ -1901,9 +1901,9 @@ var require_diagnostics = __commonJS({ }); diagnosticsChannel.channel("undici:client:sendHeaders").subscribe((evt) => { const { - request: { method, path: path28, origin } + request: { method, path: path29, origin } } = evt; - debuglog("sending request to %s %s/%s", method, origin, path28); + debuglog("sending request to %s %s/%s", method, origin, path29); }); } diagnosticsChannel.channel("undici:websocket:open").subscribe((evt) => { @@ -1966,7 +1966,7 @@ var require_request = __commonJS({ var kHandler = /* @__PURE__ */ Symbol("handler"); var Request = class { constructor(origin, { - path: path28, + path: path29, method, body, headers, @@ -1981,11 +1981,11 @@ var require_request = __commonJS({ expectContinue, servername }, handler2) { - if (typeof path28 !== "string") { + if (typeof path29 !== "string") { throw new InvalidArgumentError("path must be a string"); - } else if (path28[0] !== "/" && !(path28.startsWith("http://") || path28.startsWith("https://")) && method !== "CONNECT") { + } else if (path29[0] !== "/" && !(path29.startsWith("http://") || path29.startsWith("https://")) && method !== "CONNECT") { throw new InvalidArgumentError("path must be an absolute URL or start with a slash"); - } else if (invalidPathRegex.test(path28)) { + } else if (invalidPathRegex.test(path29)) { throw new InvalidArgumentError("invalid request path"); } if (typeof method !== "string") { @@ -2051,7 +2051,7 @@ var require_request = __commonJS({ this.completed = false; this.aborted = false; this.upgrade = upgrade || null; - this.path = query ? buildURL(path28, query) : path28; + this.path = query ? buildURL(path29, query) : path29; this.origin = origin; this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent; this.blocking = blocking == null ? false : blocking; @@ -4347,8 +4347,8 @@ var require_util2 = __commonJS({ } return "allowed"; } - function isErrorLike(object) { - return object instanceof Error || (object?.constructor?.name === "Error" || object?.constructor?.name === "DOMException"); + function isErrorLike(object2) { + return object2 instanceof Error || (object2?.constructor?.name === "Error" || object2?.constructor?.name === "DOMException"); } function isValidReasonPhrase(statusText) { for (let i = 0; i < statusText.length; ++i) { @@ -4773,7 +4773,7 @@ var require_util2 = __commonJS({ return new FastIterableIterator(target, kind); }; } - function iteratorMixin(name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) { + function iteratorMixin(name, object2, kInternalIterator, keyIndex = 0, valueIndex = 1) { const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex); const properties = { keys: { @@ -4781,7 +4781,7 @@ var require_util2 = __commonJS({ enumerable: true, configurable: true, value: function keys() { - webidl.brandCheck(this, object); + webidl.brandCheck(this, object2); return makeIterator(this, "key"); } }, @@ -4790,7 +4790,7 @@ var require_util2 = __commonJS({ enumerable: true, configurable: true, value: function values() { - webidl.brandCheck(this, object); + webidl.brandCheck(this, object2); return makeIterator(this, "value"); } }, @@ -4799,7 +4799,7 @@ var require_util2 = __commonJS({ enumerable: true, configurable: true, value: function entries() { - webidl.brandCheck(this, object); + webidl.brandCheck(this, object2); return makeIterator(this, "key+value"); } }, @@ -4808,7 +4808,7 @@ var require_util2 = __commonJS({ enumerable: true, configurable: true, value: function forEach(callbackfn, thisArg = globalThis) { - webidl.brandCheck(this, object); + webidl.brandCheck(this, object2); webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`); if (typeof callbackfn !== "function") { throw new TypeError( @@ -4821,7 +4821,7 @@ var require_util2 = __commonJS({ } } }; - return Object.defineProperties(object.prototype, { + return Object.defineProperties(object2.prototype, { ...properties, [Symbol.iterator]: { writable: true, @@ -5221,8 +5221,8 @@ var require_file = __commonJS({ } }; webidl.converters.Blob = webidl.interfaceConverter(Blob2); - function isFileLike(object) { - return object instanceof File2 || object && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && object[Symbol.toStringTag] === "File"; + function isFileLike(object2) { + return object2 instanceof File2 || object2 && (typeof object2.stream === "function" || typeof object2.arrayBuffer === "function") && object2[Symbol.toStringTag] === "File"; } module2.exports = { FileLike, isFileLike }; } @@ -5670,12 +5670,12 @@ var require_body = __commonJS({ } }); } - function extractBody(object, keepalive = false) { + function extractBody(object2, keepalive = false) { let stream2 = null; - if (object instanceof ReadableStream) { - stream2 = object; - } else if (isBlobLike(object)) { - stream2 = object.stream(); + if (object2 instanceof ReadableStream) { + stream2 = object2; + } else if (isBlobLike(object2)) { + stream2 = object2.stream(); } else { stream2 = new ReadableStream({ async pull(controller) { @@ -5695,17 +5695,17 @@ var require_body = __commonJS({ let source = null; let length = null; let type = null; - if (typeof object === "string") { - source = object; + if (typeof object2 === "string") { + source = object2; type = "text/plain;charset=UTF-8"; - } else if (object instanceof URLSearchParams) { - source = object.toString(); + } else if (object2 instanceof URLSearchParams) { + source = object2.toString(); type = "application/x-www-form-urlencoded;charset=UTF-8"; - } else if (isArrayBuffer(object)) { - source = new Uint8Array(object.slice()); - } else if (ArrayBuffer.isView(object)) { - source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)); - } else if (util.isFormDataLike(object)) { + } else if (isArrayBuffer(object2)) { + source = new Uint8Array(object2.slice()); + } else if (ArrayBuffer.isView(object2)) { + source = new Uint8Array(object2.buffer.slice(object2.byteOffset, object2.byteOffset + object2.byteLength)); + } else if (util.isFormDataLike(object2)) { const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`; const prefix = `--${boundary}\r Content-Disposition: form-data`; @@ -5715,7 +5715,7 @@ Content-Disposition: form-data`; const rn = new Uint8Array([13, 10]); length = 0; let hasUnknownSizeValue = false; - for (const [name, value] of object) { + for (const [name, value] of object2) { if (typeof value === "string") { const chunk2 = textEncoder.encode(prefix + `; name="${escape2(normalizeLinefeeds(name))}"\r \r @@ -5743,7 +5743,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r if (hasUnknownSizeValue) { length = null; } - source = object; + source = object2; action = async function* () { for (const part of blobParts) { if (part.stream) { @@ -5754,22 +5754,22 @@ Content-Type: ${value.type || "application/octet-stream"}\r } }; type = `multipart/form-data; boundary=${boundary}`; - } else if (isBlobLike(object)) { - source = object; - length = object.size; - if (object.type) { - type = object.type; + } else if (isBlobLike(object2)) { + source = object2; + length = object2.size; + if (object2.type) { + type = object2.type; } - } else if (typeof object[Symbol.asyncIterator] === "function") { + } else if (typeof object2[Symbol.asyncIterator] === "function") { if (keepalive) { throw new TypeError("keepalive"); } - if (util.isDisturbed(object) || object.locked) { + if (util.isDisturbed(object2) || object2.locked) { throw new TypeError( "Response body object should not be disturbed or locked" ); } - stream2 = object instanceof ReadableStream ? object : ReadableStreamFrom(object); + stream2 = object2 instanceof ReadableStream ? object2 : ReadableStreamFrom(object2); } if (typeof source === "string" || util.isBuffer(source)) { length = Buffer.byteLength(source); @@ -5778,7 +5778,7 @@ Content-Type: ${value.type || "application/octet-stream"}\r let iterator2; stream2 = new ReadableStream({ async start() { - iterator2 = action(object)[Symbol.asyncIterator](); + iterator2 = action(object2)[Symbol.asyncIterator](); }, async pull(controller) { const { value, done } = await iterator2.next(); @@ -5806,12 +5806,12 @@ Content-Type: ${value.type || "application/octet-stream"}\r const body = { stream: stream2, source, length }; return [body, type]; } - function safelyExtractBody(object, keepalive = false) { - if (object instanceof ReadableStream) { - assert(!util.isDisturbed(object), "The body has already been consumed."); - assert(!object.locked, "The stream is locked."); + function safelyExtractBody(object2, keepalive = false) { + if (object2 instanceof ReadableStream) { + assert(!util.isDisturbed(object2), "The body has already been consumed."); + assert(!object2.locked, "The stream is locked."); } - return extractBody(object, keepalive); + return extractBody(object2, keepalive); } function cloneBody(instance, body) { const [out1, out2] = body.stream.tee(); @@ -5891,12 +5891,12 @@ Content-Type: ${value.type || "application/octet-stream"}\r function mixinBody(prototype) { Object.assign(prototype.prototype, bodyMixinMethods(prototype)); } - async function consumeBody(object, convertBytesToJSValue, instance) { - webidl.brandCheck(object, instance); - if (bodyUnusable(object)) { + async function consumeBody(object2, convertBytesToJSValue, instance) { + webidl.brandCheck(object2, instance); + if (bodyUnusable(object2)) { throw new TypeError("Body is unusable: Body has already been read"); } - throwIfAborted(object[kState]); + throwIfAborted(object2[kState]); const promise = createDeferredPromise(); const errorSteps = (error3) => promise.reject(error3); const successSteps = (data) => { @@ -5906,15 +5906,15 @@ Content-Type: ${value.type || "application/octet-stream"}\r errorSteps(e); } }; - if (object[kState].body == null) { + if (object2[kState].body == null) { successSteps(Buffer.allocUnsafe(0)); return promise.promise; } - await fullyReadBody(object[kState].body, successSteps, errorSteps); + await fullyReadBody(object2[kState].body, successSteps, errorSteps); return promise.promise; } - function bodyUnusable(object) { - const body = object[kState].body; + function bodyUnusable(object2) { + const body = object2[kState].body; return body != null && (body.stream.locked || util.isDisturbed(body.stream)); } function parseJSONFromBytes(bytes) { @@ -6570,7 +6570,7 @@ var require_client_h1 = __commonJS({ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT"; } function writeH1(client, request3) { - const { method, path: path28, host, upgrade, blocking, reset } = request3; + const { method, path: path29, host, upgrade, blocking, reset } = request3; let { body, headers, contentLength } = request3; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH"; if (util.isFormDataLike(body)) { @@ -6636,7 +6636,7 @@ var require_client_h1 = __commonJS({ if (blocking) { socket[kBlocking] = true; } - let header = `${method} ${path28} HTTP/1.1\r + let header = `${method} ${path29} HTTP/1.1\r `; if (typeof host === "string") { header += `host: ${host}\r @@ -7162,7 +7162,7 @@ var require_client_h2 = __commonJS({ } function writeH2(client, request3) { const session = client[kHTTP2Session]; - const { method, path: path28, host, upgrade, expectContinue, signal, headers: reqHeaders } = request3; + const { method, path: path29, host, upgrade, expectContinue, signal, headers: reqHeaders } = request3; let { body } = request3; if (upgrade) { util.errorRequest(client, request3, new Error("Upgrade not supported for H2")); @@ -7229,7 +7229,7 @@ var require_client_h2 = __commonJS({ }); return true; } - headers[HTTP2_HEADER_PATH] = path28; + headers[HTTP2_HEADER_PATH] = path29; headers[HTTP2_HEADER_SCHEME] = "https"; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH"; if (body && typeof body.read === "function") { @@ -7582,9 +7582,9 @@ var require_redirect_handler = __commonJS({ return this.handler.onHeaders(statusCode, headers, resume, statusText); } const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))); - const path28 = search ? `${pathname}${search}` : pathname; + const path29 = search ? `${pathname}${search}` : pathname; this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin); - this.opts.path = path28; + this.opts.path = path29; this.opts.origin = origin; this.opts.maxRedirections = 0; this.opts.query = null; @@ -8818,10 +8818,10 @@ var require_proxy_agent = __commonJS({ }; const { origin, - path: path28 = "/", + path: path29 = "/", headers = {} } = opts; - opts.path = origin + path28; + opts.path = origin + path29; if (!("host" in headers) && !("Host" in headers)) { const { host } = new URL2(origin); headers.host = host; @@ -10742,20 +10742,20 @@ var require_mock_utils = __commonJS({ } return true; } - function safeUrl(path28) { - if (typeof path28 !== "string") { - return path28; + function safeUrl(path29) { + if (typeof path29 !== "string") { + return path29; } - const pathSegments = path28.split("?"); + const pathSegments = path29.split("?"); if (pathSegments.length !== 2) { - return path28; + return path29; } const qp = new URLSearchParams(pathSegments.pop()); qp.sort(); return [...pathSegments, qp.toString()].join("?"); } - function matchKey(mockDispatch2, { path: path28, method, body, headers }) { - const pathMatch = matchValue(mockDispatch2.path, path28); + function matchKey(mockDispatch2, { path: path29, method, body, headers }) { + const pathMatch = matchValue(mockDispatch2.path, path29); const methodMatch = matchValue(mockDispatch2.method, method); const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true; const headersMatch = matchHeaders(mockDispatch2, headers); @@ -10777,7 +10777,7 @@ var require_mock_utils = __commonJS({ function getMockDispatch(mockDispatches, key) { const basePath = key.query ? buildURL(key.path, key.query) : key.path; const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath; - let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path28 }) => matchValue(safeUrl(path28), resolvedPath)); + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path29 }) => matchValue(safeUrl(path29), resolvedPath)); if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`); } @@ -10815,9 +10815,9 @@ var require_mock_utils = __commonJS({ } } function buildKey(opts) { - const { path: path28, method, body, headers, query } = opts; + const { path: path29, method, body, headers, query } = opts; return { - path: path28, + path: path29, method, body, headers, @@ -11280,10 +11280,10 @@ var require_pending_interceptors_formatter = __commonJS({ } format(pendingInterceptors) { const withPrettyHeaders = pendingInterceptors.map( - ({ method, path: path28, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + ({ method, path: path29, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ Method: method, Origin: origin, - Path: path28, + Path: path29, "Status code": statusCode, Persistent: persist ? PERSISTENT : NOT_PERSISTENT, Invocations: timesInvoked, @@ -11961,10 +11961,10 @@ var require_headers = __commonJS({ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i; return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j); } - function fill(headers, object) { - if (Array.isArray(object)) { - for (let i = 0; i < object.length; ++i) { - const header = object[i]; + function fill(headers, object2) { + if (Array.isArray(object2)) { + for (let i = 0; i < object2.length; ++i) { + const header = object2[i]; if (header.length !== 2) { throw webidl.errors.exception({ header: "Headers constructor", @@ -11973,10 +11973,10 @@ var require_headers = __commonJS({ } appendHeader(headers, header[0], header[1]); } - } else if (typeof object === "object" && object !== null) { - const keys = Object.keys(object); + } else if (typeof object2 === "object" && object2 !== null) { + const keys = Object.keys(object2); for (let i = 0; i < keys.length; ++i) { - appendHeader(headers, keys[i], object[keys[i]]); + appendHeader(headers, keys[i], object2[keys[i]]); } } else { throw webidl.errors.conversionFailed({ @@ -16164,9 +16164,9 @@ var require_util6 = __commonJS({ } } } - function validateCookiePath(path28) { - for (let i = 0; i < path28.length; ++i) { - const code = path28.charCodeAt(i); + function validateCookiePath(path29) { + for (let i = 0; i < path29.length; ++i) { + const code = path29.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) code === 127 || // DEL code === 59) { @@ -18806,11 +18806,11 @@ var require_undici = __commonJS({ if (typeof opts.path !== "string") { throw new InvalidArgumentError("invalid opts.path"); } - let path28 = opts.path; + let path29 = opts.path; if (!opts.path.startsWith("/")) { - path28 = `/${path28}`; + path29 = `/${path29}`; } - url2 = new URL(util.parseOrigin(url2).origin + path28); + url2 = new URL(util.parseOrigin(url2).origin + path29); } else { if (!opts) { opts = typeof url2 === "object" ? url2 : {}; @@ -20113,7 +20113,7 @@ var require_path_utils = __commonJS({ exports2.toPosixPath = toPosixPath; exports2.toWin32Path = toWin32Path; exports2.toPlatformPath = toPlatformPath; - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); function toPosixPath(pth) { return pth.replace(/[\\]/g, "/"); } @@ -20121,7 +20121,7 @@ var require_path_utils = __commonJS({ return pth.replace(/[/]/g, "\\"); } function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path28.sep); + return pth.replace(/[/\\]/g, path29.sep); } } }); @@ -20203,13 +20203,13 @@ var require_io_util = __commonJS({ exports2.isRooted = isRooted; exports2.tryGetExecutablePath = tryGetExecutablePath; exports2.getCmdPath = getCmdPath; - var fs30 = __importStar2(require("fs")); - var path28 = __importStar2(require("path")); - _a = fs30.promises, exports2.chmod = _a.chmod, exports2.copyFile = _a.copyFile, exports2.lstat = _a.lstat, exports2.mkdir = _a.mkdir, exports2.open = _a.open, exports2.readdir = _a.readdir, exports2.rename = _a.rename, exports2.rm = _a.rm, exports2.rmdir = _a.rmdir, exports2.stat = _a.stat, exports2.symlink = _a.symlink, exports2.unlink = _a.unlink; + var fs31 = __importStar2(require("fs")); + var path29 = __importStar2(require("path")); + _a = fs31.promises, exports2.chmod = _a.chmod, exports2.copyFile = _a.copyFile, exports2.lstat = _a.lstat, exports2.mkdir = _a.mkdir, exports2.open = _a.open, exports2.readdir = _a.readdir, exports2.rename = _a.rename, exports2.rm = _a.rm, exports2.rmdir = _a.rmdir, exports2.stat = _a.stat, exports2.symlink = _a.symlink, exports2.unlink = _a.unlink; exports2.IS_WINDOWS = process.platform === "win32"; function readlink(fsPath) { return __awaiter2(this, void 0, void 0, function* () { - const result = yield fs30.promises.readlink(fsPath); + const result = yield fs31.promises.readlink(fsPath); if (exports2.IS_WINDOWS && !result.endsWith("\\")) { return `${result}\\`; } @@ -20217,7 +20217,7 @@ var require_io_util = __commonJS({ }); } exports2.UV_FS_O_EXLOCK = 268435456; - exports2.READONLY = fs30.constants.O_RDONLY; + exports2.READONLY = fs31.constants.O_RDONLY; function exists(fsPath) { return __awaiter2(this, void 0, void 0, function* () { try { @@ -20259,7 +20259,7 @@ var require_io_util = __commonJS({ } if (stats && stats.isFile()) { if (exports2.IS_WINDOWS) { - const upperExt = path28.extname(filePath).toUpperCase(); + const upperExt = path29.extname(filePath).toUpperCase(); if (extensions.some((validExt) => validExt.toUpperCase() === upperExt)) { return filePath; } @@ -20283,11 +20283,11 @@ var require_io_util = __commonJS({ if (stats && stats.isFile()) { if (exports2.IS_WINDOWS) { try { - const directory = path28.dirname(filePath); - const upperName = path28.basename(filePath).toUpperCase(); + const directory = path29.dirname(filePath); + const upperName = path29.basename(filePath).toUpperCase(); for (const actualName of yield (0, exports2.readdir)(directory)) { if (upperName === actualName.toUpperCase()) { - filePath = path28.join(directory, actualName); + filePath = path29.join(directory, actualName); break; } } @@ -20399,7 +20399,7 @@ var require_io = __commonJS({ exports2.which = which9; exports2.findInPath = findInPath; var assert_1 = require("assert"); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var ioUtil = __importStar2(require_io_util()); function cp(source_1, dest_1) { return __awaiter2(this, arguments, void 0, function* (source, dest, options = {}) { @@ -20408,7 +20408,7 @@ var require_io = __commonJS({ if (destStat && destStat.isFile() && !force) { return; } - const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path28.join(dest, path28.basename(source)) : dest; + const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path29.join(dest, path29.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } @@ -20420,7 +20420,7 @@ var require_io = __commonJS({ yield cpDirRecursive(source, newDest, 0, force); } } else { - if (path28.relative(source, newDest) === "") { + if (path29.relative(source, newDest) === "") { throw new Error(`'${newDest}' and '${source}' are the same file`); } yield copyFile2(source, newDest, force); @@ -20432,7 +20432,7 @@ var require_io = __commonJS({ if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { - dest = path28.join(dest, path28.basename(source)); + dest = path29.join(dest, path29.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { @@ -20443,7 +20443,7 @@ var require_io = __commonJS({ } } } - yield mkdirP(path28.dirname(dest)); + yield mkdirP(path29.dirname(dest)); yield ioUtil.rename(source, dest); }); } @@ -20502,7 +20502,7 @@ var require_io = __commonJS({ } const extensions = []; if (ioUtil.IS_WINDOWS && process.env["PATHEXT"]) { - for (const extension of process.env["PATHEXT"].split(path28.delimiter)) { + for (const extension of process.env["PATHEXT"].split(path29.delimiter)) { if (extension) { extensions.push(extension); } @@ -20515,12 +20515,12 @@ var require_io = __commonJS({ } return []; } - if (tool.includes(path28.sep)) { + if (tool.includes(path29.sep)) { return []; } const directories = []; if (process.env.PATH) { - for (const p of process.env.PATH.split(path28.delimiter)) { + for (const p of process.env.PATH.split(path29.delimiter)) { if (p) { directories.push(p); } @@ -20528,7 +20528,7 @@ var require_io = __commonJS({ } const matches = []; for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path28.join(directory, tool), extensions); + const filePath = yield ioUtil.tryGetExecutablePath(path29.join(directory, tool), extensions); if (filePath) { matches.push(filePath); } @@ -20658,7 +20658,7 @@ var require_toolrunner = __commonJS({ var os7 = __importStar2(require("os")); var events = __importStar2(require("events")); var child = __importStar2(require("child_process")); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var io9 = __importStar2(require_io()); var ioUtil = __importStar2(require_io_util()); var timers_1 = require("timers"); @@ -20873,7 +20873,7 @@ var require_toolrunner = __commonJS({ exec() { return __awaiter2(this, void 0, void 0, function* () { if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes("/") || IS_WINDOWS && this.toolPath.includes("\\"))) { - this.toolPath = path28.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + this.toolPath = path29.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } this.toolPath = yield io9.which(this.toolPath, true); return new Promise((resolve13, reject) => __awaiter2(this, void 0, void 0, function* () { @@ -21426,7 +21426,7 @@ var require_core = __commonJS({ var file_command_1 = require_file_command(); var utils_1 = require_utils(); var os7 = __importStar2(require("os")); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var oidc_utils_1 = require_oidc_utils(); var ExitCode; (function(ExitCode2) { @@ -21452,7 +21452,7 @@ var require_core = __commonJS({ } else { (0, command_1.issueCommand)("add-path", {}, inputPath); } - process.env["PATH"] = `${inputPath}${path28.delimiter}${process.env["PATH"]}`; + process.env["PATH"] = `${inputPath}${path29.delimiter}${process.env["PATH"]}`; } function getInput2(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || ""; @@ -21589,8 +21589,8 @@ var require_context = __commonJS({ if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: "utf8" })); } else { - const path28 = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path28} does not exist${os_1.EOL}`); + const path29 = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path29} does not exist${os_1.EOL}`); } } this.eventName = process.env.GITHUB_EVENT_NAME; @@ -21891,12 +21891,12 @@ var init_universal_user_agent2 = __esm({ }); // node_modules/@octokit/endpoint/dist-bundle/index.js -function lowercaseKeys(object) { - if (!object) { +function lowercaseKeys(object2) { + if (!object2) { return {}; } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; + return Object.keys(object2).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object2[key]; return newObj; }, {}); } @@ -21972,11 +21972,11 @@ function extractUrlVariableNames(url2) { } return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); } -function omit(object, keysToOmit) { +function omit(object2, keysToOmit) { const result = { __proto__: null }; - for (const key of Object.keys(object)) { + for (const key of Object.keys(object2)) { if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; + result[key] = object2[key]; } } return result; @@ -29197,14 +29197,14 @@ var require_light = __commonJS({ var require_helpers = __commonJS({ "node_modules/jsonschema/lib/helpers.js"(exports2, module2) { "use strict"; - var ValidationError = exports2.ValidationError = function ValidationError2(message, instance, schema, path28, name, argument) { - if (Array.isArray(path28)) { - this.path = path28; - this.property = path28.reduce(function(sum, item) { + var ValidationError = exports2.ValidationError = function ValidationError2(message, instance, schema, path29, name, argument) { + if (Array.isArray(path29)) { + this.path = path29; + this.property = path29.reduce(function(sum, item) { return sum + makeSuffix(item); }, "instance"); - } else if (path28 !== void 0) { - this.property = path28; + } else if (path29 !== void 0) { + this.property = path29; } if (message) { this.message = message; @@ -29297,16 +29297,16 @@ var require_helpers = __commonJS({ name: { value: "SchemaError", enumerable: false } } ); - var SchemaContext = exports2.SchemaContext = function SchemaContext2(schema, options, path28, base, schemas) { + var SchemaContext = exports2.SchemaContext = function SchemaContext2(schema, options, path29, base, schemas) { this.schema = schema; this.options = options; - if (Array.isArray(path28)) { - this.path = path28; - this.propertyPath = path28.reduce(function(sum, item) { + if (Array.isArray(path29)) { + this.path = path29; + this.propertyPath = path29.reduce(function(sum, item) { return sum + makeSuffix(item); }, "instance"); } else { - this.propertyPath = path28; + this.propertyPath = path29; } this.base = base; this.schemas = schemas; @@ -29315,10 +29315,10 @@ var require_helpers = __commonJS({ return (() => resolveUrl(this.base, target))(); }; SchemaContext.prototype.makeChild = function makeChild(schema, propertyName) { - var path28 = propertyName === void 0 ? this.path : this.path.concat([propertyName]); + var path29 = propertyName === void 0 ? this.path : this.path.concat([propertyName]); var id = schema.$id || schema.id; let base = (() => resolveUrl(this.base, id || ""))(); - var ctx = new SchemaContext(schema, this.options, path28, base, Object.create(this.schemas)); + var ctx = new SchemaContext(schema, this.options, path29, base, Object.create(this.schemas)); if (id && !ctx.schemas[base]) { ctx.schemas[base] = schema; } @@ -29488,13 +29488,13 @@ var require_helpers = __commonJS({ exports2.encodePath = function encodePointer(a) { return a.map(pathEncoder).join(""); }; - exports2.getDecimalPlaces = function getDecimalPlaces(number) { + exports2.getDecimalPlaces = function getDecimalPlaces(number2) { var decimalPlaces = 0; - if (isNaN(number)) return decimalPlaces; - if (typeof number !== "number") { - number = Number(number); + if (isNaN(number2)) return decimalPlaces; + if (typeof number2 !== "number") { + number2 = Number(number2); } - var parts = number.toString().split("e"); + var parts = number2.toString().split("e"); if (parts.length === 2) { if (parts[1][0] !== "-") { return decimalPlaces; @@ -29694,11 +29694,11 @@ var require_attribute = __commonJS({ } return result; }; - function getEnumerableProperty(object, key) { - if (Object.hasOwnProperty.call(object, key)) return object[key]; - if (!(key in object)) return; - while (object = Object.getPrototypeOf(object)) { - if (Object.propertyIsEnumerable.call(object, key)) return object[key]; + function getEnumerableProperty(object2, key) { + if (Object.hasOwnProperty.call(object2, key)) return object2[key]; + if (!(key in object2)) return; + while (object2 = Object.getPrototypeOf(object2)) { + if (Object.propertyIsEnumerable.call(object2, key)) return object2[key]; } } validators.propertyNames = function validatePropertyNames(instance, schema, options, ctx) { @@ -30779,7 +30779,7 @@ var require_internal_path_helper = __commonJS({ exports2.hasRoot = hasRoot; exports2.normalizeSeparators = normalizeSeparators; exports2.safeTrimTrailingSeparator = safeTrimTrailingSeparator; - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var assert_1 = __importDefault2(require("assert")); var IS_WINDOWS = process.platform === "win32"; function dirname5(p) { @@ -30787,7 +30787,7 @@ var require_internal_path_helper = __commonJS({ if (IS_WINDOWS && /^\\\\[^\\]+(\\[^\\]+)?$/.test(p)) { return p; } - let result = path28.dirname(p); + let result = path29.dirname(p); if (IS_WINDOWS && /^\\\\[^\\]+\\[^\\]+\\$/.test(result)) { result = safeTrimTrailingSeparator(result); } @@ -30824,7 +30824,7 @@ var require_internal_path_helper = __commonJS({ (0, assert_1.default)(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); if (root.endsWith("/") || IS_WINDOWS && root.endsWith("\\")) { } else { - root += path28.sep; + root += path29.sep; } return root + itemPath; } @@ -30858,10 +30858,10 @@ var require_internal_path_helper = __commonJS({ return ""; } p = normalizeSeparators(p); - if (!p.endsWith(path28.sep)) { + if (!p.endsWith(path29.sep)) { return p; } - if (p === path28.sep) { + if (p === path29.sep) { return p; } if (IS_WINDOWS && /^[A-Z]:\\$/i.test(p)) { @@ -31208,7 +31208,7 @@ var require_minimatch = __commonJS({ "node_modules/minimatch/minimatch.js"(exports2, module2) { module2.exports = minimatch; minimatch.Minimatch = Minimatch; - var path28 = (function() { + var path29 = (function() { try { return require("path"); } catch (e) { @@ -31216,7 +31216,7 @@ var require_minimatch = __commonJS({ })() || { sep: "/" }; - minimatch.sep = path28.sep; + minimatch.sep = path29.sep; var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}; var expand2 = require_brace_expansion(); var plTypes = { @@ -31305,8 +31305,8 @@ var require_minimatch = __commonJS({ assertValidPattern(pattern); if (!options) options = {}; pattern = pattern.trim(); - if (!options.allowWindowsEscape && path28.sep !== "/") { - pattern = pattern.split(path28.sep).join("/"); + if (!options.allowWindowsEscape && path29.sep !== "/") { + pattern = pattern.split(path29.sep).join("/"); } this.options = options; this.maxGlobstarRecursion = options.maxGlobstarRecursion !== void 0 ? options.maxGlobstarRecursion : 200; @@ -31677,8 +31677,8 @@ var require_minimatch = __commonJS({ if (this.empty) return f === ""; if (f === "/" && partial) return true; var options = this.options; - if (path28.sep !== "/") { - f = f.split(path28.sep).join("/"); + if (path29.sep !== "/") { + f = f.split(path29.sep).join("/"); } f = f.split(slashSplit); this.debug(this.pattern, "split", f); @@ -31921,7 +31921,7 @@ var require_internal_path = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Path = void 0; - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var pathHelper = __importStar2(require_internal_path_helper()); var assert_1 = __importDefault2(require("assert")); var IS_WINDOWS = process.platform === "win32"; @@ -31936,12 +31936,12 @@ var require_internal_path = __commonJS({ (0, assert_1.default)(itemPath, `Parameter 'itemPath' must not be empty`); itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); if (!pathHelper.hasRoot(itemPath)) { - this.segments = itemPath.split(path28.sep); + this.segments = itemPath.split(path29.sep); } else { let remaining = itemPath; let dir = pathHelper.dirname(remaining); while (dir !== remaining) { - const basename2 = path28.basename(remaining); + const basename2 = path29.basename(remaining); this.segments.unshift(basename2); remaining = dir; dir = pathHelper.dirname(remaining); @@ -31959,7 +31959,7 @@ var require_internal_path = __commonJS({ (0, assert_1.default)(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); this.segments.push(segment); } else { - (0, assert_1.default)(!segment.includes(path28.sep), `Parameter 'itemPath' contains unexpected path separators`); + (0, assert_1.default)(!segment.includes(path29.sep), `Parameter 'itemPath' contains unexpected path separators`); this.segments.push(segment); } } @@ -31970,12 +31970,12 @@ var require_internal_path = __commonJS({ */ toString() { let result = this.segments[0]; - let skipSlash = result.endsWith(path28.sep) || IS_WINDOWS && /^[A-Z]:$/i.test(result); + let skipSlash = result.endsWith(path29.sep) || IS_WINDOWS && /^[A-Z]:$/i.test(result); for (let i = 1; i < this.segments.length; i++) { if (skipSlash) { skipSlash = false; } else { - result += path28.sep; + result += path29.sep; } result += this.segments[i]; } @@ -32033,7 +32033,7 @@ var require_internal_pattern = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.Pattern = void 0; var os7 = __importStar2(require("os")); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var pathHelper = __importStar2(require_internal_path_helper()); var assert_1 = __importDefault2(require("assert")); var minimatch_1 = require_minimatch(); @@ -32062,7 +32062,7 @@ var require_internal_pattern = __commonJS({ } pattern = _Pattern.fixupPattern(pattern, homedir2); this.segments = new internal_path_1.Path(pattern).segments; - this.trailingSeparator = pathHelper.normalizeSeparators(pattern).endsWith(path28.sep); + this.trailingSeparator = pathHelper.normalizeSeparators(pattern).endsWith(path29.sep); pattern = pathHelper.safeTrimTrailingSeparator(pattern); let foundGlob = false; const searchSegments = this.segments.map((x) => _Pattern.getLiteral(x)).filter((x) => !foundGlob && !(foundGlob = x === "")); @@ -32086,8 +32086,8 @@ var require_internal_pattern = __commonJS({ match(itemPath) { if (this.segments[this.segments.length - 1] === "**") { itemPath = pathHelper.normalizeSeparators(itemPath); - if (!itemPath.endsWith(path28.sep) && this.isImplicitPattern === false) { - itemPath = `${itemPath}${path28.sep}`; + if (!itemPath.endsWith(path29.sep) && this.isImplicitPattern === false) { + itemPath = `${itemPath}${path29.sep}`; } } else { itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); @@ -32122,9 +32122,9 @@ var require_internal_pattern = __commonJS({ (0, assert_1.default)(literalSegments.every((x, i) => (x !== "." || i === 0) && x !== ".."), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); (0, assert_1.default)(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); pattern = pathHelper.normalizeSeparators(pattern); - if (pattern === "." || pattern.startsWith(`.${path28.sep}`)) { + if (pattern === "." || pattern.startsWith(`.${path29.sep}`)) { pattern = _Pattern.globEscape(process.cwd()) + pattern.substr(1); - } else if (pattern === "~" || pattern.startsWith(`~${path28.sep}`)) { + } else if (pattern === "~" || pattern.startsWith(`~${path29.sep}`)) { homedir2 = homedir2 || os7.homedir(); (0, assert_1.default)(homedir2, "Unable to determine HOME directory"); (0, assert_1.default)(pathHelper.hasAbsoluteRoot(homedir2), `Expected HOME directory to be a rooted path. Actual '${homedir2}'`); @@ -32208,8 +32208,8 @@ var require_internal_search_state = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.SearchState = void 0; var SearchState = class { - constructor(path28, level) { - this.path = path28; + constructor(path29, level) { + this.path = path29; this.level = level; } }; @@ -32351,9 +32351,9 @@ var require_internal_globber = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DefaultGlobber = void 0; var core30 = __importStar2(require_core()); - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var globOptionsHelper = __importStar2(require_internal_glob_options_helper()); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var patternHelper = __importStar2(require_internal_pattern_helper()); var internal_match_kind_1 = require_internal_match_kind(); var internal_pattern_1 = require_internal_pattern(); @@ -32405,7 +32405,7 @@ var require_internal_globber = __commonJS({ for (const searchPath of patternHelper.getSearchPaths(patterns)) { core30.debug(`Search path '${searchPath}'`); try { - yield __await2(fs30.promises.lstat(searchPath)); + yield __await2(fs31.promises.lstat(searchPath)); } catch (err) { if (err.code === "ENOENT") { continue; @@ -32429,7 +32429,7 @@ var require_internal_globber = __commonJS({ if (!stats) { continue; } - if (options.excludeHiddenFiles && path28.basename(item.path).match(/^\./)) { + if (options.excludeHiddenFiles && path29.basename(item.path).match(/^\./)) { continue; } if (stats.isDirectory()) { @@ -32439,7 +32439,7 @@ var require_internal_globber = __commonJS({ continue; } const childLevel = item.level + 1; - const childItems = (yield __await2(fs30.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path28.join(item.path, x), childLevel)); + const childItems = (yield __await2(fs31.promises.readdir(item.path))).map((x) => new internal_search_state_1.SearchState(path29.join(item.path, x), childLevel)); stack.push(...childItems.reverse()); } else if (match & internal_match_kind_1.MatchKind.File) { yield yield __await2(item.path); @@ -32474,7 +32474,7 @@ var require_internal_globber = __commonJS({ let stats; if (options.followSymbolicLinks) { try { - stats = yield fs30.promises.stat(item.path); + stats = yield fs31.promises.stat(item.path); } catch (err) { if (err.code === "ENOENT") { if (options.omitBrokenSymbolicLinks) { @@ -32486,10 +32486,10 @@ var require_internal_globber = __commonJS({ throw err; } } else { - stats = yield fs30.promises.lstat(item.path); + stats = yield fs31.promises.lstat(item.path); } if (stats.isDirectory() && options.followSymbolicLinks) { - const realPath = yield fs30.promises.realpath(item.path); + const realPath = yield fs31.promises.realpath(item.path); while (traversalChain.length >= item.level) { traversalChain.pop(); } @@ -32598,10 +32598,10 @@ var require_internal_hash_files = __commonJS({ exports2.hashFiles = hashFiles2; var crypto3 = __importStar2(require("crypto")); var core30 = __importStar2(require_core()); - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var stream2 = __importStar2(require("stream")); var util = __importStar2(require("util")); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); function hashFiles2(globber_1, currentWorkspace_1) { return __awaiter2(this, arguments, void 0, function* (globber, currentWorkspace, verbose = false) { var _a, e_1, _b, _c; @@ -32617,17 +32617,17 @@ var require_internal_hash_files = __commonJS({ _e = false; const file = _c; writeDelegate(file); - if (!file.startsWith(`${githubWorkspace}${path28.sep}`)) { + if (!file.startsWith(`${githubWorkspace}${path29.sep}`)) { writeDelegate(`Ignore '${file}' since it is not under GITHUB_WORKSPACE.`); continue; } - if (fs30.statSync(file).isDirectory()) { + if (fs31.statSync(file).isDirectory()) { writeDelegate(`Skip directory '${file}'.`); continue; } const hash2 = crypto3.createHash("sha256"); const pipeline = util.promisify(stream2.pipeline); - yield pipeline(fs30.createReadStream(file), hash2); + yield pipeline(fs31.createReadStream(file), hash2); result.write(hash2.digest()); count++; if (!hasMatch) { @@ -34002,8 +34002,8 @@ var require_cacheUtils = __commonJS({ var glob2 = __importStar2(require_glob()); var io9 = __importStar2(require_io()); var crypto3 = __importStar2(require("crypto")); - var fs30 = __importStar2(require("fs")); - var path28 = __importStar2(require("path")); + var fs31 = __importStar2(require("fs")); + var path29 = __importStar2(require("path")); var semver11 = __importStar2(require_semver3()); var util = __importStar2(require("util")); var constants_1 = require_constants7(); @@ -34023,15 +34023,15 @@ var require_cacheUtils = __commonJS({ baseLocation = "/home"; } } - tempDirectory = path28.join(baseLocation, "actions", "temp"); + tempDirectory = path29.join(baseLocation, "actions", "temp"); } - const dest = path28.join(tempDirectory, crypto3.randomUUID()); + const dest = path29.join(tempDirectory, crypto3.randomUUID()); yield io9.mkdirP(dest); return dest; }); } function getArchiveFileSizeInBytes(filePath) { - return fs30.statSync(filePath).size; + return fs31.statSync(filePath).size; } function resolvePaths(patterns) { return __awaiter2(this, void 0, void 0, function* () { @@ -34047,7 +34047,7 @@ var require_cacheUtils = __commonJS({ _c = _g.value; _e = false; const file = _c; - const relativeFile = path28.relative(workspace, file).replace(new RegExp(`\\${path28.sep}`, "g"), "/"); + const relativeFile = path29.relative(workspace, file).replace(new RegExp(`\\${path29.sep}`, "g"), "/"); core30.debug(`Matched: ${relativeFile}`); if (relativeFile === "") { paths.push("."); @@ -34069,7 +34069,7 @@ var require_cacheUtils = __commonJS({ } function unlinkFile(filePath) { return __awaiter2(this, void 0, void 0, function* () { - return util.promisify(fs30.unlink)(filePath); + return util.promisify(fs31.unlink)(filePath); }); } function getVersion(app_1) { @@ -34111,7 +34111,7 @@ var require_cacheUtils = __commonJS({ } function getGnuTarPathOnWindows() { return __awaiter2(this, void 0, void 0, function* () { - if (fs30.existsSync(constants_1.GnuTarPathOnWindows)) { + if (fs31.existsSync(constants_1.GnuTarPathOnWindows)) { return constants_1.GnuTarPathOnWindows; } const versionOutput = yield getVersion("tar"); @@ -34574,13 +34574,13 @@ function __disposeResources(env) { } return next(); } -function __rewriteRelativeImportExtension(path28, preserveJsx) { - if (typeof path28 === "string" && /^\.\.?\//.test(path28)) { - return path28.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) { +function __rewriteRelativeImportExtension(path29, preserveJsx) { + if (typeof path29 === "string" && /^\.\.?\//.test(path29)) { + return path29.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) { return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js"; }); } - return path28; + return path29; } var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default; var init_tslib_es6 = __esm({ @@ -38994,8 +38994,8 @@ var require_getClient = __commonJS({ } const { allowInsecureConnection, httpClient } = clientOptions; const endpointUrl = clientOptions.endpoint ?? endpoint2; - const client = (path28, ...args) => { - const getUrl = (requestOptions) => (0, urlHelpers_js_1.buildRequestUrl)(endpointUrl, path28, args, { allowInsecureConnection, ...requestOptions }); + const client = (path29, ...args) => { + const getUrl = (requestOptions) => (0, urlHelpers_js_1.buildRequestUrl)(endpointUrl, path29, args, { allowInsecureConnection, ...requestOptions }); return { get: (requestOptions = {}) => { return buildOperation("GET", getUrl(requestOptions), pipeline, requestOptions, allowInsecureConnection, httpClient); @@ -41670,7 +41670,7 @@ var require_serializer = __commonJS({ * * @returns A valid serialized Javascript object */ - serialize(mapper, object, objectName, options = { xml: {} }) { + serialize(mapper, object2, objectName, options = { xml: {} }) { const updatedOptions = { xml: { rootName: options.xml.rootName ?? "", @@ -41687,40 +41687,40 @@ var require_serializer = __commonJS({ payload = []; } if (mapper.isConstant) { - object = mapper.defaultValue; + object2 = mapper.defaultValue; } const { required, nullable } = mapper; - if (required && nullable && object === void 0) { + if (required && nullable && object2 === void 0) { throw new Error(`${objectName} cannot be undefined.`); } - if (required && !nullable && (object === void 0 || object === null)) { + if (required && !nullable && (object2 === void 0 || object2 === null)) { throw new Error(`${objectName} cannot be null or undefined.`); } - if (!required && nullable === false && object === null) { + if (!required && nullable === false && object2 === null) { throw new Error(`${objectName} cannot be null.`); } - if (object === void 0 || object === null) { - payload = object; + if (object2 === void 0 || object2 === null) { + payload = object2; } else { if (mapperType.match(/^any$/i) !== null) { - payload = object; + payload = object2; } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) { - payload = serializeBasicTypes(mapperType, objectName, object); + payload = serializeBasicTypes(mapperType, objectName, object2); } else if (mapperType.match(/^Enum$/i) !== null) { const enumMapper = mapper; - payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); + payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object2); } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { - payload = serializeDateTypes(mapperType, object, objectName); + payload = serializeDateTypes(mapperType, object2, objectName); } else if (mapperType.match(/^ByteArray$/i) !== null) { - payload = serializeByteArrayType(objectName, object); + payload = serializeByteArrayType(objectName, object2); } else if (mapperType.match(/^Base64Url$/i) !== null) { - payload = serializeBase64UrlType(objectName, object); + payload = serializeBase64UrlType(objectName, object2); } else if (mapperType.match(/^Sequence$/i) !== null) { - payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + payload = serializeSequenceType(this, mapper, object2, objectName, Boolean(this.isXML), updatedOptions); } else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + payload = serializeDictionaryType(this, mapper, object2, objectName, Boolean(this.isXML), updatedOptions); } else if (mapperType.match(/^Composite$/i) !== null) { - payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + payload = serializeCompositeType(this, mapper, object2, objectName, Boolean(this.isXML), updatedOptions); } } return payload; @@ -41960,8 +41960,8 @@ var require_serializer = __commonJS({ } return value; } - function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { - if (!Array.isArray(object)) { + function serializeSequenceType(serializer, mapper, object2, objectName, isXml, options) { + if (!Array.isArray(object2)) { throw new Error(`${objectName} must be of type Array.`); } let elementType = mapper.type.element; @@ -41972,8 +41972,8 @@ var require_serializer = __commonJS({ elementType = serializer.modelMappers[elementType.type.className] ?? elementType; } const tempArray = []; - for (let i = 0; i < object.length; i++) { - const serializedValue = serializer.serialize(elementType, object[i], objectName, options); + for (let i = 0; i < object2.length; i++) { + const serializedValue = serializer.serialize(elementType, object2[i], objectName, options); if (isXml && elementType.xmlNamespace) { const xmlnsKey = elementType.xmlNamespacePrefix ? `xmlns:${elementType.xmlNamespacePrefix}` : "xmlns"; if (elementType.type.name === "Composite") { @@ -41990,8 +41990,8 @@ var require_serializer = __commonJS({ } return tempArray; } - function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { - if (typeof object !== "object") { + function serializeDictionaryType(serializer, mapper, object2, objectName, isXml, options) { + if (typeof object2 !== "object") { throw new Error(`${objectName} must be of type object.`); } const valueType = mapper.type.value; @@ -41999,8 +41999,8 @@ var require_serializer = __commonJS({ throw new Error(`"value" metadata for a Dictionary must be defined in the mapper and it must of type "object" in ${objectName}.`); } const tempDictionary = {}; - for (const key of Object.keys(object)) { - const serializedValue = serializer.serialize(valueType, object[key], objectName, options); + for (const key of Object.keys(object2)) { + const serializedValue = serializer.serialize(valueType, object2[key], objectName, options); tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); } if (isXml && mapper.xmlNamespace) { @@ -42040,11 +42040,11 @@ var require_serializer = __commonJS({ } return modelProps; } - function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { + function serializeCompositeType(serializer, mapper, object2, objectName, isXml, options) { if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { - mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); + mapper = getPolymorphicMapper(serializer, mapper, object2, "clientName"); } - if (object !== void 0 && object !== null) { + if (object2 !== void 0 && object2 !== null) { const payload = {}; const modelProps = resolveModelProperties(serializer, mapper, objectName); for (const key of Object.keys(modelProps)) { @@ -42065,7 +42065,7 @@ var require_serializer = __commonJS({ propName = paths.pop(); for (const pathName of paths) { const childObject = parentObject[pathName]; - if ((childObject === void 0 || childObject === null) && (object[key] !== void 0 && object[key] !== null || propertyMapper.defaultValue !== void 0)) { + if ((childObject === void 0 || childObject === null) && (object2[key] !== void 0 && object2[key] !== null || propertyMapper.defaultValue !== void 0)) { parentObject[pathName] = {}; } parentObject = parentObject[pathName]; @@ -42080,7 +42080,7 @@ var require_serializer = __commonJS({ }; } const propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName : objectName; - let toSerialize = object[key]; + let toSerialize = object2[key]; const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && (toSerialize === void 0 || toSerialize === null)) { toSerialize = mapper.serializedName; @@ -42102,16 +42102,16 @@ var require_serializer = __commonJS({ const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); if (additionalPropertiesMapper) { const propNames = Object.keys(modelProps); - for (const clientPropName in object) { + for (const clientPropName in object2) { const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); if (isAdditionalProperty) { - payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); + payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object2[clientPropName], objectName + '["' + clientPropName + '"]', options); } } } return payload; } - return object; + return object2; } function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { if (!isXml || !propertyMapper.xmlNamespace) { @@ -42295,7 +42295,7 @@ var require_serializer = __commonJS({ } return void 0; } - function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { + function getPolymorphicMapper(serializer, mapper, object2, polymorphicPropertyName) { const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); if (polymorphicDiscriminator) { let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; @@ -42303,7 +42303,7 @@ var require_serializer = __commonJS({ if (polymorphicPropertyName === "serializedName") { discriminatorName = discriminatorName.replace(/\\/gi, ""); } - const discriminatorValue = object[discriminatorName]; + const discriminatorValue = object2[discriminatorName]; const typeName = mapper.type.uberParent ?? mapper.type.className; if (typeof discriminatorValue === "string" && typeName) { const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName); @@ -42866,15 +42866,15 @@ var require_urlHelpers2 = __commonJS({ let isAbsolutePath = false; let requestUrl = replaceAll(baseUri, urlReplacements); if (operationSpec.path) { - let path28 = replaceAll(operationSpec.path, urlReplacements); - if (operationSpec.path === "/{nextLink}" && path28.startsWith("/")) { - path28 = path28.substring(1); + let path29 = replaceAll(operationSpec.path, urlReplacements); + if (operationSpec.path === "/{nextLink}" && path29.startsWith("/")) { + path29 = path29.substring(1); } - if (isAbsoluteUrl(path28)) { - requestUrl = path28; + if (isAbsoluteUrl(path29)) { + requestUrl = path29; isAbsolutePath = true; } else { - requestUrl = appendPath(requestUrl, path28); + requestUrl = appendPath(requestUrl, path29); } } const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject); @@ -42920,9 +42920,9 @@ var require_urlHelpers2 = __commonJS({ } const searchStart = pathToAppend.indexOf("?"); if (searchStart !== -1) { - const path28 = pathToAppend.substring(0, searchStart); + const path29 = pathToAppend.substring(0, searchStart); const search = pathToAppend.substring(searchStart + 1); - newPath = newPath + path28; + newPath = newPath + path29; if (search) { parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search; } @@ -45838,10 +45838,10 @@ var require_utils_common = __commonJS({ var constants_js_1 = require_constants10(); function escapeURLPath(url2) { const urlParsed = new URL(url2); - let path28 = urlParsed.pathname; - path28 = path28 || "/"; - path28 = escape2(path28); - urlParsed.pathname = path28; + let path29 = urlParsed.pathname; + path29 = path29 || "/"; + path29 = escape2(path29); + urlParsed.pathname = path29; return urlParsed.toString(); } function getProxyUriFromDevConnString(connectionString) { @@ -45926,9 +45926,9 @@ var require_utils_common = __commonJS({ } function appendToURLPath(url2, name) { const urlParsed = new URL(url2); - let path28 = urlParsed.pathname; - path28 = path28 ? path28.endsWith("/") ? `${path28}${name}` : `${path28}/${name}` : name; - urlParsed.pathname = path28; + let path29 = urlParsed.pathname; + path29 = path29 ? path29.endsWith("/") ? `${path29}${name}` : `${path29}/${name}` : name; + urlParsed.pathname = path29; return urlParsed.toString(); } function setURLParameter(url2, name, value) { @@ -47155,9 +47155,9 @@ var require_StorageSharedKeyCredentialPolicy = __commonJS({ * @param request - */ getCanonicalizedResourceString(request3) { - const path28 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; + const path29 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${this.factory.accountName}${path28}`; + canonicalizedResourceString += `/${this.factory.accountName}${path29}`; const queries = (0, utils_common_js_1.getURLQueries)(request3.url); const lowercaseQueries = {}; if (queries) { @@ -47896,10 +47896,10 @@ var require_utils_common2 = __commonJS({ var constants_js_1 = require_constants11(); function escapeURLPath(url2) { const urlParsed = new URL(url2); - let path28 = urlParsed.pathname; - path28 = path28 || "/"; - path28 = escape2(path28); - urlParsed.pathname = path28; + let path29 = urlParsed.pathname; + path29 = path29 || "/"; + path29 = escape2(path29); + urlParsed.pathname = path29; return urlParsed.toString(); } function getProxyUriFromDevConnString(connectionString) { @@ -47984,9 +47984,9 @@ var require_utils_common2 = __commonJS({ } function appendToURLPath(url2, name) { const urlParsed = new URL(url2); - let path28 = urlParsed.pathname; - path28 = path28 ? path28.endsWith("/") ? `${path28}${name}` : `${path28}/${name}` : name; - urlParsed.pathname = path28; + let path29 = urlParsed.pathname; + path29 = path29 ? path29.endsWith("/") ? `${path29}${name}` : `${path29}/${name}` : name; + urlParsed.pathname = path29; return urlParsed.toString(); } function setURLParameter(url2, name, value) { @@ -48907,9 +48907,9 @@ var require_StorageSharedKeyCredentialPolicy2 = __commonJS({ * @param request - */ getCanonicalizedResourceString(request3) { - const path28 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; + const path29 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${this.factory.accountName}${path28}`; + canonicalizedResourceString += `/${this.factory.accountName}${path29}`; const queries = (0, utils_common_js_1.getURLQueries)(request3.url); const lowercaseQueries = {}; if (queries) { @@ -49539,9 +49539,9 @@ var require_StorageSharedKeyCredentialPolicyV2 = __commonJS({ return canonicalizedHeadersStringToSign; } function getCanonicalizedResourceString(request3) { - const path28 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; + const path29 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${options.accountName}${path28}`; + canonicalizedResourceString += `/${options.accountName}${path29}`; const queries = (0, utils_common_js_1.getURLQueries)(request3.url); const lowercaseQueries = {}; if (queries) { @@ -49886,9 +49886,9 @@ var require_StorageSharedKeyCredentialPolicyV22 = __commonJS({ return canonicalizedHeadersStringToSign; } function getCanonicalizedResourceString(request3) { - const path28 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; + const path29 = (0, utils_common_js_1.getURLPath)(request3.url) || "/"; let canonicalizedResourceString = ""; - canonicalizedResourceString += `/${options.accountName}${path28}`; + canonicalizedResourceString += `/${options.accountName}${path29}`; const queries = (0, utils_common_js_1.getURLQueries)(request3.url); const lowercaseQueries = {}; if (queries) { @@ -71543,8 +71543,8 @@ var require_BlobBatch = __commonJS({ if (this.operationCount >= constants_js_1.BATCH_MAX_REQUEST) { throw new RangeError(`Cannot exceed ${constants_js_1.BATCH_MAX_REQUEST} sub requests in a single batch`); } - const path28 = (0, utils_common_js_1.getURLPath)(subRequest.url); - if (!path28 || path28 === "") { + const path29 = (0, utils_common_js_1.getURLPath)(subRequest.url); + if (!path29 || path29 === "") { throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); } } @@ -71622,8 +71622,8 @@ var require_BlobBatchClient = __commonJS({ pipeline = (0, Pipeline_js_1.newPipeline)(credentialOrPipeline, options); } const storageClientContext = new StorageContextClient_js_1.StorageContextClient(url2, (0, Pipeline_js_1.getCoreClientOptions)(pipeline)); - const path28 = (0, utils_common_js_1.getURLPath)(url2); - if (path28 && path28 !== "/") { + const path29 = (0, utils_common_js_1.getURLPath)(url2); + if (path29 && path29 !== "/") { this.serviceOrContainerContext = storageClientContext.container; } else { this.serviceOrContainerContext = storageClientContext.service; @@ -74910,7 +74910,7 @@ var require_downloadUtils = __commonJS({ var http_client_1 = require_lib(); var storage_blob_1 = require_commonjs15(); var buffer = __importStar2(require("buffer")); - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var stream2 = __importStar2(require("stream")); var util = __importStar2(require("util")); var utils = __importStar2(require_cacheUtils()); @@ -75021,7 +75021,7 @@ var require_downloadUtils = __commonJS({ exports2.DownloadProgress = DownloadProgress; function downloadCacheHttpClient(archiveLocation, archivePath) { return __awaiter2(this, void 0, void 0, function* () { - const writeStream = fs30.createWriteStream(archivePath); + const writeStream = fs31.createWriteStream(archivePath); const httpClient = new http_client_1.HttpClient("actions/cache"); const downloadResponse = yield (0, requestUtils_1.retryHttpClientResponse)("downloadCache", () => __awaiter2(this, void 0, void 0, function* () { return httpClient.get(archiveLocation); @@ -75046,7 +75046,7 @@ var require_downloadUtils = __commonJS({ function downloadCacheHttpClientConcurrent(archiveLocation, archivePath, options) { return __awaiter2(this, void 0, void 0, function* () { var _a; - const archiveDescriptor = yield fs30.promises.open(archivePath, "w"); + const archiveDescriptor = yield fs31.promises.open(archivePath, "w"); const httpClient = new http_client_1.HttpClient("actions/cache", void 0, { socketTimeout: options.timeoutInMs, keepAlive: true @@ -75162,7 +75162,7 @@ var require_downloadUtils = __commonJS({ } else { const maxSegmentSize = Math.min(134217728, buffer.constants.MAX_LENGTH); const downloadProgress = new DownloadProgress(contentLength); - const fd = fs30.openSync(archivePath, "w"); + const fd = fs31.openSync(archivePath, "w"); try { downloadProgress.startDisplayTimer(); const controller = new abort_controller_1.AbortController(); @@ -75180,12 +75180,12 @@ var require_downloadUtils = __commonJS({ controller.abort(); throw new Error("Aborting cache download as the download time exceeded the timeout."); } else if (Buffer.isBuffer(result)) { - fs30.writeFileSync(fd, result); + fs31.writeFileSync(fd, result); } } } finally { downloadProgress.stopDisplayTimer(); - fs30.closeSync(fd); + fs31.closeSync(fd); } } }); @@ -75507,7 +75507,7 @@ var require_cacheHttpClient = __commonJS({ var core30 = __importStar2(require_core()); var http_client_1 = require_lib(); var auth_1 = require_auth(); - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var url_1 = require("url"); var utils = __importStar2(require_cacheUtils()); var uploadUtils_1 = require_uploadUtils(); @@ -75642,7 +75642,7 @@ Other caches with similar key:`); return __awaiter2(this, void 0, void 0, function* () { const fileSize = utils.getArchiveFileSizeInBytes(archivePath); const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); - const fd = fs30.openSync(archivePath, "r"); + const fd = fs31.openSync(archivePath, "r"); const uploadOptions = (0, options_1.getUploadOptions)(options); const concurrency = utils.assertDefined("uploadConcurrency", uploadOptions.uploadConcurrency); const maxChunkSize = utils.assertDefined("uploadChunkSize", uploadOptions.uploadChunkSize); @@ -75656,7 +75656,7 @@ Other caches with similar key:`); const start = offset; const end = offset + chunkSize - 1; offset += maxChunkSize; - yield uploadChunk(httpClient, resourceUrl, () => fs30.createReadStream(archivePath, { + yield uploadChunk(httpClient, resourceUrl, () => fs31.createReadStream(archivePath, { fd, start, end, @@ -75667,7 +75667,7 @@ Other caches with similar key:`); } }))); } finally { - fs30.closeSync(fd); + fs31.closeSync(fd); } return; }); @@ -78574,9 +78574,9 @@ var require_enum_object = __commonJS({ if (!isEnumObject(enumObject)) throw new Error("not a typescript enum object"); let values = []; - for (let [name, number] of Object.entries(enumObject)) - if (typeof number == "number") - values.push({ name, number }); + for (let [name, number2] of Object.entries(enumObject)) + if (typeof number2 == "number") + values.push({ name, number: number2 }); return values; } exports2.listEnumValues = listEnumValues; @@ -80932,7 +80932,7 @@ var require_tar = __commonJS({ var exec_1 = require_exec(); var io9 = __importStar2(require_io()); var fs_1 = require("fs"); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var utils = __importStar2(require_cacheUtils()); var constants_1 = require_constants7(); var IS_WINDOWS = process.platform === "win32"; @@ -80978,13 +80978,13 @@ var require_tar = __commonJS({ const BSD_TAR_ZSTD = tarPath.type === constants_1.ArchiveToolType.BSD && compressionMethod !== constants_1.CompressionMethod.Gzip && IS_WINDOWS; switch (type) { case "create": - args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path28.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path28.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path28.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); + args.push("--posix", "-cf", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path29.sep}`, "g"), "/"), "--exclude", BSD_TAR_ZSTD ? tarFile : cacheFileName.replace(new RegExp(`\\${path29.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path29.sep}`, "g"), "/"), "--files-from", constants_1.ManifestFilename); break; case "extract": - args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path28.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path28.sep}`, "g"), "/")); + args.push("-xf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path29.sep}`, "g"), "/"), "-P", "-C", workingDirectory.replace(new RegExp(`\\${path29.sep}`, "g"), "/")); break; case "list": - args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path28.sep}`, "g"), "/"), "-P"); + args.push("-tf", BSD_TAR_ZSTD ? tarFile : archivePath.replace(new RegExp(`\\${path29.sep}`, "g"), "/"), "-P"); break; } if (tarPath.type === constants_1.ArchiveToolType.GNU) { @@ -81030,7 +81030,7 @@ var require_tar = __commonJS({ return BSD_TAR_ZSTD ? [ "zstd -d --long=30 --force -o", constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path28.sep}`, "g"), "/") + archivePath.replace(new RegExp(`\\${path29.sep}`, "g"), "/") ] : [ "--use-compress-program", IS_WINDOWS ? '"zstd -d --long=30"' : "unzstd --long=30" @@ -81039,7 +81039,7 @@ var require_tar = __commonJS({ return BSD_TAR_ZSTD ? [ "zstd -d --force -o", constants_1.TarFilename, - archivePath.replace(new RegExp(`\\${path28.sep}`, "g"), "/") + archivePath.replace(new RegExp(`\\${path29.sep}`, "g"), "/") ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -d"' : "unzstd"]; default: return ["-z"]; @@ -81054,7 +81054,7 @@ var require_tar = __commonJS({ case constants_1.CompressionMethod.Zstd: return BSD_TAR_ZSTD ? [ "zstd -T0 --long=30 --force -o", - cacheFileName.replace(new RegExp(`\\${path28.sep}`, "g"), "/"), + cacheFileName.replace(new RegExp(`\\${path29.sep}`, "g"), "/"), constants_1.TarFilename ] : [ "--use-compress-program", @@ -81063,7 +81063,7 @@ var require_tar = __commonJS({ case constants_1.CompressionMethod.ZstdWithoutLong: return BSD_TAR_ZSTD ? [ "zstd -T0 --force -o", - cacheFileName.replace(new RegExp(`\\${path28.sep}`, "g"), "/"), + cacheFileName.replace(new RegExp(`\\${path29.sep}`, "g"), "/"), constants_1.TarFilename ] : ["--use-compress-program", IS_WINDOWS ? '"zstd -T0"' : "zstdmt"]; default: @@ -81101,7 +81101,7 @@ var require_tar = __commonJS({ } function createTar(archiveFolder, sourceDirectories, compressionMethod) { return __awaiter2(this, void 0, void 0, function* () { - (0, fs_1.writeFileSync)(path28.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); + (0, fs_1.writeFileSync)(path29.join(archiveFolder, constants_1.ManifestFilename), sourceDirectories.join("\n")); const commands = yield getCommands(compressionMethod, "create"); yield execCommands(commands, archiveFolder); }); @@ -81183,7 +81183,7 @@ var require_cache4 = __commonJS({ exports2.restoreCache = restoreCache5; exports2.saveCache = saveCache5; var core30 = __importStar2(require_core()); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var utils = __importStar2(require_cacheUtils()); var cacheHttpClient = __importStar2(require_cacheHttpClient()); var cacheTwirpClient = __importStar2(require_cacheTwirpClient()); @@ -81278,7 +81278,7 @@ var require_cache4 = __commonJS({ core30.info("Lookup only - skipping download"); return cacheEntry.cacheKey; } - archivePath = path28.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + archivePath = path29.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); core30.debug(`Archive Path: ${archivePath}`); yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); if (core30.isDebug()) { @@ -81347,7 +81347,7 @@ var require_cache4 = __commonJS({ core30.info("Lookup only - skipping download"); return response.matchedKey; } - archivePath = path28.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); + archivePath = path29.join(yield utils.createTempDirectory(), utils.getCacheFileName(compressionMethod)); core30.debug(`Archive path: ${archivePath}`); core30.debug(`Starting download of archive to: ${archivePath}`); yield cacheHttpClient.downloadCache(response.signedDownloadUrl, archivePath, options); @@ -81409,7 +81409,7 @@ var require_cache4 = __commonJS({ throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); } const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path28.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + const archivePath = path29.join(archiveFolder, utils.getCacheFileName(compressionMethod)); core30.debug(`Archive Path: ${archivePath}`); try { yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); @@ -81473,7 +81473,7 @@ var require_cache4 = __commonJS({ throw new Error(`Path Validation Error: Path(s) specified in the action for caching do(es) not exist, hence no cache is being saved.`); } const archiveFolder = yield utils.createTempDirectory(); - const archivePath = path28.join(archiveFolder, utils.getCacheFileName(compressionMethod)); + const archivePath = path29.join(archiveFolder, utils.getCacheFileName(compressionMethod)); core30.debug(`Archive Path: ${archivePath}`); try { yield (0, tar_1.createTar)(archiveFolder, cachePaths, compressionMethod); @@ -81623,7 +81623,7 @@ var require_manifest = __commonJS({ var core_1 = require_core(); var os7 = require("os"); var cp = require("child_process"); - var fs30 = require("fs"); + var fs31 = require("fs"); function _findMatch(versionSpec, stable, candidates, archFilter) { return __awaiter2(this, void 0, void 0, function* () { const platFilter = os7.platform(); @@ -81685,10 +81685,10 @@ var require_manifest = __commonJS({ const lsbReleaseFile = "/etc/lsb-release"; const osReleaseFile = "/etc/os-release"; let contents = ""; - if (fs30.existsSync(lsbReleaseFile)) { - contents = fs30.readFileSync(lsbReleaseFile).toString(); - } else if (fs30.existsSync(osReleaseFile)) { - contents = fs30.readFileSync(osReleaseFile).toString(); + if (fs31.existsSync(lsbReleaseFile)) { + contents = fs31.readFileSync(lsbReleaseFile).toString(); + } else if (fs31.existsSync(osReleaseFile)) { + contents = fs31.readFileSync(osReleaseFile).toString(); } return contents; } @@ -81897,10 +81897,10 @@ var require_tool_cache = __commonJS({ var core30 = __importStar2(require_core()); var io9 = __importStar2(require_io()); var crypto3 = __importStar2(require("crypto")); - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var mm = __importStar2(require_manifest()); var os7 = __importStar2(require("os")); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var httpm = __importStar2(require_lib()); var semver11 = __importStar2(require_semver2()); var stream2 = __importStar2(require("stream")); @@ -81921,8 +81921,8 @@ var require_tool_cache = __commonJS({ var userAgent2 = "actions/tool-cache"; function downloadTool3(url2, dest, auth2, headers) { return __awaiter2(this, void 0, void 0, function* () { - dest = dest || path28.join(_getTempDirectory(), crypto3.randomUUID()); - yield io9.mkdirP(path28.dirname(dest)); + dest = dest || path29.join(_getTempDirectory(), crypto3.randomUUID()); + yield io9.mkdirP(path29.dirname(dest)); core30.debug(`Downloading ${url2}`); core30.debug(`Destination ${dest}`); const maxAttempts = 3; @@ -81943,7 +81943,7 @@ var require_tool_cache = __commonJS({ } function downloadToolAttempt(url2, dest, auth2, headers) { return __awaiter2(this, void 0, void 0, function* () { - if (fs30.existsSync(dest)) { + if (fs31.existsSync(dest)) { throw new Error(`Destination file path ${dest} already exists`); } const http = new httpm.HttpClient(userAgent2, [], { @@ -81967,7 +81967,7 @@ var require_tool_cache = __commonJS({ const readStream = responseMessageFactory(); let succeeded = false; try { - yield pipeline(readStream, fs30.createWriteStream(dest)); + yield pipeline(readStream, fs31.createWriteStream(dest)); core30.debug("download complete"); succeeded = true; return dest; @@ -82012,7 +82012,7 @@ var require_tool_cache = __commonJS({ process.chdir(originalCwd); } } else { - const escapedScript = path28.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); + const escapedScript = path29.join(__dirname, "..", "scripts", "Invoke-7zdec.ps1").replace(/'/g, "''").replace(/"|\n|\r/g, ""); const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ""); const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, ""); const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`; @@ -82179,12 +82179,12 @@ var require_tool_cache = __commonJS({ arch2 = arch2 || os7.arch(); core30.debug(`Caching tool ${tool} ${version} ${arch2}`); core30.debug(`source dir: ${sourceDir}`); - if (!fs30.statSync(sourceDir).isDirectory()) { + if (!fs31.statSync(sourceDir).isDirectory()) { throw new Error("sourceDir is not a directory"); } const destPath = yield _createToolPath(tool, version, arch2); - for (const itemName of fs30.readdirSync(sourceDir)) { - const s = path28.join(sourceDir, itemName); + for (const itemName of fs31.readdirSync(sourceDir)) { + const s = path29.join(sourceDir, itemName); yield io9.cp(s, destPath, { recursive: true }); } _completeToolPath(tool, version, arch2); @@ -82197,11 +82197,11 @@ var require_tool_cache = __commonJS({ arch2 = arch2 || os7.arch(); core30.debug(`Caching tool ${tool} ${version} ${arch2}`); core30.debug(`source file: ${sourceFile}`); - if (!fs30.statSync(sourceFile).isFile()) { + if (!fs31.statSync(sourceFile).isFile()) { throw new Error("sourceFile is not a file"); } const destFolder = yield _createToolPath(tool, version, arch2); - const destPath = path28.join(destFolder, targetFile); + const destPath = path29.join(destFolder, targetFile); core30.debug(`destination file ${destPath}`); yield io9.cp(sourceFile, destPath); _completeToolPath(tool, version, arch2); @@ -82224,9 +82224,9 @@ var require_tool_cache = __commonJS({ let toolPath = ""; if (versionSpec) { versionSpec = semver11.clean(versionSpec) || ""; - const cachePath = path28.join(_getCacheDirectory(), toolName, versionSpec, arch2); + const cachePath = path29.join(_getCacheDirectory(), toolName, versionSpec, arch2); core30.debug(`checking cache: ${cachePath}`); - if (fs30.existsSync(cachePath) && fs30.existsSync(`${cachePath}.complete`)) { + if (fs31.existsSync(cachePath) && fs31.existsSync(`${cachePath}.complete`)) { core30.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch2}`); toolPath = cachePath; } else { @@ -82238,13 +82238,13 @@ var require_tool_cache = __commonJS({ function findAllVersions2(toolName, arch2) { const versions = []; arch2 = arch2 || os7.arch(); - const toolPath = path28.join(_getCacheDirectory(), toolName); - if (fs30.existsSync(toolPath)) { - const children = fs30.readdirSync(toolPath); + const toolPath = path29.join(_getCacheDirectory(), toolName); + if (fs31.existsSync(toolPath)) { + const children = fs31.readdirSync(toolPath); for (const child of children) { if (isExplicitVersion(child)) { - const fullPath = path28.join(toolPath, child, arch2 || ""); - if (fs30.existsSync(fullPath) && fs30.existsSync(`${fullPath}.complete`)) { + const fullPath = path29.join(toolPath, child, arch2 || ""); + if (fs31.existsSync(fullPath) && fs31.existsSync(`${fullPath}.complete`)) { versions.push(child); } } @@ -82295,7 +82295,7 @@ var require_tool_cache = __commonJS({ function _createExtractFolder(dest) { return __awaiter2(this, void 0, void 0, function* () { if (!dest) { - dest = path28.join(_getTempDirectory(), crypto3.randomUUID()); + dest = path29.join(_getTempDirectory(), crypto3.randomUUID()); } yield io9.mkdirP(dest); return dest; @@ -82303,7 +82303,7 @@ var require_tool_cache = __commonJS({ } function _createToolPath(tool, version, arch2) { return __awaiter2(this, void 0, void 0, function* () { - const folderPath = path28.join(_getCacheDirectory(), tool, semver11.clean(version) || version, arch2 || ""); + const folderPath = path29.join(_getCacheDirectory(), tool, semver11.clean(version) || version, arch2 || ""); core30.debug(`destination ${folderPath}`); const markerPath = `${folderPath}.complete`; yield io9.rmRF(folderPath); @@ -82313,9 +82313,9 @@ var require_tool_cache = __commonJS({ }); } function _completeToolPath(tool, version, arch2) { - const folderPath = path28.join(_getCacheDirectory(), tool, semver11.clean(version) || version, arch2 || ""); + const folderPath = path29.join(_getCacheDirectory(), tool, semver11.clean(version) || version, arch2 || ""); const markerPath = `${folderPath}.complete`; - fs30.writeFileSync(markerPath, ""); + fs31.writeFileSync(markerPath, ""); core30.debug("finished caching tool"); } function isExplicitVersion(versionSpec) { @@ -88006,13 +88006,13 @@ These characters are not allowed in the artifact name due to limitations with ce (0, core_1.info)(`Artifact name is valid!`); } exports2.validateArtifactName = validateArtifactName; - function validateFilePath(path28) { - if (!path28) { + function validateFilePath(path29) { + if (!path29) { throw new Error(`Provided file path input during validation is empty`); } for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { - if (path28.includes(invalidCharacterKey)) { - throw new Error(`The path for one of the files in artifact is not valid: ${path28}. Contains the following character: ${errorMessageForCharacter} + if (path29.includes(invalidCharacterKey)) { + throw new Error(`The path for one of the files in artifact is not valid: ${path29}. Contains the following character: ${errorMessageForCharacter} Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} @@ -88557,15 +88557,15 @@ var require_upload_zip_specification = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getUploadZipSpecification = exports2.validateRootDirectory = void 0; - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var core_1 = require_core(); var path_1 = require("path"); var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation(); function validateRootDirectory(rootDirectory) { - if (!fs30.existsSync(rootDirectory)) { + if (!fs31.existsSync(rootDirectory)) { throw new Error(`The provided rootDirectory ${rootDirectory} does not exist`); } - if (!fs30.statSync(rootDirectory).isDirectory()) { + if (!fs31.statSync(rootDirectory).isDirectory()) { throw new Error(`The provided rootDirectory ${rootDirectory} is not a valid directory`); } (0, core_1.info)(`Root directory input is valid!`); @@ -88576,7 +88576,7 @@ var require_upload_zip_specification = __commonJS({ rootDirectory = (0, path_1.normalize)(rootDirectory); rootDirectory = (0, path_1.resolve)(rootDirectory); for (let file of filesToZip) { - const stats = fs30.lstatSync(file, { throwIfNoEntry: false }); + const stats = fs31.lstatSync(file, { throwIfNoEntry: false }); if (!stats) { throw new Error(`File ${file} does not exist`); } @@ -88915,8 +88915,8 @@ var require_minimatch2 = __commonJS({ return new Minimatch(pattern, options).match(p); }; module2.exports = minimatch; - var path28 = require_path(); - minimatch.sep = path28.sep; + var path29 = require_path(); + minimatch.sep = path29.sep; var GLOBSTAR = /* @__PURE__ */ Symbol("globstar **"); minimatch.GLOBSTAR = GLOBSTAR; var expand2 = require_brace_expansion2(); @@ -89522,8 +89522,8 @@ var require_minimatch2 = __commonJS({ if (this.empty) return f === ""; if (f === "/" && partial) return true; const options = this.options; - if (path28.sep !== "/") { - f = f.split(path28.sep).join("/"); + if (path29.sep !== "/") { + f = f.split(path29.sep).join("/"); } f = f.split(slashSplit); this.debug(this.pattern, "split", f); @@ -89561,13 +89561,13 @@ var require_minimatch2 = __commonJS({ var require_readdir_glob = __commonJS({ "node_modules/readdir-glob/index.js"(exports2, module2) { module2.exports = readdirGlob; - var fs30 = require("fs"); + var fs31 = require("fs"); var { EventEmitter } = require("events"); var { Minimatch } = require_minimatch2(); var { resolve: resolve13 } = require("path"); function readdir(dir, strict) { return new Promise((resolve14, reject) => { - fs30.readdir(dir, { withFileTypes: true }, (err, files) => { + fs31.readdir(dir, { withFileTypes: true }, (err, files) => { if (err) { switch (err.code) { case "ENOTDIR": @@ -89600,7 +89600,7 @@ var require_readdir_glob = __commonJS({ } function stat(file, followSymlinks) { return new Promise((resolve14, reject) => { - const statFunc = followSymlinks ? fs30.stat : fs30.lstat; + const statFunc = followSymlinks ? fs31.stat : fs31.lstat; statFunc(file, (err, stats) => { if (err) { switch (err.code) { @@ -89621,8 +89621,8 @@ var require_readdir_glob = __commonJS({ }); }); } - async function* exploreWalkAsync(dir, path28, followSymlinks, useStat, shouldSkip, strict) { - let files = await readdir(path28 + dir, strict); + async function* exploreWalkAsync(dir, path29, followSymlinks, useStat, shouldSkip, strict) { + let files = await readdir(path29 + dir, strict); for (const file of files) { let name = file.name; if (name === void 0) { @@ -89631,7 +89631,7 @@ var require_readdir_glob = __commonJS({ } const filename = dir + "/" + name; const relative3 = filename.slice(1); - const absolute = path28 + "/" + relative3; + const absolute = path29 + "/" + relative3; let stats = null; if (useStat || followSymlinks) { stats = await stat(absolute, followSymlinks); @@ -89645,15 +89645,15 @@ var require_readdir_glob = __commonJS({ if (stats.isDirectory()) { if (!shouldSkip(relative3)) { yield { relative: relative3, absolute, stats }; - yield* exploreWalkAsync(filename, path28, followSymlinks, useStat, shouldSkip, false); + yield* exploreWalkAsync(filename, path29, followSymlinks, useStat, shouldSkip, false); } } else { yield { relative: relative3, absolute, stats }; } } } - async function* explore(path28, followSymlinks, useStat, shouldSkip) { - yield* exploreWalkAsync("", path28, followSymlinks, useStat, shouldSkip, true); + async function* explore(path29, followSymlinks, useStat, shouldSkip) { + yield* exploreWalkAsync("", path29, followSymlinks, useStat, shouldSkip, true); } function readOptions(options) { return { @@ -91665,54 +91665,54 @@ var require_polyfills = __commonJS({ } var chdir; module2.exports = patch; - function patch(fs30) { + function patch(fs31) { if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs30); - } - if (!fs30.lutimes) { - patchLutimes(fs30); - } - fs30.chown = chownFix(fs30.chown); - fs30.fchown = chownFix(fs30.fchown); - fs30.lchown = chownFix(fs30.lchown); - fs30.chmod = chmodFix(fs30.chmod); - fs30.fchmod = chmodFix(fs30.fchmod); - fs30.lchmod = chmodFix(fs30.lchmod); - fs30.chownSync = chownFixSync(fs30.chownSync); - fs30.fchownSync = chownFixSync(fs30.fchownSync); - fs30.lchownSync = chownFixSync(fs30.lchownSync); - fs30.chmodSync = chmodFixSync(fs30.chmodSync); - fs30.fchmodSync = chmodFixSync(fs30.fchmodSync); - fs30.lchmodSync = chmodFixSync(fs30.lchmodSync); - fs30.stat = statFix(fs30.stat); - fs30.fstat = statFix(fs30.fstat); - fs30.lstat = statFix(fs30.lstat); - fs30.statSync = statFixSync(fs30.statSync); - fs30.fstatSync = statFixSync(fs30.fstatSync); - fs30.lstatSync = statFixSync(fs30.lstatSync); - if (fs30.chmod && !fs30.lchmod) { - fs30.lchmod = function(path28, mode, cb) { + patchLchmod(fs31); + } + if (!fs31.lutimes) { + patchLutimes(fs31); + } + fs31.chown = chownFix(fs31.chown); + fs31.fchown = chownFix(fs31.fchown); + fs31.lchown = chownFix(fs31.lchown); + fs31.chmod = chmodFix(fs31.chmod); + fs31.fchmod = chmodFix(fs31.fchmod); + fs31.lchmod = chmodFix(fs31.lchmod); + fs31.chownSync = chownFixSync(fs31.chownSync); + fs31.fchownSync = chownFixSync(fs31.fchownSync); + fs31.lchownSync = chownFixSync(fs31.lchownSync); + fs31.chmodSync = chmodFixSync(fs31.chmodSync); + fs31.fchmodSync = chmodFixSync(fs31.fchmodSync); + fs31.lchmodSync = chmodFixSync(fs31.lchmodSync); + fs31.stat = statFix(fs31.stat); + fs31.fstat = statFix(fs31.fstat); + fs31.lstat = statFix(fs31.lstat); + fs31.statSync = statFixSync(fs31.statSync); + fs31.fstatSync = statFixSync(fs31.fstatSync); + fs31.lstatSync = statFixSync(fs31.lstatSync); + if (fs31.chmod && !fs31.lchmod) { + fs31.lchmod = function(path29, mode, cb) { if (cb) process.nextTick(cb); }; - fs30.lchmodSync = function() { + fs31.lchmodSync = function() { }; } - if (fs30.chown && !fs30.lchown) { - fs30.lchown = function(path28, uid, gid, cb) { + if (fs31.chown && !fs31.lchown) { + fs31.lchown = function(path29, uid, gid, cb) { if (cb) process.nextTick(cb); }; - fs30.lchownSync = function() { + fs31.lchownSync = function() { }; } if (platform2 === "win32") { - fs30.rename = typeof fs30.rename !== "function" ? fs30.rename : (function(fs$rename) { + fs31.rename = typeof fs31.rename !== "function" ? fs31.rename : (function(fs$rename) { function rename(from, to, cb) { var start = Date.now(); var backoff = 0; fs$rename(from, to, function CB(er) { if (er && (er.code === "EACCES" || er.code === "EPERM") && Date.now() - start < 6e4) { setTimeout(function() { - fs30.stat(to, function(stater, st) { + fs31.stat(to, function(stater, st) { if (stater && stater.code === "ENOENT") fs$rename(from, to, CB); else @@ -91728,9 +91728,9 @@ var require_polyfills = __commonJS({ } if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename); return rename; - })(fs30.rename); + })(fs31.rename); } - fs30.read = typeof fs30.read !== "function" ? fs30.read : (function(fs$read) { + fs31.read = typeof fs31.read !== "function" ? fs31.read : (function(fs$read) { function read(fd, buffer, offset, length, position, callback_) { var callback; if (callback_ && typeof callback_ === "function") { @@ -91738,22 +91738,22 @@ var require_polyfills = __commonJS({ callback = function(er, _2, __) { if (er && er.code === "EAGAIN" && eagCounter < 10) { eagCounter++; - return fs$read.call(fs30, fd, buffer, offset, length, position, callback); + return fs$read.call(fs31, fd, buffer, offset, length, position, callback); } callback_.apply(this, arguments); }; } - return fs$read.call(fs30, fd, buffer, offset, length, position, callback); + return fs$read.call(fs31, fd, buffer, offset, length, position, callback); } if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read); return read; - })(fs30.read); - fs30.readSync = typeof fs30.readSync !== "function" ? fs30.readSync : /* @__PURE__ */ (function(fs$readSync) { + })(fs31.read); + fs31.readSync = typeof fs31.readSync !== "function" ? fs31.readSync : /* @__PURE__ */ (function(fs$readSync) { return function(fd, buffer, offset, length, position) { var eagCounter = 0; while (true) { try { - return fs$readSync.call(fs30, fd, buffer, offset, length, position); + return fs$readSync.call(fs31, fd, buffer, offset, length, position); } catch (er) { if (er.code === "EAGAIN" && eagCounter < 10) { eagCounter++; @@ -91763,11 +91763,11 @@ var require_polyfills = __commonJS({ } } }; - })(fs30.readSync); - function patchLchmod(fs31) { - fs31.lchmod = function(path28, mode, callback) { - fs31.open( - path28, + })(fs31.readSync); + function patchLchmod(fs32) { + fs32.lchmod = function(path29, mode, callback) { + fs32.open( + path29, constants.O_WRONLY | constants.O_SYMLINK, mode, function(err, fd) { @@ -91775,80 +91775,80 @@ var require_polyfills = __commonJS({ if (callback) callback(err); return; } - fs31.fchmod(fd, mode, function(err2) { - fs31.close(fd, function(err22) { + fs32.fchmod(fd, mode, function(err2) { + fs32.close(fd, function(err22) { if (callback) callback(err2 || err22); }); }); } ); }; - fs31.lchmodSync = function(path28, mode) { - var fd = fs31.openSync(path28, constants.O_WRONLY | constants.O_SYMLINK, mode); + fs32.lchmodSync = function(path29, mode) { + var fd = fs32.openSync(path29, constants.O_WRONLY | constants.O_SYMLINK, mode); var threw = true; var ret; try { - ret = fs31.fchmodSync(fd, mode); + ret = fs32.fchmodSync(fd, mode); threw = false; } finally { if (threw) { try { - fs31.closeSync(fd); + fs32.closeSync(fd); } catch (er) { } } else { - fs31.closeSync(fd); + fs32.closeSync(fd); } } return ret; }; } - function patchLutimes(fs31) { - if (constants.hasOwnProperty("O_SYMLINK") && fs31.futimes) { - fs31.lutimes = function(path28, at, mt, cb) { - fs31.open(path28, constants.O_SYMLINK, function(er, fd) { + function patchLutimes(fs32) { + if (constants.hasOwnProperty("O_SYMLINK") && fs32.futimes) { + fs32.lutimes = function(path29, at, mt, cb) { + fs32.open(path29, constants.O_SYMLINK, function(er, fd) { if (er) { if (cb) cb(er); return; } - fs31.futimes(fd, at, mt, function(er2) { - fs31.close(fd, function(er22) { + fs32.futimes(fd, at, mt, function(er2) { + fs32.close(fd, function(er22) { if (cb) cb(er2 || er22); }); }); }); }; - fs31.lutimesSync = function(path28, at, mt) { - var fd = fs31.openSync(path28, constants.O_SYMLINK); + fs32.lutimesSync = function(path29, at, mt) { + var fd = fs32.openSync(path29, constants.O_SYMLINK); var ret; var threw = true; try { - ret = fs31.futimesSync(fd, at, mt); + ret = fs32.futimesSync(fd, at, mt); threw = false; } finally { if (threw) { try { - fs31.closeSync(fd); + fs32.closeSync(fd); } catch (er) { } } else { - fs31.closeSync(fd); + fs32.closeSync(fd); } } return ret; }; - } else if (fs31.futimes) { - fs31.lutimes = function(_a, _b, _c, cb) { + } else if (fs32.futimes) { + fs32.lutimes = function(_a, _b, _c, cb) { if (cb) process.nextTick(cb); }; - fs31.lutimesSync = function() { + fs32.lutimesSync = function() { }; } } function chmodFix(orig) { if (!orig) return orig; return function(target, mode, cb) { - return orig.call(fs30, target, mode, function(er) { + return orig.call(fs31, target, mode, function(er) { if (chownErOk(er)) er = null; if (cb) cb.apply(this, arguments); }); @@ -91858,7 +91858,7 @@ var require_polyfills = __commonJS({ if (!orig) return orig; return function(target, mode) { try { - return orig.call(fs30, target, mode); + return orig.call(fs31, target, mode); } catch (er) { if (!chownErOk(er)) throw er; } @@ -91867,7 +91867,7 @@ var require_polyfills = __commonJS({ function chownFix(orig) { if (!orig) return orig; return function(target, uid, gid, cb) { - return orig.call(fs30, target, uid, gid, function(er) { + return orig.call(fs31, target, uid, gid, function(er) { if (chownErOk(er)) er = null; if (cb) cb.apply(this, arguments); }); @@ -91877,7 +91877,7 @@ var require_polyfills = __commonJS({ if (!orig) return orig; return function(target, uid, gid) { try { - return orig.call(fs30, target, uid, gid); + return orig.call(fs31, target, uid, gid); } catch (er) { if (!chownErOk(er)) throw er; } @@ -91897,13 +91897,13 @@ var require_polyfills = __commonJS({ } if (cb) cb.apply(this, arguments); } - return options ? orig.call(fs30, target, options, callback) : orig.call(fs30, target, callback); + return options ? orig.call(fs31, target, options, callback) : orig.call(fs31, target, callback); }; } function statFixSync(orig) { if (!orig) return orig; return function(target, options) { - var stats = options ? orig.call(fs30, target, options) : orig.call(fs30, target); + var stats = options ? orig.call(fs31, target, options) : orig.call(fs31, target); if (stats) { if (stats.uid < 0) stats.uid += 4294967296; if (stats.gid < 0) stats.gid += 4294967296; @@ -91932,16 +91932,16 @@ var require_legacy_streams = __commonJS({ "node_modules/graceful-fs/legacy-streams.js"(exports2, module2) { var Stream = require("stream").Stream; module2.exports = legacy; - function legacy(fs30) { + function legacy(fs31) { return { ReadStream, WriteStream }; - function ReadStream(path28, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path28, options); + function ReadStream(path29, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path29, options); Stream.call(this); var self2 = this; - this.path = path28; + this.path = path29; this.fd = null; this.readable = true; this.paused = false; @@ -91975,7 +91975,7 @@ var require_legacy_streams = __commonJS({ }); return; } - fs30.open(this.path, this.flags, this.mode, function(err, fd) { + fs31.open(this.path, this.flags, this.mode, function(err, fd) { if (err) { self2.emit("error", err); self2.readable = false; @@ -91986,10 +91986,10 @@ var require_legacy_streams = __commonJS({ self2._read(); }); } - function WriteStream(path28, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path28, options); + function WriteStream(path29, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path29, options); Stream.call(this); - this.path = path28; + this.path = path29; this.fd = null; this.writable = true; this.flags = "w"; @@ -92014,7 +92014,7 @@ var require_legacy_streams = __commonJS({ this.busy = false; this._queue = []; if (this.fd === null) { - this._open = fs30.open; + this._open = fs31.open; this._queue.push([this._open, this.path, this.flags, this.mode, void 0]); this.flush(); } @@ -92049,7 +92049,7 @@ var require_clone = __commonJS({ // node_modules/graceful-fs/graceful-fs.js var require_graceful_fs = __commonJS({ "node_modules/graceful-fs/graceful-fs.js"(exports2, module2) { - var fs30 = require("fs"); + var fs31 = require("fs"); var polyfills = require_polyfills(); var legacy = require_legacy_streams(); var clone = require_clone(); @@ -92081,12 +92081,12 @@ var require_graceful_fs = __commonJS({ m = "GFS4: " + m.split(/\n/).join("\nGFS4: "); console.error(m); }; - if (!fs30[gracefulQueue]) { + if (!fs31[gracefulQueue]) { queue = global[gracefulQueue] || []; - publishQueue(fs30, queue); - fs30.close = (function(fs$close) { + publishQueue(fs31, queue); + fs31.close = (function(fs$close) { function close(fd, cb) { - return fs$close.call(fs30, fd, function(err) { + return fs$close.call(fs31, fd, function(err) { if (!err) { resetQueue(); } @@ -92098,48 +92098,48 @@ var require_graceful_fs = __commonJS({ value: fs$close }); return close; - })(fs30.close); - fs30.closeSync = (function(fs$closeSync) { + })(fs31.close); + fs31.closeSync = (function(fs$closeSync) { function closeSync(fd) { - fs$closeSync.apply(fs30, arguments); + fs$closeSync.apply(fs31, arguments); resetQueue(); } Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync }); return closeSync; - })(fs30.closeSync); + })(fs31.closeSync); if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) { process.on("exit", function() { - debug6(fs30[gracefulQueue]); - require("assert").equal(fs30[gracefulQueue].length, 0); + debug6(fs31[gracefulQueue]); + require("assert").equal(fs31[gracefulQueue].length, 0); }); } } var queue; if (!global[gracefulQueue]) { - publishQueue(global, fs30[gracefulQueue]); - } - module2.exports = patch(clone(fs30)); - if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs30.__patched) { - module2.exports = patch(fs30); - fs30.__patched = true; - } - function patch(fs31) { - polyfills(fs31); - fs31.gracefulify = patch; - fs31.createReadStream = createReadStream3; - fs31.createWriteStream = createWriteStream3; - var fs$readFile = fs31.readFile; - fs31.readFile = readFile; - function readFile(path28, options, cb) { + publishQueue(global, fs31[gracefulQueue]); + } + module2.exports = patch(clone(fs31)); + if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs31.__patched) { + module2.exports = patch(fs31); + fs31.__patched = true; + } + function patch(fs32) { + polyfills(fs32); + fs32.gracefulify = patch; + fs32.createReadStream = createReadStream3; + fs32.createWriteStream = createWriteStream3; + var fs$readFile = fs32.readFile; + fs32.readFile = readFile; + function readFile(path29, options, cb) { if (typeof options === "function") cb = options, options = null; - return go$readFile(path28, options, cb); - function go$readFile(path29, options2, cb2, startTime) { - return fs$readFile(path29, options2, function(err) { + return go$readFile(path29, options, cb); + function go$readFile(path30, options2, cb2, startTime) { + return fs$readFile(path30, options2, function(err) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$readFile, [path29, options2, cb2], err, startTime || Date.now(), Date.now()]); + enqueue([go$readFile, [path30, options2, cb2], err, startTime || Date.now(), Date.now()]); else { if (typeof cb2 === "function") cb2.apply(this, arguments); @@ -92147,16 +92147,16 @@ var require_graceful_fs = __commonJS({ }); } } - var fs$writeFile = fs31.writeFile; - fs31.writeFile = writeFile; - function writeFile(path28, data, options, cb) { + var fs$writeFile = fs32.writeFile; + fs32.writeFile = writeFile; + function writeFile(path29, data, options, cb) { if (typeof options === "function") cb = options, options = null; - return go$writeFile(path28, data, options, cb); - function go$writeFile(path29, data2, options2, cb2, startTime) { - return fs$writeFile(path29, data2, options2, function(err) { + return go$writeFile(path29, data, options, cb); + function go$writeFile(path30, data2, options2, cb2, startTime) { + return fs$writeFile(path30, data2, options2, function(err) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$writeFile, [path29, data2, options2, cb2], err, startTime || Date.now(), Date.now()]); + enqueue([go$writeFile, [path30, data2, options2, cb2], err, startTime || Date.now(), Date.now()]); else { if (typeof cb2 === "function") cb2.apply(this, arguments); @@ -92164,17 +92164,17 @@ var require_graceful_fs = __commonJS({ }); } } - var fs$appendFile = fs31.appendFile; + var fs$appendFile = fs32.appendFile; if (fs$appendFile) - fs31.appendFile = appendFile; - function appendFile(path28, data, options, cb) { + fs32.appendFile = appendFile; + function appendFile(path29, data, options, cb) { if (typeof options === "function") cb = options, options = null; - return go$appendFile(path28, data, options, cb); - function go$appendFile(path29, data2, options2, cb2, startTime) { - return fs$appendFile(path29, data2, options2, function(err) { + return go$appendFile(path29, data, options, cb); + function go$appendFile(path30, data2, options2, cb2, startTime) { + return fs$appendFile(path30, data2, options2, function(err) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$appendFile, [path29, data2, options2, cb2], err, startTime || Date.now(), Date.now()]); + enqueue([go$appendFile, [path30, data2, options2, cb2], err, startTime || Date.now(), Date.now()]); else { if (typeof cb2 === "function") cb2.apply(this, arguments); @@ -92182,9 +92182,9 @@ var require_graceful_fs = __commonJS({ }); } } - var fs$copyFile = fs31.copyFile; + var fs$copyFile = fs32.copyFile; if (fs$copyFile) - fs31.copyFile = copyFile2; + fs32.copyFile = copyFile2; function copyFile2(src, dest, flags, cb) { if (typeof flags === "function") { cb = flags; @@ -92202,34 +92202,34 @@ var require_graceful_fs = __commonJS({ }); } } - var fs$readdir = fs31.readdir; - fs31.readdir = readdir; + var fs$readdir = fs32.readdir; + fs32.readdir = readdir; var noReaddirOptionVersions = /^v[0-5]\./; - function readdir(path28, options, cb) { + function readdir(path29, options, cb) { if (typeof options === "function") cb = options, options = null; - var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path29, options2, cb2, startTime) { - return fs$readdir(path29, fs$readdirCallback( - path29, + var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path30, options2, cb2, startTime) { + return fs$readdir(path30, fs$readdirCallback( + path30, options2, cb2, startTime )); - } : function go$readdir2(path29, options2, cb2, startTime) { - return fs$readdir(path29, options2, fs$readdirCallback( - path29, + } : function go$readdir2(path30, options2, cb2, startTime) { + return fs$readdir(path30, options2, fs$readdirCallback( + path30, options2, cb2, startTime )); }; - return go$readdir(path28, options, cb); - function fs$readdirCallback(path29, options2, cb2, startTime) { + return go$readdir(path29, options, cb); + function fs$readdirCallback(path30, options2, cb2, startTime) { return function(err, files) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) enqueue([ go$readdir, - [path29, options2, cb2], + [path30, options2, cb2], err, startTime || Date.now(), Date.now() @@ -92244,21 +92244,21 @@ var require_graceful_fs = __commonJS({ } } if (process.version.substr(0, 4) === "v0.8") { - var legStreams = legacy(fs31); + var legStreams = legacy(fs32); ReadStream = legStreams.ReadStream; WriteStream = legStreams.WriteStream; } - var fs$ReadStream = fs31.ReadStream; + var fs$ReadStream = fs32.ReadStream; if (fs$ReadStream) { ReadStream.prototype = Object.create(fs$ReadStream.prototype); ReadStream.prototype.open = ReadStream$open; } - var fs$WriteStream = fs31.WriteStream; + var fs$WriteStream = fs32.WriteStream; if (fs$WriteStream) { WriteStream.prototype = Object.create(fs$WriteStream.prototype); WriteStream.prototype.open = WriteStream$open; } - Object.defineProperty(fs31, "ReadStream", { + Object.defineProperty(fs32, "ReadStream", { get: function() { return ReadStream; }, @@ -92268,7 +92268,7 @@ var require_graceful_fs = __commonJS({ enumerable: true, configurable: true }); - Object.defineProperty(fs31, "WriteStream", { + Object.defineProperty(fs32, "WriteStream", { get: function() { return WriteStream; }, @@ -92279,7 +92279,7 @@ var require_graceful_fs = __commonJS({ configurable: true }); var FileReadStream = ReadStream; - Object.defineProperty(fs31, "FileReadStream", { + Object.defineProperty(fs32, "FileReadStream", { get: function() { return FileReadStream; }, @@ -92290,7 +92290,7 @@ var require_graceful_fs = __commonJS({ configurable: true }); var FileWriteStream = WriteStream; - Object.defineProperty(fs31, "FileWriteStream", { + Object.defineProperty(fs32, "FileWriteStream", { get: function() { return FileWriteStream; }, @@ -92300,7 +92300,7 @@ var require_graceful_fs = __commonJS({ enumerable: true, configurable: true }); - function ReadStream(path28, options) { + function ReadStream(path29, options) { if (this instanceof ReadStream) return fs$ReadStream.apply(this, arguments), this; else @@ -92320,7 +92320,7 @@ var require_graceful_fs = __commonJS({ } }); } - function WriteStream(path28, options) { + function WriteStream(path29, options) { if (this instanceof WriteStream) return fs$WriteStream.apply(this, arguments), this; else @@ -92338,22 +92338,22 @@ var require_graceful_fs = __commonJS({ } }); } - function createReadStream3(path28, options) { - return new fs31.ReadStream(path28, options); + function createReadStream3(path29, options) { + return new fs32.ReadStream(path29, options); } - function createWriteStream3(path28, options) { - return new fs31.WriteStream(path28, options); + function createWriteStream3(path29, options) { + return new fs32.WriteStream(path29, options); } - var fs$open = fs31.open; - fs31.open = open; - function open(path28, flags, mode, cb) { + var fs$open = fs32.open; + fs32.open = open; + function open(path29, flags, mode, cb) { if (typeof mode === "function") cb = mode, mode = null; - return go$open(path28, flags, mode, cb); - function go$open(path29, flags2, mode2, cb2, startTime) { - return fs$open(path29, flags2, mode2, function(err, fd) { + return go$open(path29, flags, mode, cb); + function go$open(path30, flags2, mode2, cb2, startTime) { + return fs$open(path30, flags2, mode2, function(err, fd) { if (err && (err.code === "EMFILE" || err.code === "ENFILE")) - enqueue([go$open, [path29, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]); + enqueue([go$open, [path30, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]); else { if (typeof cb2 === "function") cb2.apply(this, arguments); @@ -92361,20 +92361,20 @@ var require_graceful_fs = __commonJS({ }); } } - return fs31; + return fs32; } function enqueue(elem) { debug6("ENQUEUE", elem[0].name, elem[1]); - fs30[gracefulQueue].push(elem); + fs31[gracefulQueue].push(elem); retry2(); } var retryTimer; function resetQueue() { var now = Date.now(); - for (var i = 0; i < fs30[gracefulQueue].length; ++i) { - if (fs30[gracefulQueue][i].length > 2) { - fs30[gracefulQueue][i][3] = now; - fs30[gracefulQueue][i][4] = now; + for (var i = 0; i < fs31[gracefulQueue].length; ++i) { + if (fs31[gracefulQueue][i].length > 2) { + fs31[gracefulQueue][i][3] = now; + fs31[gracefulQueue][i][4] = now; } } retry2(); @@ -92382,9 +92382,9 @@ var require_graceful_fs = __commonJS({ function retry2() { clearTimeout(retryTimer); retryTimer = void 0; - if (fs30[gracefulQueue].length === 0) + if (fs31[gracefulQueue].length === 0) return; - var elem = fs30[gracefulQueue].shift(); + var elem = fs31[gracefulQueue].shift(); var fn = elem[0]; var args = elem[1]; var err = elem[2]; @@ -92406,7 +92406,7 @@ var require_graceful_fs = __commonJS({ debug6("RETRY", fn.name, args); fn.apply(null, args.concat([startTime])); } else { - fs30[gracefulQueue].push(elem); + fs31[gracefulQueue].push(elem); } } if (retryTimer === void 0) { @@ -92570,10 +92570,10 @@ var require_util12 = __commonJS({ return arg == null; } exports2.isNullOrUndefined = isNullOrUndefined; - function isNumber(arg) { + function isNumber2(arg) { return typeof arg === "number"; } - exports2.isNumber = isNumber; + exports2.isNumber = isNumber2; function isString3(arg) { return typeof arg === "string"; } @@ -92706,7 +92706,7 @@ var require_BufferList = __commonJS({ this.head = this.tail = null; this.length = 0; }; - BufferList.prototype.join = function join21(s) { + BufferList.prototype.join = function join22(s) { if (this.length === 0) return ""; var p = this.head; var ret = "" + p.data; @@ -92913,15 +92913,15 @@ var require_stream_writable = __commonJS({ if (typeof Symbol === "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === "function") { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { - value: function(object) { - if (realHasInstance.call(this, object)) return true; + value: function(object2) { + if (realHasInstance.call(this, object2)) return true; if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; + return object2 && object2._writableState instanceof WritableState; } }); } else { - realHasInstance = function(object) { - return object instanceof this; + realHasInstance = function(object2) { + return object2 instanceof this; }; } function Writable(options) { @@ -94454,22 +94454,22 @@ var require_lazystream = __commonJS({ // node_modules/normalize-path/index.js var require_normalize_path = __commonJS({ "node_modules/normalize-path/index.js"(exports2, module2) { - module2.exports = function(path28, stripTrailing) { - if (typeof path28 !== "string") { + module2.exports = function(path29, stripTrailing) { + if (typeof path29 !== "string") { throw new TypeError("expected path to be a string"); } - if (path28 === "\\" || path28 === "/") return "/"; - var len = path28.length; - if (len <= 1) return path28; + if (path29 === "\\" || path29 === "/") return "/"; + var len = path29.length; + if (len <= 1) return path29; var prefix = ""; - if (len > 4 && path28[3] === "\\") { - var ch = path28[2]; - if ((ch === "?" || ch === ".") && path28.slice(0, 2) === "\\\\") { - path28 = path28.slice(2); + if (len > 4 && path29[3] === "\\") { + var ch = path29[2]; + if ((ch === "?" || ch === ".") && path29.slice(0, 2) === "\\\\") { + path29 = path29.slice(2); prefix = "//"; } } - var segs = path28.split(/[/\\]+/); + var segs = path29.split(/[/\\]+/); if (stripTrailing !== false && segs[segs.length - 1] === "") { segs.pop(); } @@ -94739,8 +94739,8 @@ var require_baseIsNative = __commonJS({ // node_modules/lodash/_getValue.js var require_getValue = __commonJS({ "node_modules/lodash/_getValue.js"(exports2, module2) { - function getValue(object, key) { - return object == null ? void 0 : object[key]; + function getValue(object2, key) { + return object2 == null ? void 0 : object2[key]; } module2.exports = getValue; } @@ -94751,8 +94751,8 @@ var require_getNative = __commonJS({ "node_modules/lodash/_getNative.js"(exports2, module2) { var baseIsNative = require_baseIsNative(); var getValue = require_getValue(); - function getNative(object, key) { - var value = getValue(object, key); + function getNative(object2, key) { + var value = getValue(object2, key); return baseIsNative(value) ? value : void 0; } module2.exports = getNative; @@ -94895,13 +94895,13 @@ var require_isIterateeCall = __commonJS({ var isArrayLike = require_isArrayLike(); var isIndex = require_isIndex(); var isObject2 = require_isObject(); - function isIterateeCall(value, index, object) { - if (!isObject2(object)) { + function isIterateeCall(value, index, object2) { + if (!isObject2(object2)) { return false; } var type = typeof index; - if (type == "number" ? isArrayLike(object) && isIndex(index, object.length) : type == "string" && index in object) { - return eq(object[index], value); + if (type == "number" ? isArrayLike(object2) && isIndex(index, object2.length) : type == "string" && index in object2) { + return eq(object2[index], value); } return false; } @@ -95125,10 +95125,10 @@ var require_isPrototype = __commonJS({ // node_modules/lodash/_nativeKeysIn.js var require_nativeKeysIn = __commonJS({ "node_modules/lodash/_nativeKeysIn.js"(exports2, module2) { - function nativeKeysIn(object) { + function nativeKeysIn(object2) { var result = []; - if (object != null) { - for (var key in Object(object)) { + if (object2 != null) { + for (var key in Object(object2)) { result.push(key); } } @@ -95146,13 +95146,13 @@ var require_baseKeysIn = __commonJS({ var nativeKeysIn = require_nativeKeysIn(); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; - function baseKeysIn(object) { - if (!isObject2(object)) { - return nativeKeysIn(object); + function baseKeysIn(object2) { + if (!isObject2(object2)) { + return nativeKeysIn(object2); } - var isProto = isPrototype(object), result = []; - for (var key in object) { - if (!(key == "constructor" && (isProto || !hasOwnProperty.call(object, key)))) { + var isProto = isPrototype(object2), result = []; + for (var key in object2) { + if (!(key == "constructor" && (isProto || !hasOwnProperty.call(object2, key)))) { result.push(key); } } @@ -95168,8 +95168,8 @@ var require_keysIn = __commonJS({ var arrayLikeKeys = require_arrayLikeKeys(); var baseKeysIn = require_baseKeysIn(); var isArrayLike = require_isArrayLike(); - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + function keysIn(object2) { + return isArrayLike(object2) ? arrayLikeKeys(object2, true) : baseKeysIn(object2); } module2.exports = keysIn; } @@ -95184,8 +95184,8 @@ var require_defaults = __commonJS({ var keysIn = require_keysIn(); var objectProto = Object.prototype; var hasOwnProperty = objectProto.hasOwnProperty; - var defaults = baseRest(function(object, sources) { - object = Object(object); + var defaults = baseRest(function(object2, sources) { + object2 = Object(object2); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : void 0; @@ -95199,13 +95199,13 @@ var require_defaults = __commonJS({ var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; - var value = object[key]; - if (value === void 0 || eq(value, objectProto[key]) && !hasOwnProperty.call(object, key)) { - object[key] = source[key]; + var value = object2[key]; + if (value === void 0 || eq(value, objectProto[key]) && !hasOwnProperty.call(object2, key)) { + object2[key] = source[key]; } } } - return object; + return object2; }); module2.exports = defaults; } @@ -98983,10 +98983,10 @@ var require_writable = __commonJS({ } ObjectDefineProperty(Writable, SymbolHasInstance, { __proto__: null, - value: function(object) { - if (FunctionPrototypeSymbolHasInstance(this, object)) return true; + value: function(object2) { + if (FunctionPrototypeSymbolHasInstance(this, object2)) return true; if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; + return object2 && object2._writableState instanceof WritableState; } }); Writable.prototype.pipe = function() { @@ -101020,24 +101020,24 @@ var require_operators = __commonJS({ } }.call(this); } - function toIntegerOrInfinity(number) { - number = Number2(number); - if (NumberIsNaN(number)) { + function toIntegerOrInfinity(number2) { + number2 = Number2(number2); + if (NumberIsNaN(number2)) { return 0; } - if (number < 0) { - throw new ERR_OUT_OF_RANGE("number", ">= 0", number); + if (number2 < 0) { + throw new ERR_OUT_OF_RANGE("number", ">= 0", number2); } - return number; + return number2; } - function drop(number, options = void 0) { + function drop(number2, options = void 0) { if (options != null) { validateObject(options, "options"); } if ((options === null || options === void 0 ? void 0 : options.signal) != null) { validateAbortSignal(options.signal, "options.signal"); } - number = toIntegerOrInfinity(number); + number2 = toIntegerOrInfinity(number2); return async function* drop2() { var _options$signal5; if (options !== null && options !== void 0 && (_options$signal5 = options.signal) !== null && _options$signal5 !== void 0 && _options$signal5.aborted) { @@ -101048,20 +101048,20 @@ var require_operators = __commonJS({ if (options !== null && options !== void 0 && (_options$signal6 = options.signal) !== null && _options$signal6 !== void 0 && _options$signal6.aborted) { throw new AbortError(); } - if (number-- <= 0) { + if (number2-- <= 0) { yield val; } } }.call(this); } - function take(number, options = void 0) { + function take(number2, options = void 0) { if (options != null) { validateObject(options, "options"); } if ((options === null || options === void 0 ? void 0 : options.signal) != null) { validateAbortSignal(options.signal, "options.signal"); } - number = toIntegerOrInfinity(number); + number2 = toIntegerOrInfinity(number2); return async function* take2() { var _options$signal7; if (options !== null && options !== void 0 && (_options$signal7 = options.signal) !== null && _options$signal7 !== void 0 && _options$signal7.aborted) { @@ -101072,10 +101072,10 @@ var require_operators = __commonJS({ if (options !== null && options !== void 0 && (_options$signal8 = options.signal) !== null && _options$signal8 !== void 0 && _options$signal8.aborted) { throw new AbortError(); } - if (number-- > 0) { + if (number2-- > 0) { yield val; } - if (number <= 0) { + if (number2 <= 0) { return; } } @@ -103259,11 +103259,11 @@ var require_commonjs20 = __commonJS({ return (f) => f.length === len && f !== "." && f !== ".."; }; var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix"; - var path28 = { + var path29 = { win32: { sep: "\\" }, posix: { sep: "/" } }; - exports2.sep = defaultPlatform === "win32" ? path28.win32.sep : path28.posix.sep; + exports2.sep = defaultPlatform === "win32" ? path29.win32.sep : path29.posix.sep; exports2.minimatch.sep = exports2.sep; exports2.GLOBSTAR = /* @__PURE__ */ Symbol("globstar **"); exports2.minimatch.GLOBSTAR = exports2.GLOBSTAR; @@ -106622,12 +106622,12 @@ var require_commonjs23 = __commonJS({ /** * Get the Path object referenced by the string path, resolved from this Path */ - resolve(path28) { - if (!path28) { + resolve(path29) { + if (!path29) { return this; } - const rootPath = this.getRootString(path28); - const dir = path28.substring(rootPath.length); + const rootPath = this.getRootString(path29); + const dir = path29.substring(rootPath.length); const dirParts = dir.split(this.splitSep); const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts); return result; @@ -107380,8 +107380,8 @@ var require_commonjs23 = __commonJS({ /** * @internal */ - getRootString(path28) { - return node_path_1.win32.parse(path28).root; + getRootString(path29) { + return node_path_1.win32.parse(path29).root; } /** * @internal @@ -107428,8 +107428,8 @@ var require_commonjs23 = __commonJS({ /** * @internal */ - getRootString(path28) { - return path28.startsWith("/") ? "/" : ""; + getRootString(path29) { + return path29.startsWith("/") ? "/" : ""; } /** * @internal @@ -107479,8 +107479,8 @@ var require_commonjs23 = __commonJS({ * * @internal */ - constructor(cwd = process.cwd(), pathImpl, sep6, { nocase, childrenCacheSize = 16 * 1024, fs: fs30 = defaultFS } = {}) { - this.#fs = fsFromOption(fs30); + constructor(cwd = process.cwd(), pathImpl, sep6, { nocase, childrenCacheSize = 16 * 1024, fs: fs31 = defaultFS } = {}) { + this.#fs = fsFromOption(fs31); if (cwd instanceof URL || cwd.startsWith("file://")) { cwd = (0, node_url_1.fileURLToPath)(cwd); } @@ -107519,11 +107519,11 @@ var require_commonjs23 = __commonJS({ /** * Get the depth of a provided path, string, or the cwd */ - depth(path28 = this.cwd) { - if (typeof path28 === "string") { - path28 = this.cwd.resolve(path28); + depth(path29 = this.cwd) { + if (typeof path29 === "string") { + path29 = this.cwd.resolve(path29); } - return path28.depth(); + return path29.depth(); } /** * Return the cache of child entries. Exposed so subclasses can create @@ -108010,9 +108010,9 @@ var require_commonjs23 = __commonJS({ process2(); return results; } - chdir(path28 = this.cwd) { + chdir(path29 = this.cwd) { const oldCwd = this.cwd; - this.cwd = typeof path28 === "string" ? this.cwd.resolve(path28) : path28; + this.cwd = typeof path29 === "string" ? this.cwd.resolve(path29) : path29; this.cwd[setAsCwd](oldCwd); } }; @@ -108039,8 +108039,8 @@ var require_commonjs23 = __commonJS({ /** * @internal */ - newRoot(fs30) { - return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs30 }); + newRoot(fs31) { + return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs31 }); } /** * Return true if the provided path string is an absolute path @@ -108069,8 +108069,8 @@ var require_commonjs23 = __commonJS({ /** * @internal */ - newRoot(fs30) { - return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs30 }); + newRoot(fs31) { + return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs31 }); } /** * Return true if the provided path string is an absolute path @@ -108400,8 +108400,8 @@ var require_processor = __commonJS({ } // match, absolute, ifdir entries() { - return [...this.store.entries()].map(([path28, n]) => [ - path28, + return [...this.store.entries()].map(([path29, n]) => [ + path29, !!(n & 2), !!(n & 1) ]); @@ -108619,9 +108619,9 @@ var require_walker = __commonJS({ signal; maxDepth; includeChildMatches; - constructor(patterns, path28, opts) { + constructor(patterns, path29, opts) { this.patterns = patterns; - this.path = path28; + this.path = path29; this.opts = opts; this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/"; this.includeChildMatches = opts.includeChildMatches !== false; @@ -108640,11 +108640,11 @@ var require_walker = __commonJS({ }); } } - #ignored(path28) { - return this.seen.has(path28) || !!this.#ignore?.ignored?.(path28); + #ignored(path29) { + return this.seen.has(path29) || !!this.#ignore?.ignored?.(path29); } - #childrenIgnored(path28) { - return !!this.#ignore?.childrenIgnored?.(path28); + #childrenIgnored(path29) { + return !!this.#ignore?.childrenIgnored?.(path29); } // backpressure mechanism pause() { @@ -108860,8 +108860,8 @@ var require_walker = __commonJS({ exports2.GlobUtil = GlobUtil; var GlobWalker = class extends GlobUtil { matches = /* @__PURE__ */ new Set(); - constructor(patterns, path28, opts) { - super(patterns, path28, opts); + constructor(patterns, path29, opts) { + super(patterns, path29, opts); } matchEmit(e) { this.matches.add(e); @@ -108899,8 +108899,8 @@ var require_walker = __commonJS({ exports2.GlobWalker = GlobWalker; var GlobStream = class extends GlobUtil { results; - constructor(patterns, path28, opts) { - super(patterns, path28, opts); + constructor(patterns, path29, opts) { + super(patterns, path29, opts); this.results = new minipass_1.Minipass({ signal: this.signal, objectMode: true @@ -109255,8 +109255,8 @@ var require_commonjs24 = __commonJS({ // node_modules/archiver-utils/file.js var require_file3 = __commonJS({ "node_modules/archiver-utils/file.js"(exports2, module2) { - var fs30 = require_graceful_fs(); - var path28 = require("path"); + var fs31 = require_graceful_fs(); + var path29 = require("path"); var flatten = require_flatten(); var difference = require_difference(); var union = require_union(); @@ -109281,8 +109281,8 @@ var require_file3 = __commonJS({ return result; }; file.exists = function() { - var filepath = path28.join.apply(path28, arguments); - return fs30.existsSync(filepath); + var filepath = path29.join.apply(path29, arguments); + return fs31.existsSync(filepath); }; file.expand = function(...args) { var options = isPlainObject3(args[0]) ? args.shift() : {}; @@ -109295,12 +109295,12 @@ var require_file3 = __commonJS({ }); if (options.filter) { matches = matches.filter(function(filepath) { - filepath = path28.join(options.cwd || "", filepath); + filepath = path29.join(options.cwd || "", filepath); try { if (typeof options.filter === "function") { return options.filter(filepath); } else { - return fs30.statSync(filepath)[options.filter](); + return fs31.statSync(filepath)[options.filter](); } } catch (e) { return false; @@ -109312,7 +109312,7 @@ var require_file3 = __commonJS({ file.expandMapping = function(patterns, destBase, options) { options = Object.assign({ rename: function(destBase2, destPath) { - return path28.join(destBase2 || "", destPath); + return path29.join(destBase2 || "", destPath); } }, options); var files = []; @@ -109320,14 +109320,14 @@ var require_file3 = __commonJS({ file.expand(options, patterns).forEach(function(src) { var destPath = src; if (options.flatten) { - destPath = path28.basename(destPath); + destPath = path29.basename(destPath); } if (options.ext) { destPath = destPath.replace(/(\.[^\/]*)?$/, options.ext); } var dest = options.rename(destBase, destPath, options); if (options.cwd) { - src = path28.join(options.cwd, src); + src = path29.join(options.cwd, src); } dest = dest.replace(pathSeparatorRe, "/"); src = src.replace(pathSeparatorRe, "/"); @@ -109408,8 +109408,8 @@ var require_file3 = __commonJS({ // node_modules/archiver-utils/index.js var require_archiver_utils = __commonJS({ "node_modules/archiver-utils/index.js"(exports2, module2) { - var fs30 = require_graceful_fs(); - var path28 = require("path"); + var fs31 = require_graceful_fs(); + var path29 = require("path"); var isStream = require_is_stream(); var lazystream = require_lazystream(); var normalizePath = require_normalize_path(); @@ -109447,7 +109447,7 @@ var require_archiver_utils = __commonJS({ } return dateish; }; - utils.defaults = function(object, source, guard) { + utils.defaults = function(object2, source, guard) { var args = arguments; args[0] = args[0] || {}; return defaults(...args); @@ -109457,7 +109457,7 @@ var require_archiver_utils = __commonJS({ }; utils.lazyReadStream = function(filepath) { return new lazystream.Readable(function() { - return fs30.createReadStream(filepath); + return fs31.createReadStream(filepath); }); }; utils.normalizeInputSource = function(source) { @@ -109485,7 +109485,7 @@ var require_archiver_utils = __commonJS({ callback = base; base = dirpath; } - fs30.readdir(dirpath, function(err, list) { + fs31.readdir(dirpath, function(err, list) { var i = 0; var file; var filepath; @@ -109497,11 +109497,11 @@ var require_archiver_utils = __commonJS({ if (!file) { return callback(null, results); } - filepath = path28.join(dirpath, file); - fs30.stat(filepath, function(err2, stats) { + filepath = path29.join(dirpath, file); + fs31.stat(filepath, function(err2, stats) { results.push({ path: filepath, - relative: path28.relative(base, filepath).replace(/\\/g, "/"), + relative: path29.relative(base, filepath).replace(/\\/g, "/"), stats }); if (stats && stats.isDirectory()) { @@ -109560,10 +109560,10 @@ var require_error3 = __commonJS({ // node_modules/archiver/lib/core.js var require_core3 = __commonJS({ "node_modules/archiver/lib/core.js"(exports2, module2) { - var fs30 = require("fs"); + var fs31 = require("fs"); var glob2 = require_readdir_glob(); var async = require_async(); - var path28 = require("path"); + var path29 = require("path"); var util = require_archiver_utils(); var inherits = require("util").inherits; var ArchiverError = require_error3(); @@ -109624,7 +109624,7 @@ var require_core3 = __commonJS({ data.sourcePath = filepath; task.data = data; this._entriesCount++; - if (data.stats && data.stats instanceof fs30.Stats) { + if (data.stats && data.stats instanceof fs31.Stats) { task = this._updateQueueTaskWithStats(task, data.stats); if (task) { if (data.stats.size) { @@ -109795,7 +109795,7 @@ var require_core3 = __commonJS({ callback(); return; } - fs30.lstat(task.filepath, function(err, stats) { + fs31.lstat(task.filepath, function(err, stats) { if (this._state.aborted) { setImmediate(callback); return; @@ -109838,10 +109838,10 @@ var require_core3 = __commonJS({ task.data.sourceType = "buffer"; task.source = Buffer.concat([]); } else if (stats.isSymbolicLink() && this._moduleSupports("symlink")) { - var linkPath = fs30.readlinkSync(task.filepath); - var dirName = path28.dirname(task.filepath); + var linkPath = fs31.readlinkSync(task.filepath); + var dirName = path29.dirname(task.filepath); task.data.type = "symlink"; - task.data.linkname = path28.relative(dirName, path28.resolve(dirName, linkPath)); + task.data.linkname = path29.relative(dirName, path29.resolve(dirName, linkPath)); task.data.sourceType = "buffer"; task.source = Buffer.concat([]); } else { @@ -114291,8 +114291,8 @@ var require_context2 = __commonJS({ if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: "utf8" })); } else { - const path28 = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path28} does not exist${os_1.EOL}`); + const path29 = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path29} does not exist${os_1.EOL}`); } } this.eventName = process.env.GITHUB_EVENT_NAME; @@ -115329,12 +115329,12 @@ var require_dist_node2 = __commonJS({ format: "" } }; - function lowercaseKeys2(object) { - if (!object) { + function lowercaseKeys2(object2) { + if (!object2) { return {}; } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; + return Object.keys(object2).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object2[key]; return newObj; }, {}); } @@ -115416,11 +115416,11 @@ var require_dist_node2 = __commonJS({ } return matches.map(removeNonChars2).reduce((a, b) => a.concat(b), []); } - function omit2(object, keysToOmit) { + function omit2(object2, keysToOmit) { const result = { __proto__: null }; - for (const key of Object.keys(object)) { + for (const key of Object.keys(object2)) { if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; + result[key] = object2[key]; } } return result; @@ -119188,7 +119188,7 @@ var require_traverse = __commonJS({ })(this.value); }; function walk(root, cb, immutable) { - var path28 = []; + var path29 = []; var parents = []; var alive = true; return (function walker(node_) { @@ -119197,11 +119197,11 @@ var require_traverse = __commonJS({ var state = { node, node_, - path: [].concat(path28), + path: [].concat(path29), parent: parents.slice(-1)[0], - key: path28.slice(-1)[0], - isRoot: path28.length === 0, - level: path28.length, + key: path29.slice(-1)[0], + isRoot: path29.length === 0, + level: path29.length, circular: null, update: function(x) { if (!state.isRoot) { @@ -119256,7 +119256,7 @@ var require_traverse = __commonJS({ parents.push(state); var keys = Object.keys(state.node); keys.forEach(function(key, i2) { - path28.push(key); + path29.push(key); if (modifiers.pre) modifiers.pre.call(state, state.node[key], key); var child = walker(state.node[key]); if (immutable && Object.hasOwnProperty.call(state.node, key)) { @@ -119265,7 +119265,7 @@ var require_traverse = __commonJS({ child.isLast = i2 == keys.length - 1; child.isFirst = i2 == 0; if (modifiers.post) modifiers.post.call(state, child); - path28.pop(); + path29.pop(); }); parents.pop(); } @@ -120286,11 +120286,11 @@ var require_unzip_stream = __commonJS({ return requiredLength; case states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX: var isUtf8 = (this.parsedEntity.flags & 2048) !== 0; - var path28 = this._decodeString(chunk.slice(0, this.parsedEntity.fileNameLength), isUtf8); + var path29 = this._decodeString(chunk.slice(0, this.parsedEntity.fileNameLength), isUtf8); var extraDataBuffer = chunk.slice(this.parsedEntity.fileNameLength, this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength); var extra = this._readExtraFields(extraDataBuffer); if (extra && extra.parsed && extra.parsed.path && !isUtf8) { - path28 = extra.parsed.path; + path29 = extra.parsed.path; } this.parsedEntity.extra = extra.parsed; var isUnix = (this.parsedEntity.versionMadeBy & 65280) >> 8 === 3; @@ -120302,7 +120302,7 @@ var require_unzip_stream = __commonJS({ } if (this.options.debug) { const debugObj = Object.assign({}, this.parsedEntity, { - path: path28, + path: path29, flags: "0x" + this.parsedEntity.flags.toString(16), unixAttrs: unixAttrs && "0" + unixAttrs.toString(8), isSymlink, @@ -120739,8 +120739,8 @@ var require_parser_stream = __commonJS({ // node_modules/mkdirp/index.js var require_mkdirp = __commonJS({ "node_modules/mkdirp/index.js"(exports2, module2) { - var path28 = require("path"); - var fs30 = require("fs"); + var path29 = require("path"); + var fs31 = require("fs"); var _0777 = parseInt("0777", 8); module2.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; function mkdirP(p, opts, f, made) { @@ -120751,7 +120751,7 @@ var require_mkdirp = __commonJS({ opts = { mode: opts }; } var mode = opts.mode; - var xfs = opts.fs || fs30; + var xfs = opts.fs || fs31; if (mode === void 0) { mode = _0777; } @@ -120759,7 +120759,7 @@ var require_mkdirp = __commonJS({ var cb = f || /* istanbul ignore next */ function() { }; - p = path28.resolve(p); + p = path29.resolve(p); xfs.mkdir(p, mode, function(er) { if (!er) { made = made || p; @@ -120767,8 +120767,8 @@ var require_mkdirp = __commonJS({ } switch (er.code) { case "ENOENT": - if (path28.dirname(p) === p) return cb(er); - mkdirP(path28.dirname(p), opts, function(er2, made2) { + if (path29.dirname(p) === p) return cb(er); + mkdirP(path29.dirname(p), opts, function(er2, made2) { if (er2) cb(er2, made2); else mkdirP(p, opts, cb, made2); }); @@ -120790,19 +120790,19 @@ var require_mkdirp = __commonJS({ opts = { mode: opts }; } var mode = opts.mode; - var xfs = opts.fs || fs30; + var xfs = opts.fs || fs31; if (mode === void 0) { mode = _0777; } if (!made) made = null; - p = path28.resolve(p); + p = path29.resolve(p); try { xfs.mkdirSync(p, mode); made = made || p; } catch (err0) { switch (err0.code) { case "ENOENT": - made = sync(path28.dirname(p), opts, made); + made = sync(path29.dirname(p), opts, made); sync(p, opts, made); break; // In the case of any other error, just see if there's a dir @@ -120827,8 +120827,8 @@ var require_mkdirp = __commonJS({ // node_modules/unzip-stream/lib/extract.js var require_extract2 = __commonJS({ "node_modules/unzip-stream/lib/extract.js"(exports2, module2) { - var fs30 = require("fs"); - var path28 = require("path"); + var fs31 = require("fs"); + var path29 = require("path"); var util = require("util"); var mkdirp = require_mkdirp(); var Transform = require("stream").Transform; @@ -120870,11 +120870,11 @@ var require_extract2 = __commonJS({ }; Extract.prototype._processEntry = function(entry) { var self2 = this; - var destPath = path28.join(this.opts.path, entry.path); - var directory = entry.isDirectory ? destPath : path28.dirname(destPath); + var destPath = path29.join(this.opts.path, entry.path); + var directory = entry.isDirectory ? destPath : path29.dirname(destPath); this.unfinishedEntries++; var writeFileFn = function() { - var pipedStream = fs30.createWriteStream(destPath); + var pipedStream = fs31.createWriteStream(destPath); pipedStream.on("close", function() { self2.unfinishedEntries--; self2._notifyAwaiter(); @@ -120998,10 +120998,10 @@ var require_download_artifact = __commonJS({ parsed.search = ""; return parsed.toString(); }; - function exists(path28) { + function exists(path29) { return __awaiter2(this, void 0, void 0, function* () { try { - yield promises_1.default.access(path28); + yield promises_1.default.access(path29); return true; } catch (error3) { if (error3.code === "ENOENT") { @@ -121233,12 +121233,12 @@ var require_dist_node11 = __commonJS({ octokit.log.debug("request", options); const start = Date.now(); const requestOptions = octokit.request.endpoint.parse(options); - const path28 = requestOptions.url.replace(options.baseUrl, ""); + const path29 = requestOptions.url.replace(options.baseUrl, ""); return request3(options).then((response) => { - octokit.log.info(`${requestOptions.method} ${path28} - ${response.status} in ${Date.now() - start}ms`); + octokit.log.info(`${requestOptions.method} ${path29} - ${response.status} in ${Date.now() - start}ms`); return response; }).catch((error3) => { - octokit.log.info(`${requestOptions.method} ${path28} - ${error3.status} in ${Date.now() - start}ms`); + octokit.log.info(`${requestOptions.method} ${path29} - ${error3.status} in ${Date.now() - start}ms`); throw error3; }); }); @@ -122072,7 +122072,7 @@ var require_file_command2 = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.prepareKeyValueMessage = exports2.issueFileCommand = void 0; var crypto3 = __importStar2(require("crypto")); - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var os7 = __importStar2(require("os")); var utils_1 = require_utils10(); function issueFileCommand(command, message) { @@ -122080,10 +122080,10 @@ var require_file_command2 = __commonJS({ if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } - if (!fs30.existsSync(filePath)) { + if (!fs31.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs30.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os7.EOL}`, { + fs31.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os7.EOL}`, { encoding: "utf8" }); } @@ -123333,7 +123333,7 @@ var require_path_utils2 = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.toPlatformPath = exports2.toWin32Path = exports2.toPosixPath = void 0; - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); function toPosixPath(pth) { return pth.replace(/[\\]/g, "/"); } @@ -123343,7 +123343,7 @@ var require_path_utils2 = __commonJS({ } exports2.toWin32Path = toWin32Path; function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path28.sep); + return pth.replace(/[/\\]/g, path29.sep); } exports2.toPlatformPath = toPlatformPath; } @@ -123406,12 +123406,12 @@ var require_io_util2 = __commonJS({ var _a; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getCmdPath = exports2.tryGetExecutablePath = exports2.isRooted = exports2.isDirectory = exports2.exists = exports2.READONLY = exports2.UV_FS_O_EXLOCK = exports2.IS_WINDOWS = exports2.unlink = exports2.symlink = exports2.stat = exports2.rmdir = exports2.rm = exports2.rename = exports2.readlink = exports2.readdir = exports2.open = exports2.mkdir = exports2.lstat = exports2.copyFile = exports2.chmod = void 0; - var fs30 = __importStar2(require("fs")); - var path28 = __importStar2(require("path")); - _a = fs30.promises, exports2.chmod = _a.chmod, exports2.copyFile = _a.copyFile, exports2.lstat = _a.lstat, exports2.mkdir = _a.mkdir, exports2.open = _a.open, exports2.readdir = _a.readdir, exports2.readlink = _a.readlink, exports2.rename = _a.rename, exports2.rm = _a.rm, exports2.rmdir = _a.rmdir, exports2.stat = _a.stat, exports2.symlink = _a.symlink, exports2.unlink = _a.unlink; + var fs31 = __importStar2(require("fs")); + var path29 = __importStar2(require("path")); + _a = fs31.promises, exports2.chmod = _a.chmod, exports2.copyFile = _a.copyFile, exports2.lstat = _a.lstat, exports2.mkdir = _a.mkdir, exports2.open = _a.open, exports2.readdir = _a.readdir, exports2.readlink = _a.readlink, exports2.rename = _a.rename, exports2.rm = _a.rm, exports2.rmdir = _a.rmdir, exports2.stat = _a.stat, exports2.symlink = _a.symlink, exports2.unlink = _a.unlink; exports2.IS_WINDOWS = process.platform === "win32"; exports2.UV_FS_O_EXLOCK = 268435456; - exports2.READONLY = fs30.constants.O_RDONLY; + exports2.READONLY = fs31.constants.O_RDONLY; function exists(fsPath) { return __awaiter2(this, void 0, void 0, function* () { try { @@ -123456,7 +123456,7 @@ var require_io_util2 = __commonJS({ } if (stats && stats.isFile()) { if (exports2.IS_WINDOWS) { - const upperExt = path28.extname(filePath).toUpperCase(); + const upperExt = path29.extname(filePath).toUpperCase(); if (extensions.some((validExt) => validExt.toUpperCase() === upperExt)) { return filePath; } @@ -123480,11 +123480,11 @@ var require_io_util2 = __commonJS({ if (stats && stats.isFile()) { if (exports2.IS_WINDOWS) { try { - const directory = path28.dirname(filePath); - const upperName = path28.basename(filePath).toUpperCase(); + const directory = path29.dirname(filePath); + const upperName = path29.basename(filePath).toUpperCase(); for (const actualName of yield exports2.readdir(directory)) { if (upperName === actualName.toUpperCase()) { - filePath = path28.join(directory, actualName); + filePath = path29.join(directory, actualName); break; } } @@ -123579,7 +123579,7 @@ var require_io2 = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.findInPath = exports2.which = exports2.mkdirP = exports2.rmRF = exports2.mv = exports2.cp = void 0; var assert_1 = require("assert"); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var ioUtil = __importStar2(require_io_util2()); function cp(source, dest, options = {}) { return __awaiter2(this, void 0, void 0, function* () { @@ -123588,7 +123588,7 @@ var require_io2 = __commonJS({ if (destStat && destStat.isFile() && !force) { return; } - const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path28.join(dest, path28.basename(source)) : dest; + const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path29.join(dest, path29.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } @@ -123600,7 +123600,7 @@ var require_io2 = __commonJS({ yield cpDirRecursive(source, newDest, 0, force); } } else { - if (path28.relative(source, newDest) === "") { + if (path29.relative(source, newDest) === "") { throw new Error(`'${newDest}' and '${source}' are the same file`); } yield copyFile2(source, newDest, force); @@ -123613,7 +123613,7 @@ var require_io2 = __commonJS({ if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { - dest = path28.join(dest, path28.basename(source)); + dest = path29.join(dest, path29.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { @@ -123624,7 +123624,7 @@ var require_io2 = __commonJS({ } } } - yield mkdirP(path28.dirname(dest)); + yield mkdirP(path29.dirname(dest)); yield ioUtil.rename(source, dest); }); } @@ -123687,7 +123687,7 @@ var require_io2 = __commonJS({ } const extensions = []; if (ioUtil.IS_WINDOWS && process.env["PATHEXT"]) { - for (const extension of process.env["PATHEXT"].split(path28.delimiter)) { + for (const extension of process.env["PATHEXT"].split(path29.delimiter)) { if (extension) { extensions.push(extension); } @@ -123700,12 +123700,12 @@ var require_io2 = __commonJS({ } return []; } - if (tool.includes(path28.sep)) { + if (tool.includes(path29.sep)) { return []; } const directories = []; if (process.env.PATH) { - for (const p of process.env.PATH.split(path28.delimiter)) { + for (const p of process.env.PATH.split(path29.delimiter)) { if (p) { directories.push(p); } @@ -123713,7 +123713,7 @@ var require_io2 = __commonJS({ } const matches = []; for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path28.join(directory, tool), extensions); + const filePath = yield ioUtil.tryGetExecutablePath(path29.join(directory, tool), extensions); if (filePath) { matches.push(filePath); } @@ -123829,7 +123829,7 @@ var require_toolrunner2 = __commonJS({ var os7 = __importStar2(require("os")); var events = __importStar2(require("events")); var child = __importStar2(require("child_process")); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var io9 = __importStar2(require_io2()); var ioUtil = __importStar2(require_io_util2()); var timers_1 = require("timers"); @@ -124044,7 +124044,7 @@ var require_toolrunner2 = __commonJS({ exec() { return __awaiter2(this, void 0, void 0, function* () { if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes("/") || IS_WINDOWS && this.toolPath.includes("\\"))) { - this.toolPath = path28.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + this.toolPath = path29.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } this.toolPath = yield io9.which(this.toolPath, true); return new Promise((resolve13, reject) => __awaiter2(this, void 0, void 0, function* () { @@ -124544,7 +124544,7 @@ var require_core4 = __commonJS({ var file_command_1 = require_file_command2(); var utils_1 = require_utils10(); var os7 = __importStar2(require("os")); - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); var oidc_utils_1 = require_oidc_utils2(); var ExitCode; (function(ExitCode2) { @@ -124572,7 +124572,7 @@ var require_core4 = __commonJS({ } else { (0, command_1.issueCommand)("add-path", {}, inputPath); } - process.env["PATH"] = `${inputPath}${path28.delimiter}${process.env["PATH"]}`; + process.env["PATH"] = `${inputPath}${path29.delimiter}${process.env["PATH"]}`; } exports2.addPath = addPath2; function getInput2(name, options) { @@ -124748,13 +124748,13 @@ These characters are not allowed in the artifact name due to limitations with ce (0, core_1.info)(`Artifact name is valid!`); } exports2.checkArtifactName = checkArtifactName; - function checkArtifactFilePath(path28) { - if (!path28) { - throw new Error(`Artifact path: ${path28}, is incorrectly provided`); + function checkArtifactFilePath(path29) { + if (!path29) { + throw new Error(`Artifact path: ${path29}, is incorrectly provided`); } for (const [invalidCharacterKey, errorMessageForCharacter] of invalidArtifactFilePathCharacters) { - if (path28.includes(invalidCharacterKey)) { - throw new Error(`Artifact path is not valid: ${path28}. Contains the following character: ${errorMessageForCharacter} + if (path29.includes(invalidCharacterKey)) { + throw new Error(`Artifact path is not valid: ${path29}. Contains the following character: ${errorMessageForCharacter} Invalid characters include: ${Array.from(invalidArtifactFilePathCharacters.values()).toString()} @@ -124800,25 +124800,25 @@ var require_upload_specification = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getUploadSpecification = void 0; - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var core_1 = require_core4(); var path_1 = require("path"); var path_and_artifact_name_validation_1 = require_path_and_artifact_name_validation2(); function getUploadSpecification(artifactName, rootDirectory, artifactFiles) { const specifications = []; - if (!fs30.existsSync(rootDirectory)) { + if (!fs31.existsSync(rootDirectory)) { throw new Error(`Provided rootDirectory ${rootDirectory} does not exist`); } - if (!fs30.statSync(rootDirectory).isDirectory()) { + if (!fs31.statSync(rootDirectory).isDirectory()) { throw new Error(`Provided rootDirectory ${rootDirectory} is not a valid directory`); } rootDirectory = (0, path_1.normalize)(rootDirectory); rootDirectory = (0, path_1.resolve)(rootDirectory); for (let file of artifactFiles) { - if (!fs30.existsSync(file)) { + if (!fs31.existsSync(file)) { throw new Error(`File ${file} does not exist`); } - if (!fs30.statSync(file).isDirectory()) { + if (!fs31.statSync(file).isDirectory()) { file = (0, path_1.normalize)(file); file = (0, path_1.resolve)(file); if (!file.startsWith(rootDirectory)) { @@ -124843,11 +124843,11 @@ var require_upload_specification = __commonJS({ // node_modules/tmp/lib/tmp.js var require_tmp = __commonJS({ "node_modules/tmp/lib/tmp.js"(exports2, module2) { - var fs30 = require("fs"); + var fs31 = require("fs"); var os7 = require("os"); - var path28 = require("path"); + var path29 = require("path"); var crypto3 = require("crypto"); - var _c = { fs: fs30.constants, os: os7.constants }; + var _c = { fs: fs31.constants, os: os7.constants }; var RANDOM_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; var TEMPLATE_PATTERN = /XXXXXX/; var DEFAULT_TRIES = 3; @@ -124859,13 +124859,13 @@ var require_tmp = __commonJS({ var FILE_MODE = 384; var EXIT = "exit"; var _removeObjects = []; - var FN_RMDIR_SYNC = fs30.rmdirSync.bind(fs30); + var FN_RMDIR_SYNC = fs31.rmdirSync.bind(fs31); var _gracefulCleanup = false; function rimraf(dirPath, callback) { - return fs30.rm(dirPath, { recursive: true }, callback); + return fs31.rm(dirPath, { recursive: true }, callback); } function FN_RIMRAF_SYNC(dirPath) { - return fs30.rmSync(dirPath, { recursive: true }); + return fs31.rmSync(dirPath, { recursive: true }); } function tmpName(options, callback) { const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; @@ -124875,7 +124875,7 @@ var require_tmp = __commonJS({ (function _getUniqueName() { try { const name = _generateTmpName(sanitizedOptions); - fs30.stat(name, function(err2) { + fs31.stat(name, function(err2) { if (!err2) { if (tries-- > 0) return _getUniqueName(); return cb(new Error("Could not get a unique tmp filename, max tries reached " + name)); @@ -124895,7 +124895,7 @@ var require_tmp = __commonJS({ do { const name = _generateTmpName(sanitizedOptions); try { - fs30.statSync(name); + fs31.statSync(name); } catch (e) { return name; } @@ -124906,10 +124906,10 @@ var require_tmp = __commonJS({ const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; tmpName(opts, function _tmpNameCreated(err, name) { if (err) return cb(err); - fs30.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) { + fs31.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err2, fd) { if (err2) return cb(err2); if (opts.discardDescriptor) { - return fs30.close(fd, function _discardCallback(possibleErr) { + return fs31.close(fd, function _discardCallback(possibleErr) { return cb(possibleErr, name, void 0, _prepareTmpFileRemoveCallback(name, -1, opts, false)); }); } else { @@ -124923,9 +124923,9 @@ var require_tmp = __commonJS({ const args = _parseArguments(options), opts = args[0]; const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor; const name = tmpNameSync(opts); - let fd = fs30.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); + let fd = fs31.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE); if (opts.discardDescriptor) { - fs30.closeSync(fd); + fs31.closeSync(fd); fd = void 0; } return { @@ -124938,7 +124938,7 @@ var require_tmp = __commonJS({ const args = _parseArguments(options, callback), opts = args[0], cb = args[1]; tmpName(opts, function _tmpNameCreated(err, name) { if (err) return cb(err); - fs30.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) { + fs31.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err2) { if (err2) return cb(err2); cb(null, name, _prepareTmpDirRemoveCallback(name, opts, false)); }); @@ -124947,7 +124947,7 @@ var require_tmp = __commonJS({ function dirSync(options) { const args = _parseArguments(options), opts = args[0]; const name = tmpNameSync(opts); - fs30.mkdirSync(name, opts.mode || DIR_MODE); + fs31.mkdirSync(name, opts.mode || DIR_MODE); return { name, removeCallback: _prepareTmpDirRemoveCallback(name, opts, true) @@ -124961,20 +124961,20 @@ var require_tmp = __commonJS({ next(); }; if (0 <= fdPath[0]) - fs30.close(fdPath[0], function() { - fs30.unlink(fdPath[1], _handler); + fs31.close(fdPath[0], function() { + fs31.unlink(fdPath[1], _handler); }); - else fs30.unlink(fdPath[1], _handler); + else fs31.unlink(fdPath[1], _handler); } function _removeFileSync(fdPath) { let rethrownException = null; try { - if (0 <= fdPath[0]) fs30.closeSync(fdPath[0]); + if (0 <= fdPath[0]) fs31.closeSync(fdPath[0]); } catch (e) { if (!_isEBADF(e) && !_isENOENT(e)) throw e; } finally { try { - fs30.unlinkSync(fdPath[1]); + fs31.unlinkSync(fdPath[1]); } catch (e) { if (!_isENOENT(e)) rethrownException = e; } @@ -124990,7 +124990,7 @@ var require_tmp = __commonJS({ return sync ? removeCallbackSync : removeCallback; } function _prepareTmpDirRemoveCallback(name, opts, sync) { - const removeFunction = opts.unsafeCleanup ? rimraf : fs30.rmdir.bind(fs30); + const removeFunction = opts.unsafeCleanup ? rimraf : fs31.rmdir.bind(fs31); const removeFunctionSync = opts.unsafeCleanup ? FN_RIMRAF_SYNC : FN_RMDIR_SYNC; const removeCallbackSync = _prepareRemoveCallback(removeFunctionSync, name, sync); const removeCallback = _prepareRemoveCallback(removeFunction, name, sync, removeCallbackSync); @@ -125052,35 +125052,35 @@ var require_tmp = __commonJS({ return [actualOptions, callback]; } function _resolvePath(name, tmpDir, cb) { - const pathToResolve = path28.isAbsolute(name) ? name : path28.join(tmpDir, name); - fs30.stat(pathToResolve, function(err) { + const pathToResolve = path29.isAbsolute(name) ? name : path29.join(tmpDir, name); + fs31.stat(pathToResolve, function(err) { if (err) { - fs30.realpath(path28.dirname(pathToResolve), function(err2, parentDir) { + fs31.realpath(path29.dirname(pathToResolve), function(err2, parentDir) { if (err2) return cb(err2); - cb(null, path28.join(parentDir, path28.basename(pathToResolve))); + cb(null, path29.join(parentDir, path29.basename(pathToResolve))); }); } else { - fs30.realpath(pathToResolve, cb); + fs31.realpath(pathToResolve, cb); } }); } function _resolvePathSync(name, tmpDir) { - const pathToResolve = path28.isAbsolute(name) ? name : path28.join(tmpDir, name); + const pathToResolve = path29.isAbsolute(name) ? name : path29.join(tmpDir, name); try { - fs30.statSync(pathToResolve); - return fs30.realpathSync(pathToResolve); + fs31.statSync(pathToResolve); + return fs31.realpathSync(pathToResolve); } catch (_err) { - const parentDir = fs30.realpathSync(path28.dirname(pathToResolve)); - return path28.join(parentDir, path28.basename(pathToResolve)); + const parentDir = fs31.realpathSync(path29.dirname(pathToResolve)); + return path29.join(parentDir, path29.basename(pathToResolve)); } } function _generateTmpName(opts) { const tmpDir = opts.tmpdir; if (!_isUndefined(opts.name)) { - return path28.join(tmpDir, opts.dir, opts.name); + return path29.join(tmpDir, opts.dir, opts.name); } if (!_isUndefined(opts.template)) { - return path28.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); + return path29.join(tmpDir, opts.dir, opts.template).replace(TEMPLATE_PATTERN, _randomChars(6)); } const name = [ opts.prefix ? opts.prefix : "tmp", @@ -125090,7 +125090,7 @@ var require_tmp = __commonJS({ _randomChars(12), opts.postfix ? "-" + opts.postfix : "" ].join(""); - return path28.join(tmpDir, opts.dir, name); + return path29.join(tmpDir, opts.dir, name); } function _assertPath(option, value) { if (typeof value !== "string") { @@ -125104,8 +125104,8 @@ var require_tmp = __commonJS({ function _assertOptionsBase(options) { if (!_isUndefined(options.name)) { const name = options.name; - if (path28.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`); - const basename2 = path28.basename(name); + if (path29.isAbsolute(name)) throw new Error(`name option must not contain an absolute path, found "${name}".`); + const basename2 = path29.basename(name); if (basename2 === ".." || basename2 === "." || basename2 !== name) { throw new Error(`name option must not contain a path, found "${name}".`); } @@ -125134,8 +125134,8 @@ var require_tmp = __commonJS({ if (_isUndefined(name)) return cb(null); _resolvePath(name, tmpDir, function(err, resolvedPath) { if (err) return cb(err); - const relativePath = path28.relative(tmpDir, resolvedPath); - if (relativePath.startsWith("..") || path28.isAbsolute(relativePath)) { + const relativePath = path29.relative(tmpDir, resolvedPath); + if (relativePath.startsWith("..") || path29.isAbsolute(relativePath)) { return cb(new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`)); } cb(null, relativePath); @@ -125144,8 +125144,8 @@ var require_tmp = __commonJS({ function _getRelativePathSync(option, name, tmpDir) { if (_isUndefined(name)) return; const resolvedPath = _resolvePathSync(name, tmpDir); - const relativePath = path28.relative(tmpDir, resolvedPath); - if (relativePath.startsWith("..") || path28.isAbsolute(relativePath)) { + const relativePath = path29.relative(tmpDir, resolvedPath); + if (relativePath.startsWith("..") || path29.isAbsolute(relativePath)) { throw new Error(`${option} option must be relative to "${tmpDir}", found "${relativePath}".`); } return relativePath; @@ -125191,10 +125191,10 @@ var require_tmp = __commonJS({ _gracefulCleanup = true; } function _getTmpDir(options, cb) { - return fs30.realpath(options && options.tmpdir || os7.tmpdir(), cb); + return fs31.realpath(options && options.tmpdir || os7.tmpdir(), cb); } function _getTmpDirSync(options) { - return fs30.realpathSync(options && options.tmpdir || os7.tmpdir()); + return fs31.realpathSync(options && options.tmpdir || os7.tmpdir()); } process.addListener(EXIT, _garbageCollector); Object.defineProperty(module2.exports, "tmpdir", { @@ -125224,14 +125224,14 @@ var require_tmp_promise = __commonJS({ var fileWithOptions = promisify( (options, cb) => tmp.file( options, - (err, path28, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path28, fd, cleanup: promisify(cleanup) }) + (err, path29, fd, cleanup) => err ? cb(err) : cb(void 0, { path: path29, fd, cleanup: promisify(cleanup) }) ) ); module2.exports.file = async (options) => fileWithOptions(options); module2.exports.withFile = async function withFile(fn, options) { - const { path: path28, fd, cleanup } = await module2.exports.file(options); + const { path: path29, fd, cleanup } = await module2.exports.file(options); try { - return await fn({ path: path28, fd }); + return await fn({ path: path29, fd }); } finally { await cleanup(); } @@ -125240,14 +125240,14 @@ var require_tmp_promise = __commonJS({ var dirWithOptions = promisify( (options, cb) => tmp.dir( options, - (err, path28, cleanup) => err ? cb(err) : cb(void 0, { path: path28, cleanup: promisify(cleanup) }) + (err, path29, cleanup) => err ? cb(err) : cb(void 0, { path: path29, cleanup: promisify(cleanup) }) ) ); module2.exports.dir = async (options) => dirWithOptions(options); module2.exports.withDir = async function withDir(fn, options) { - const { path: path28, cleanup } = await module2.exports.dir(options); + const { path: path29, cleanup } = await module2.exports.dir(options); try { - return await fn({ path: path28 }); + return await fn({ path: path29 }); } finally { await cleanup(); } @@ -126048,10 +126048,10 @@ var require_upload_gzip = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.createGZipFileInBuffer = exports2.createGZipFileOnDisk = void 0; - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var zlib3 = __importStar2(require("zlib")); var util_1 = require("util"); - var stat = (0, util_1.promisify)(fs30.stat); + var stat = (0, util_1.promisify)(fs31.stat); var gzipExemptFileExtensions = [ ".gz", ".gzip", @@ -126084,9 +126084,9 @@ var require_upload_gzip = __commonJS({ } } return new Promise((resolve13, reject) => { - const inputStream = fs30.createReadStream(originalFilePath); + const inputStream = fs31.createReadStream(originalFilePath); const gzip = zlib3.createGzip(); - const outputStream = fs30.createWriteStream(tempFilePath); + const outputStream = fs31.createWriteStream(tempFilePath); inputStream.pipe(gzip).pipe(outputStream); outputStream.on("finish", () => __awaiter2(this, void 0, void 0, function* () { const size = (yield stat(tempFilePath)).size; @@ -126104,7 +126104,7 @@ var require_upload_gzip = __commonJS({ return __awaiter2(this, void 0, void 0, function* () { return new Promise((resolve13) => __awaiter2(this, void 0, void 0, function* () { var _a, e_1, _b, _c; - const inputStream = fs30.createReadStream(originalFilePath); + const inputStream = fs31.createReadStream(originalFilePath); const gzip = zlib3.createGzip(); inputStream.pipe(gzip); const chunks = []; @@ -126313,7 +126313,7 @@ var require_upload_http_client = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.UploadHttpClient = void 0; - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var core30 = __importStar2(require_core4()); var tmp = __importStar2(require_tmp_promise()); var stream2 = __importStar2(require("stream")); @@ -126327,7 +126327,7 @@ var require_upload_http_client = __commonJS({ var http_manager_1 = require_http_manager(); var upload_gzip_1 = require_upload_gzip(); var requestUtils_1 = require_requestUtils2(); - var stat = (0, util_1.promisify)(fs30.stat); + var stat = (0, util_1.promisify)(fs31.stat); var UploadHttpClient = class { constructor() { this.uploadHttpManager = new http_manager_1.HttpManager((0, config_variables_1.getUploadFileConcurrency)(), "@actions/artifact-upload"); @@ -126464,7 +126464,7 @@ var require_upload_http_client = __commonJS({ let openUploadStream; if (totalFileSize < buffer.byteLength) { core30.debug(`The gzip file created for ${parameters.file} did not help with reducing the size of the file. The original file will be uploaded as-is`); - openUploadStream = () => fs30.createReadStream(parameters.file); + openUploadStream = () => fs31.createReadStream(parameters.file); isGzip = false; uploadFileSize = totalFileSize; } else { @@ -126510,7 +126510,7 @@ var require_upload_http_client = __commonJS({ failedChunkSizes += chunkSize; continue; } - const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs30.createReadStream(uploadFilePath, { + const result = yield this.uploadChunk(httpClientIndex, parameters.resourceUrl, () => fs31.createReadStream(uploadFilePath, { start: startChunkIndex, end: endChunkIndex, autoClose: false @@ -126705,7 +126705,7 @@ var require_download_http_client = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.DownloadHttpClient = void 0; - var fs30 = __importStar2(require("fs")); + var fs31 = __importStar2(require("fs")); var core30 = __importStar2(require_core4()); var zlib3 = __importStar2(require("zlib")); var utils_1 = require_utils11(); @@ -126796,7 +126796,7 @@ var require_download_http_client = __commonJS({ return __awaiter2(this, void 0, void 0, function* () { let retryCount = 0; const retryLimit = (0, config_variables_1.getRetryLimit)(); - let destinationStream = fs30.createWriteStream(downloadPath); + let destinationStream = fs31.createWriteStream(downloadPath); const headers = (0, utils_1.getDownloadHeaders)("application/json", true, true); const makeDownloadRequest = () => __awaiter2(this, void 0, void 0, function* () { const client = this.downloadHttpManager.getClient(httpClientIndex); @@ -126838,7 +126838,7 @@ var require_download_http_client = __commonJS({ } }); yield (0, utils_1.rmFile)(fileDownloadPath); - destinationStream = fs30.createWriteStream(fileDownloadPath); + destinationStream = fs31.createWriteStream(fileDownloadPath); }); while (retryCount <= retryLimit) { let response; @@ -126955,21 +126955,21 @@ var require_download_specification = __commonJS({ }; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.getDownloadSpecification = void 0; - var path28 = __importStar2(require("path")); + var path29 = __importStar2(require("path")); function getDownloadSpecification(artifactName, artifactEntries, downloadPath, includeRootDirectory) { const directories = /* @__PURE__ */ new Set(); const specifications = { - rootDownloadLocation: includeRootDirectory ? path28.join(downloadPath, artifactName) : downloadPath, + rootDownloadLocation: includeRootDirectory ? path29.join(downloadPath, artifactName) : downloadPath, directoryStructure: [], emptyFilesToCreate: [], filesToDownload: [] }; for (const entry of artifactEntries) { if (entry.path.startsWith(`${artifactName}/`) || entry.path.startsWith(`${artifactName}\\`)) { - const normalizedPathEntry = path28.normalize(entry.path); - const filePath = path28.join(downloadPath, includeRootDirectory ? normalizedPathEntry : normalizedPathEntry.replace(artifactName, "")); + const normalizedPathEntry = path29.normalize(entry.path); + const filePath = path29.join(downloadPath, includeRootDirectory ? normalizedPathEntry : normalizedPathEntry.replace(artifactName, "")); if (entry.itemType === "file") { - directories.add(path28.dirname(filePath)); + directories.add(path29.dirname(filePath)); if (entry.fileLength === 0) { specifications.emptyFilesToCreate.push(filePath); } else { @@ -127111,7 +127111,7 @@ Note: The size of downloaded zips can differ significantly from the reported siz return uploadResponse; }); } - downloadArtifact(name, path28, options) { + downloadArtifact(name, path29, options) { return __awaiter2(this, void 0, void 0, function* () { const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); const artifacts = yield downloadHttpClient.listArtifacts(); @@ -127125,12 +127125,12 @@ Note: The size of downloaded zips can differ significantly from the reported siz throw new Error(`Unable to find an artifact with the name: ${name}`); } const items = yield downloadHttpClient.getContainerItems(artifactToDownload.name, artifactToDownload.fileContainerResourceUrl); - if (!path28) { - path28 = (0, config_variables_1.getWorkSpaceDirectory)(); + if (!path29) { + path29 = (0, config_variables_1.getWorkSpaceDirectory)(); } - path28 = (0, path_1.normalize)(path28); - path28 = (0, path_1.resolve)(path28); - const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(name, items.value, path28, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false); + path29 = (0, path_1.normalize)(path29); + path29 = (0, path_1.resolve)(path29); + const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(name, items.value, path29, (options === null || options === void 0 ? void 0 : options.createArtifactFolder) || false); if (downloadSpecification.filesToDownload.length === 0) { core30.info(`No downloadable files were found for the artifact: ${artifactToDownload.name}`); } else { @@ -127145,7 +127145,7 @@ Note: The size of downloaded zips can differ significantly from the reported siz }; }); } - downloadAllArtifacts(path28) { + downloadAllArtifacts(path29) { return __awaiter2(this, void 0, void 0, function* () { const downloadHttpClient = new download_http_client_1.DownloadHttpClient(); const response = []; @@ -127154,18 +127154,18 @@ Note: The size of downloaded zips can differ significantly from the reported siz core30.info("Unable to find any artifacts for the associated workflow"); return response; } - if (!path28) { - path28 = (0, config_variables_1.getWorkSpaceDirectory)(); + if (!path29) { + path29 = (0, config_variables_1.getWorkSpaceDirectory)(); } - path28 = (0, path_1.normalize)(path28); - path28 = (0, path_1.resolve)(path28); + path29 = (0, path_1.normalize)(path29); + path29 = (0, path_1.resolve)(path29); let downloadedArtifacts = 0; while (downloadedArtifacts < artifacts.count) { const currentArtifactToDownload = artifacts.value[downloadedArtifacts]; downloadedArtifacts += 1; core30.info(`starting download of artifact ${currentArtifactToDownload.name} : ${downloadedArtifacts}/${artifacts.count}`); const items = yield downloadHttpClient.getContainerItems(currentArtifactToDownload.name, currentArtifactToDownload.fileContainerResourceUrl); - const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(currentArtifactToDownload.name, items.value, path28, true); + const downloadSpecification = (0, download_specification_1.getDownloadSpecification)(currentArtifactToDownload.name, items.value, path29, true); if (downloadSpecification.filesToDownload.length === 0) { core30.info(`No downloadable files were found for any artifact ${currentArtifactToDownload.name}`); } else { @@ -128491,8 +128491,8 @@ var require_util16 = __commonJS({ parts.push(format.substring(last)); return parts.join(""); }; - util.formatNumber = function(number, decimals, dec_point, thousands_sep) { - var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; + util.formatNumber = function(number2, decimals, dec_point, thousands_sep) { + var n = number2, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; var d = dec_point === void 0 ? "," : dec_point; var t = thousands_sep === void 0 ? "." : thousands_sep, s = n < 0 ? "-" : ""; var i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + ""; @@ -145044,7 +145044,7 @@ __export(entry_points_exports, { module.exports = __toCommonJS(entry_points_exports); // src/analyze-action.ts -var fs22 = __toESM(require("fs")); +var fs23 = __toESM(require("fs")); var import_path4 = __toESM(require("path")); var import_perf_hooks4 = require("perf_hooks"); var core15 = __toESM(require_core()); @@ -145073,21 +145073,21 @@ async function getFolderSize(itemPath, options) { getFolderSize.loose = async (itemPath, options) => await core(itemPath, options); getFolderSize.strict = async (itemPath, options) => await core(itemPath, options, { strict: true }); async function core(rootItemPath, options = {}, returnType = {}) { - const fs30 = options.fs || await import("node:fs/promises"); + const fs31 = options.fs || await import("node:fs/promises"); let folderSize = 0n; const foundInos = /* @__PURE__ */ new Set(); const errors = []; await processItem(rootItemPath); async function processItem(itemPath) { if (options.ignore?.test(itemPath)) return; - const stats = returnType.strict ? await fs30.lstat(itemPath, { bigint: true }) : await fs30.lstat(itemPath, { bigint: true }).catch((error3) => errors.push(error3)); + const stats = returnType.strict ? await fs31.lstat(itemPath, { bigint: true }) : await fs31.lstat(itemPath, { bigint: true }).catch((error3) => errors.push(error3)); if (typeof stats !== "object") return; if (!foundInos.has(stats.ino)) { foundInos.add(stats.ino); folderSize += stats.size; } if (stats.isDirectory()) { - const directoryItems = returnType.strict ? await fs30.readdir(itemPath) : await fs30.readdir(itemPath).catch((error3) => errors.push(error3)); + const directoryItems = returnType.strict ? await fs31.readdir(itemPath) : await fs31.readdir(itemPath).catch((error3) => errors.push(error3)); if (typeof directoryItems !== "object") return; await Promise.all( directoryItems.map( @@ -145169,8 +145169,8 @@ var require_common = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { for (let cycle = 0; cycle < count; cycle += 1) result += string2; return result; } - function isNegativeZero(number) { - return number === 0 && Number.NEGATIVE_INFINITY === 1 / number; + function isNegativeZero(number2) { + return number2 === 0 && Number.NEGATIVE_INFINITY === 1 / number2; } module2.exports.isNothing = isNothing; module2.exports.isObject = isObject2; @@ -145425,8 +145425,8 @@ var require_null = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { function constructYamlNull() { return null; } - function isNull(object) { - return object === null; + function isNull(object2) { + return object2 === null; } module2.exports = new Type2("tag:yaml.org,2002:null", { kind: "scalar", @@ -145463,8 +145463,8 @@ var require_bool = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { function constructYamlBoolean(data) { return data === "true" || data === "True" || data === "TRUE"; } - function isBoolean(object) { - return Object.prototype.toString.call(object) === "[object Boolean]"; + function isBoolean(object2) { + return Object.prototype.toString.call(object2) === "[object Boolean]"; } module2.exports = new Type2("tag:yaml.org,2002:bool", { kind: "scalar", @@ -145472,14 +145472,14 @@ var require_bool = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { construct: constructYamlBoolean, predicate: isBoolean, represent: { - lowercase: function(object) { - return object ? "true" : "false"; + lowercase: function(object2) { + return object2 ? "true" : "false"; }, - uppercase: function(object) { - return object ? "TRUE" : "FALSE"; + uppercase: function(object2) { + return object2 ? "TRUE" : "FALSE"; }, - camelcase: function(object) { - return object ? "True" : "False"; + camelcase: function(object2) { + return object2 ? "True" : "False"; } }, defaultStyle: "lowercase" @@ -145561,8 +145561,8 @@ var require_int = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { function constructYamlInteger(data) { return parseYamlInteger(data); } - function isInteger(object) { - return Object.prototype.toString.call(object) === "[object Number]" && object % 1 === 0 && !common.isNegativeZero(object); + function isInteger(object2) { + return Object.prototype.toString.call(object2) === "[object Number]" && object2 % 1 === 0 && !common.isNegativeZero(object2); } module2.exports = new Type2("tag:yaml.org,2002:int", { kind: "scalar", @@ -145612,8 +145612,8 @@ var require_float = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { return sign * parseFloat(value, 10); } var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - function representYamlFloat(object, style) { - if (isNaN(object)) switch (style) { + function representYamlFloat(object2, style) { + if (isNaN(object2)) switch (style) { case "lowercase": return ".nan"; case "uppercase": @@ -145621,7 +145621,7 @@ var require_float = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { case "camelcase": return ".NaN"; } - else if (Number.POSITIVE_INFINITY === object) switch (style) { + else if (Number.POSITIVE_INFINITY === object2) switch (style) { case "lowercase": return ".inf"; case "uppercase": @@ -145629,7 +145629,7 @@ var require_float = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { case "camelcase": return ".Inf"; } - else if (Number.NEGATIVE_INFINITY === object) switch (style) { + else if (Number.NEGATIVE_INFINITY === object2) switch (style) { case "lowercase": return "-.inf"; case "uppercase": @@ -145637,12 +145637,12 @@ var require_float = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { case "camelcase": return "-.Inf"; } - else if (common.isNegativeZero(object)) return "-0.0"; - const res = object.toString(10); + else if (common.isNegativeZero(object2)) return "-0.0"; + const res = object2.toString(10); return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res; } - function isFloat(object) { - return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object)); + function isFloat(object2) { + return Object.prototype.toString.call(object2) === "[object Number]" && (object2 % 1 !== 0 || common.isNegativeZero(object2)); } module2.exports = new Type2("tag:yaml.org,2002:float", { kind: "scalar", @@ -145702,8 +145702,8 @@ var require_timestamp = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { if (delta) date.setTime(date.getTime() - delta); return date; } - function representYamlTimestamp(object) { - return object.toISOString(); + function representYamlTimestamp(object2) { + return object2.toISOString(); } module2.exports = new Type2("tag:yaml.org,2002:timestamp", { kind: "scalar", @@ -145764,10 +145764,10 @@ var require_binary = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { } else if (tailbits === 12) result.push(bits >> 4 & 255); return new Uint8Array(result); } - function representYamlBinary(object) { + function representYamlBinary(object2) { let result = ""; let bits = 0; - const max = object.length; + const max = object2.length; const map = BASE64_MAP; for (let idx = 0; idx < max; idx++) { if (idx % 3 === 0 && idx) { @@ -145776,7 +145776,7 @@ var require_binary = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { result += map[bits >> 6 & 63]; result += map[bits & 63]; } - bits = (bits << 8) + object[idx]; + bits = (bits << 8) + object2[idx]; } const tail = max % 3; if (tail === 0) { @@ -145815,9 +145815,9 @@ var require_omap = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { function resolveYamlOmap(data) { if (data === null) return true; const objectKeys = []; - const object = data; - for (let index = 0, length = object.length; index < length; index += 1) { - const pair = object[index]; + const object2 = data; + for (let index = 0, length = object2.length; index < length; index += 1) { + const pair = object2[index]; let pairHasKey = false; if (_toString.call(pair) !== "[object Object]") return false; let pairKey; @@ -145843,10 +145843,10 @@ var require_pairs = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { var _toString = Object.prototype.toString; function resolveYamlPairs(data) { if (data === null) return true; - const object = data; - const result = new Array(object.length); - for (let index = 0, length = object.length; index < length; index += 1) { - const pair = object[index]; + const object2 = data; + const result = new Array(object2.length); + for (let index = 0, length = object2.length; index < length; index += 1) { + const pair = object2[index]; if (_toString.call(pair) !== "[object Object]") return false; const keys = Object.keys(pair); if (keys.length !== 1) return false; @@ -145856,10 +145856,10 @@ var require_pairs = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { } function constructYamlPairs(data) { if (data === null) return []; - const object = data; - const result = new Array(object.length); - for (let index = 0, length = object.length; index < length; index += 1) { - const pair = object[index]; + const object2 = data; + const result = new Array(object2.length); + for (let index = 0, length = object2.length; index < length; index += 1) { + const pair = object2[index]; const keys = Object.keys(pair); result[index] = [keys[0], pair[keys[0]]]; } @@ -145876,9 +145876,9 @@ var require_set = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { var _hasOwnProperty = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; - const object = data; - for (const key in object) if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; + const object2 = data; + for (const key in object2) if (_hasOwnProperty.call(object2, key)) { + if (object2[key] !== null) return false; } return true; } @@ -145997,14 +145997,14 @@ var require_loader = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { if (c <= 65535) return String.fromCharCode(c); return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320); } - function setProperty2(object, key, value) { - if (key === "__proto__") Object.defineProperty(object, key, { + function setProperty2(object2, key, value) { + if (key === "__proto__") Object.defineProperty(object2, key, { configurable: true, enumerable: true, writable: true, value }); - else object[key] = value; + else object2[key] = value; } var simpleEscapeCheck = new Array(256); var simpleEscapeMap = new Array(256); @@ -147258,12 +147258,12 @@ var require_dumper = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { } return result; } - function writeFlowSequence(state, level, object) { + function writeFlowSequence(state, level, object2) { let _result = ""; const _tag = state.tag; - for (let index = 0, length = object.length; index < length; index += 1) { - let value = object[index]; - if (state.replacer) value = state.replacer.call(object, String(index), value); + for (let index = 0, length = object2.length; index < length; index += 1) { + let value = object2[index]; + if (state.replacer) value = state.replacer.call(object2, String(index), value); if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) { if (_result !== "") _result += "," + (!state.condenseFlow ? " " : ""); _result += state.dump; @@ -147272,12 +147272,12 @@ var require_dumper = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { state.tag = _tag; state.dump = "[" + _result + "]"; } - function writeBlockSequence(state, level, object, compact) { + function writeBlockSequence(state, level, object2, compact) { let _result = ""; const _tag = state.tag; - for (let index = 0, length = object.length; index < length; index += 1) { - let value = object[index]; - if (state.replacer) value = state.replacer.call(object, String(index), value); + for (let index = 0, length = object2.length; index < length; index += 1) { + let value = object2[index]; + if (state.replacer) value = state.replacer.call(object2, String(index), value); if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) { if (!compact || _result !== "") _result += generateNextLine(state, level); if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) _result += "-"; @@ -147288,17 +147288,17 @@ var require_dumper = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { state.tag = _tag; state.dump = _result || "[]"; } - function writeFlowMapping(state, level, object) { + function writeFlowMapping(state, level, object2) { let _result = ""; const _tag = state.tag; - const objectKeyList = Object.keys(object); + const objectKeyList = Object.keys(object2); for (let index = 0, length = objectKeyList.length; index < length; index += 1) { let pairBuffer = ""; if (_result !== "") pairBuffer += ", "; if (state.condenseFlow) pairBuffer += '"'; const objectKey = objectKeyList[index]; - let objectValue = object[objectKey]; - if (state.replacer) objectValue = state.replacer.call(object, objectKey, objectValue); + let objectValue = object2[objectKey]; + if (state.replacer) objectValue = state.replacer.call(object2, objectKey, objectValue); if (!writeNode(state, level, objectKey, false, false)) continue; if (state.dump.length > 1024) pairBuffer += "? "; pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " "); @@ -147309,10 +147309,10 @@ var require_dumper = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { state.tag = _tag; state.dump = "{" + _result + "}"; } - function writeBlockMapping(state, level, object, compact) { + function writeBlockMapping(state, level, object2, compact) { let _result = ""; const _tag = state.tag; - const objectKeyList = Object.keys(object); + const objectKeyList = Object.keys(object2); if (state.sortKeys === true) objectKeyList.sort(); else if (typeof state.sortKeys === "function") objectKeyList.sort(state.sortKeys); else if (state.sortKeys) throw new YAMLException2("sortKeys must be a boolean or a function"); @@ -147320,8 +147320,8 @@ var require_dumper = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { let pairBuffer = ""; if (!compact || _result !== "") pairBuffer += generateNextLine(state, level); const objectKey = objectKeyList[index]; - let objectValue = object[objectKey]; - if (state.replacer) objectValue = state.replacer.call(object, objectKey, objectValue); + let objectValue = object2[objectKey]; + if (state.replacer) objectValue = state.replacer.call(object2, objectKey, objectValue); if (!writeNode(state, level + 1, objectKey, true, true, true)) continue; const explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024; if (explicitPair) if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) pairBuffer += "?"; @@ -147337,19 +147337,19 @@ var require_dumper = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { state.tag = _tag; state.dump = _result || "{}"; } - function detectType(state, object, explicit) { + function detectType(state, object2, explicit) { const typeList = explicit ? state.explicitTypes : state.implicitTypes; for (let index = 0, length = typeList.length; index < length; index += 1) { const type = typeList[index]; - if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === "object" && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) { - if (explicit) if (type.multi && type.representName) state.tag = type.representName(object); + if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object2 === "object" && object2 instanceof type.instanceOf) && (!type.predicate || type.predicate(object2))) { + if (explicit) if (type.multi && type.representName) state.tag = type.representName(object2); else state.tag = type.tag; else state.tag = "?"; if (type.represent) { const style = state.styleMap[type.tag] || type.defaultStyle; let _result; - if (_toString.call(type.represent) === "[object Function]") _result = type.represent(object, style); - else if (_hasOwnProperty.call(type.represent, style)) _result = type.represent[style](object, style); + if (_toString.call(type.represent) === "[object Function]") _result = type.represent(object2, style); + else if (_hasOwnProperty.call(type.represent, style)) _result = type.represent[style](object2, style); else throw new YAMLException2("!<" + type.tag + '> tag resolver accepts not "' + style + '" style'); state.dump = _result; } @@ -147358,10 +147358,10 @@ var require_dumper = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { } return false; } - function writeNode(state, level, object, block, compact, iskey, isblockseq) { + function writeNode(state, level, object2, block, compact, iskey, isblockseq) { state.tag = null; - state.dump = object; - if (!detectType(state, object, false)) detectType(state, object, true); + state.dump = object2; + if (!detectType(state, object2, false)) detectType(state, object2, true); const type = _toString.call(state.dump); const inblock = block; if (block) block = state.flowLevel < 0 || state.flowLevel > level; @@ -147369,7 +147369,7 @@ var require_dumper = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { let duplicateIndex; let duplicate; if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); + duplicateIndex = state.duplicates.indexOf(object2); duplicate = duplicateIndex !== -1; } if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) compact = false; @@ -147408,25 +147408,25 @@ var require_dumper = /* @__PURE__ */ __commonJSMin(((exports2, module2) => { } return true; } - function getDuplicateReferences(object, state) { + function getDuplicateReferences(object2, state) { const objects = []; const duplicatesIndexes = []; - inspectNode(object, objects, duplicatesIndexes); + inspectNode(object2, objects, duplicatesIndexes); const length = duplicatesIndexes.length; for (let index = 0; index < length; index += 1) state.duplicates.push(objects[duplicatesIndexes[index]]); state.usedDuplicates = new Array(length); } - function inspectNode(object, objects, duplicatesIndexes) { - if (object !== null && typeof object === "object") { - const index = objects.indexOf(object); + function inspectNode(object2, objects, duplicatesIndexes) { + if (object2 !== null && typeof object2 === "object") { + const index = objects.indexOf(object2); if (index !== -1) { if (duplicatesIndexes.indexOf(index) === -1) duplicatesIndexes.push(index); } else { - objects.push(object); - if (Array.isArray(object)) for (let i = 0, length = object.length; i < length; i += 1) inspectNode(object[i], objects, duplicatesIndexes); + objects.push(object2); + if (Array.isArray(object2)) for (let i = 0, length = object2.length; i < length; i += 1) inspectNode(object2[i], objects, duplicatesIndexes); else { - const objectKeyList = Object.keys(object); - for (let i = 0, length = objectKeyList.length; i < length; i += 1) inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes); + const objectKeyList = Object.keys(object2); + for (let i = 0, length = objectKeyList.length; i < length; i += 1) inspectNode(object2[objectKeyList[i]], objects, duplicatesIndexes); } } } @@ -147502,6 +147502,9 @@ function isArray(value) { function isString(value) { return typeof value === "string"; } +function isNumber(value) { + return typeof value === "number"; +} function isStringOrUndefined(value) { return value === void 0 || isString(value); } @@ -147509,6 +147512,14 @@ var string = { validate: isString, required: true }; +var number = { + validate: isNumber, + required: true +}; +var object = { + validate: isObject, + required: true +}; function optional(validator) { return { validate: (val) => { @@ -147517,6 +147528,14 @@ function optional(validator) { required: false }; } +function undefinable(validator) { + return { + validate: (val) => { + return val === void 0 || validator.validate(val); + }, + required: false + }; +} function validateSchema(schema, obj) { for (const [key, validator] of Object.entries(schema)) { const hasKey = key in obj; @@ -147865,45 +147884,6 @@ function asHTTPError(arg) { } return void 0; } -var cachedCodeQlVersion = void 0; -function isVersionInfo(x) { - const candidate = x; - return typeof candidate === "object" && candidate !== null && typeof candidate.version === "string" && (candidate.features === void 0 || typeof candidate.features === "object" && candidate.features !== null) && (candidate.overlayVersion === void 0 || typeof candidate.overlayVersion === "number"); -} -function isPersistedVersionInfo(x) { - const candidate = x; - return typeof candidate === "object" && candidate !== null && typeof candidate.cmd === "string" && isVersionInfo(candidate.version); -} -function cacheCodeQlVersion(cmd, version) { - if (cachedCodeQlVersion !== void 0) { - throw new Error("cacheCodeQlVersion() should be called only once"); - } - cachedCodeQlVersion = version; - core2.exportVariable( - "CODEQL_ACTION_CLI_VERSION_INFO" /* CODEQL_VERSION_INFO */, - JSON.stringify({ cmd, version }) - ); -} -function getCachedCodeQlVersion(cmd) { - if (cachedCodeQlVersion !== void 0) { - return cachedCodeQlVersion; - } - const serialized = process.env["CODEQL_ACTION_CLI_VERSION_INFO" /* CODEQL_VERSION_INFO */]; - if (!serialized) { - return void 0; - } - let persisted; - try { - persisted = JSON.parse(serialized); - } catch { - return void 0; - } - if (!isPersistedVersionInfo(persisted) || cmd !== void 0 && persisted.cmd !== cmd) { - return void 0; - } - cachedCodeQlVersion = persisted.version; - return cachedCodeQlVersion; -} async function codeQlVersionAtLeast(codeql, requiredVersion) { return semver.gte((await codeql.getVersion()).version, requiredVersion); } @@ -148135,8 +148115,8 @@ async function asyncSome(array, predicate) { function isDefined2(value) { return value !== void 0 && value !== null; } -function unsafeEntriesInvariant(object) { - return Object.entries(object).filter( +function unsafeEntriesInvariant(object2) { + return Object.entries(object2).filter( ([_2, val]) => val !== void 0 ); } @@ -149869,8 +149849,8 @@ var SarifScanOrder = [ ]; // src/analyze.ts -var fs16 = __toESM(require("fs")); -var path15 = __toESM(require("path")); +var fs17 = __toESM(require("fs")); +var path16 = __toESM(require("path")); var import_perf_hooks3 = require("perf_hooks"); var io5 = __toESM(require_io()); @@ -149878,11 +149858,66 @@ var io5 = __toESM(require_io()); var core11 = __toESM(require_core()); // src/codeql.ts -var fs15 = __toESM(require("fs")); -var path14 = __toESM(require("path")); +var fs16 = __toESM(require("fs")); +var path15 = __toESM(require("path")); var core10 = __toESM(require_core()); var toolrunner3 = __toESM(require_toolrunner()); +// src/cache.ts +var fs6 = __toESM(require("fs")); +var path6 = __toESM(require("path")); +var COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; +var inMemoryCache = /* @__PURE__ */ new Map(); +function getCommandCacheFilePath() { + return path6.join(getTemporaryDirectory(), COMMAND_CACHE_FILENAME); +} +function readCommandCacheFile() { + let contents; + try { + contents = fs6.readFileSync(getCommandCacheFilePath(), "utf8"); + } catch { + return {}; + } + try { + const parsed = parseString(contents); + if (isObject(parsed)) { + return parsed; + } + } catch { + } + return {}; +} +function writeCommandCacheFile(data) { + try { + fs6.writeFileSync(getCommandCacheFilePath(), JSON.stringify(data)); + } catch { + } +} +function cacheCommandOutput(key, cmd, output) { + if (inMemoryCache.has(key)) { + throw new Error( + `cacheCommandOutput() should be called only once per key, but was called more than once for '${key}'.` + ); + } + const entry = { cmd, output }; + inMemoryCache.set(key, entry); + const data = readCommandCacheFile(); + data[key] = entry; + writeCommandCacheFile(data); +} +function getCachedCommandOutput(key, cmd, validate) { + const memoized = inMemoryCache.get(key); + if (memoized !== void 0) { + return memoized.output; + } + const entry = readCommandCacheFile()[key]; + if (!isObject(entry) || !isString(entry.cmd) || cmd !== void 0 && entry.cmd !== cmd || validate !== void 0 && !validate(entry.output)) { + return void 0; + } + inMemoryCache.set(key, { cmd: entry.cmd, output: entry.output }); + return entry.output; +} + // src/cli-errors.ts var SUPPORTED_PLATFORMS = [ ["linux", "x64"], @@ -150132,8 +150167,8 @@ function wrapCliConfigurationError(cliError) { } // src/config-utils.ts -var fs9 = __toESM(require("fs")); -var path10 = __toESM(require("path")); +var fs10 = __toESM(require("fs")); +var path11 = __toESM(require("path")); var import_perf_hooks = require("perf_hooks"); var core8 = __toESM(require_core()); @@ -150188,7 +150223,7 @@ function getDependencyCachingEnabled() { } // src/config/db-config.ts -var path6 = __toESM(require("path")); +var path7 = __toESM(require("path")); var jsonschema = __toESM(require_lib2()); var semver5 = __toESM(require_semver2()); @@ -150391,11 +150426,11 @@ function parsePacksSpecification(packStr) { throw new ConfigurationError(getPacksStrInvalid(packStr)); } } - if (packPath && (path6.isAbsolute(packPath) || // Permit using "/" instead of "\" on Windows + if (packPath && (path7.isAbsolute(packPath) || // Permit using "/" instead of "\" on Windows // Use `x.split(y).join(z)` as a polyfill for `x.replaceAll(y, z)` since // if we used a regex we'd need to escape the path separator on Windows // which seems more awkward. - path6.normalize(packPath).split(path6.sep).join("/") !== packPath.split(path6.sep).join("/"))) { + path7.normalize(packPath).split(path7.sep).join("/") !== packPath.split(path7.sep).join("/"))) { throw new ConfigurationError(getPacksStrInvalid(packStr)); } if (!packPath && pathStart) { @@ -150733,7 +150768,7 @@ function makeTelemetryDiagnostic(id, name, attributes) { } // src/diff-informed-analysis-utils.ts -var fs6 = __toESM(require("fs")); +var fs7 = __toESM(require("fs")); async function getDiffInformedAnalysisBranches(codeql, features, logger) { if (!await features.getValue("diff_informed_queries" /* DiffInformedQueries */, codeql)) { return void 0; @@ -150775,7 +150810,7 @@ async function prepareDiffInformedAnalysis(codeql, features, logger) { function writeDiffRangesJsonFile(logger, ranges) { const jsonContents = JSON.stringify(ranges, null, 2); const jsonFilePath = getDiffRangesJsonFilePath(); - fs6.writeFileSync(jsonFilePath, jsonContents); + fs7.writeFileSync(jsonFilePath, jsonContents); logger.debug( `Wrote pr-diff-range JSON file to ${jsonFilePath}: ${jsonContents}` @@ -150783,11 +150818,11 @@ ${jsonContents}` } function readDiffRangesJsonFile(logger) { const jsonFilePath = getDiffRangesJsonFilePath(); - if (!fs6.existsSync(jsonFilePath)) { + if (!fs7.existsSync(jsonFilePath)) { logger.debug(`Diff ranges JSON file does not exist at ${jsonFilePath}`); return void 0; } - const jsonContents = fs6.readFileSync(jsonFilePath, "utf8"); + const jsonContents = fs7.readFileSync(jsonFilePath, "utf8"); logger.debug( `Read pr-diff-range JSON file from ${jsonFilePath}: ${jsonContents}` @@ -151038,13 +151073,13 @@ Improved incremental analysis will be automatically retried when the next versio } // src/overlay/status.ts -var fs7 = __toESM(require("fs")); -var path8 = __toESM(require("path")); +var fs8 = __toESM(require("fs")); +var path9 = __toESM(require("path")); var actionsCache = __toESM(require_cache4()); var MAX_CACHE_OPERATION_MS = 3e4; var STATUS_FILE_NAME = "overlay-status.json"; function getStatusFilePath(languages) { - return path8.join( + return path9.join( getTemporaryDirectory(), "overlay-status", [...languages].sort().join("+"), @@ -151083,7 +151118,7 @@ async function getOverlayStatus(codeql, languages, diskUsage, logger) { const cacheKey3 = await getCacheKey(codeql, languages, diskUsage); const statusFile = getStatusFilePath(languages); try { - await fs7.promises.mkdir(path8.dirname(statusFile), { recursive: true }); + await fs8.promises.mkdir(path9.dirname(statusFile), { recursive: true }); const foundKey = await waitForResultWithTimeLimit( MAX_CACHE_OPERATION_MS, actionsCache.restoreCache([statusFile], cacheKey3), @@ -151095,13 +151130,13 @@ async function getOverlayStatus(codeql, languages, diskUsage, logger) { logger.debug("No overlay status found in Actions cache."); return void 0; } - if (!fs7.existsSync(statusFile)) { + if (!fs8.existsSync(statusFile)) { logger.debug( "Overlay status cache entry found but status file is missing." ); return void 0; } - const contents = await fs7.promises.readFile(statusFile, "utf-8"); + const contents = await fs8.promises.readFile(statusFile, "utf-8"); const parsed = JSON.parse(contents); if (!isObject(parsed) || typeof parsed["attemptedToBuildOverlayBaseDatabase"] !== "boolean" || typeof parsed["builtOverlayBaseDatabase"] !== "boolean") { logger.debug( @@ -151121,8 +151156,8 @@ async function saveOverlayStatus(codeql, languages, diskUsage, status, logger) { const cacheKey3 = await getCacheKey(codeql, languages, diskUsage); const statusFile = getStatusFilePath(languages); try { - await fs7.promises.mkdir(path8.dirname(statusFile), { recursive: true }); - await fs7.promises.writeFile(statusFile, JSON.stringify(status)); + await fs8.promises.mkdir(path9.dirname(statusFile), { recursive: true }); + await fs8.promises.writeFile(statusFile, JSON.stringify(status)); const cacheId = await waitForResultWithTimeLimit( MAX_CACHE_OPERATION_MS, actionsCache.saveCache([statusFile], cacheKey3), @@ -151148,8 +151183,8 @@ async function getCacheKey(codeql, languages, diskUsage) { } // src/trap-caching.ts -var fs8 = __toESM(require("fs")); -var path9 = __toESM(require("path")); +var fs9 = __toESM(require("fs")); +var path10 = __toESM(require("path")); var actionsCache2 = __toESM(require_cache4()); var CACHE_VERSION = 1; var CODEQL_TRAP_CACHE_PREFIX = "codeql-trap"; @@ -151166,13 +151201,13 @@ async function downloadTrapCaches(codeql, languages, logger) { `Found ${languagesSupportingCaching.length} languages that support TRAP caching` ); if (languagesSupportingCaching.length === 0) return result; - const cachesDir = path9.join( + const cachesDir = path10.join( getTemporaryDirectory(), "trapCaches" ); for (const language of languagesSupportingCaching) { - const cacheDir2 = path9.join(cachesDir, language); - fs8.mkdirSync(cacheDir2, { recursive: true }); + const cacheDir2 = path10.join(cachesDir, language); + fs9.mkdirSync(cacheDir2, { recursive: true }); result[language] = cacheDir2; } if (await isAnalyzingDefaultBranch()) { @@ -151184,7 +151219,7 @@ async function downloadTrapCaches(codeql, languages, logger) { let baseSha = "unknown"; const eventPath = process.env.GITHUB_EVENT_PATH; if (getWorkflowEventName() === "pull_request" && eventPath !== void 0) { - const event = JSON.parse(fs8.readFileSync(path9.resolve(eventPath), "utf-8")); + const event = JSON.parse(fs9.readFileSync(path10.resolve(eventPath), "utf-8")); baseSha = event.pull_request?.base?.sha || baseSha; } for (const language of languages) { @@ -151403,9 +151438,9 @@ async function getSupportedLanguageMap(codeql, logger) { } var baseWorkflowsPath = ".github/workflows"; function hasActionsWorkflows(sourceRoot) { - const workflowsPath = path10.resolve(sourceRoot, baseWorkflowsPath); - const stats = fs9.lstatSync(workflowsPath, { throwIfNoEntry: false }); - return stats !== void 0 && stats.isDirectory() && fs9.readdirSync(workflowsPath).length > 0; + const workflowsPath = path11.resolve(sourceRoot, baseWorkflowsPath); + const stats = fs10.lstatSync(workflowsPath, { throwIfNoEntry: false }); + return stats !== void 0 && stats.isDirectory() && fs10.readdirSync(workflowsPath).length > 0; } async function getRawLanguagesInRepo(repository, sourceRoot, logger) { logger.debug( @@ -151562,8 +151597,8 @@ async function downloadCacheWithTime(codeQL, languages, logger) { async function loadUserConfig(logger, configFile, workspacePath, apiDetails, tempDir, validateConfig) { if (isLocal(configFile)) { if (configFile !== userConfigFromActionPath(tempDir)) { - configFile = path10.resolve(workspacePath, configFile); - if (!(configFile + path10.sep).startsWith(workspacePath + path10.sep)) { + configFile = path11.resolve(workspacePath, configFile); + if (!(configFile + path11.sep).startsWith(workspacePath + path11.sep)) { throw new ConfigurationError( getConfigFileOutsideWorkspaceErrorMessage(configFile) ); @@ -151835,10 +151870,10 @@ async function setCppTrapCachingEnvironmentVariables(config, logger) { } } function dbLocationOrDefault(dbLocation, tempDir) { - return dbLocation || path10.resolve(tempDir, "codeql_databases"); + return dbLocation || path11.resolve(tempDir, "codeql_databases"); } function userConfigFromActionPath(tempDir) { - return path10.resolve(tempDir, "user-config-from-action.yml"); + return path11.resolve(tempDir, "user-config-from-action.yml"); } function hasQueryCustomisation(userConfig) { return isDefined2(userConfig["disable-default-queries"]) || isDefined2(userConfig.queries) || isDefined2(userConfig["query-filters"]); @@ -151871,7 +151906,7 @@ async function initConfig(features, inputs) { ); } inputs.configFile = userConfigFromActionPath(tempDir); - fs9.writeFileSync(inputs.configFile, inputs.configInput); + fs10.writeFileSync(inputs.configFile, inputs.configInput); logger.debug(`Using config from action input: ${inputs.configFile}`); } let userConfig = {}; @@ -152021,7 +152056,7 @@ function isLocal(configPath) { return configPath.indexOf("@") === -1; } function getLocalConfig(logger, configFile, validateConfig) { - if (!fs9.existsSync(configFile)) { + if (!fs10.existsSync(configFile)) { throw new ConfigurationError( getConfigFileDoesNotExistErrorMessage(configFile) ); @@ -152029,7 +152064,7 @@ function getLocalConfig(logger, configFile, validateConfig) { return parseUserConfig( logger, configFile, - fs9.readFileSync(configFile, "utf-8"), + fs10.readFileSync(configFile, "utf-8"), validateConfig ); } @@ -152069,22 +152104,22 @@ async function getRemoteConfig(logger, configFile, apiDetails, validateConfig) { ); } function getPathToParsedConfigFile(tempDir) { - return path10.join(tempDir, "config"); + return path11.join(tempDir, "config"); } async function saveConfig(config, logger) { const configString = JSON.stringify(config); const configFile = getPathToParsedConfigFile(config.tempDir); - fs9.mkdirSync(path10.dirname(configFile), { recursive: true }); - fs9.writeFileSync(configFile, configString, "utf8"); + fs10.mkdirSync(path11.dirname(configFile), { recursive: true }); + fs10.writeFileSync(configFile, configString, "utf8"); logger.debug("Saved config:"); logger.debug(configString); } async function getConfig(tempDir, logger) { const configFile = getPathToParsedConfigFile(tempDir); - if (!fs9.existsSync(configFile)) { + if (!fs10.existsSync(configFile)) { return void 0; } - const configString = fs9.readFileSync(configFile, "utf8"); + const configString = fs10.readFileSync(configFile, "utf8"); logger.debug("Loaded config:"); logger.debug(configString); const config = JSON.parse(configString); @@ -152106,9 +152141,9 @@ async function generateRegistries(registriesInput, tempDir, logger) { let qlconfigFile; if (registries) { const qlconfig = createRegistriesBlock(registries); - qlconfigFile = path10.join(tempDir, "qlconfig.yml"); + qlconfigFile = path11.join(tempDir, "qlconfig.yml"); const qlconfigContents = dump(qlconfig); - fs9.writeFileSync(qlconfigFile, qlconfigContents, "utf8"); + fs10.writeFileSync(qlconfigFile, qlconfigContents, "utf8"); logger.debug("Generated qlconfig.yml:"); logger.debug(qlconfigContents); registriesAuthTokens = registries.map((registry) => `${registry.url}=${registry.token}`).join(","); @@ -152252,8 +152287,8 @@ async function logGeneratedFilesTelemetry(config, duration, generatedFilesCount) } // src/setup-codeql.ts -var fs13 = __toESM(require("fs")); -var path12 = __toESM(require("path")); +var fs14 = __toESM(require("fs")); +var path13 = __toESM(require("path")); var toolcache3 = __toESM(require_tool_cache()); var import_fast_deep_equal = __toESM(require_fast_deep_equal()); var semver9 = __toESM(require_semver2()); @@ -152303,7 +152338,7 @@ function _v4(options, buf, offset) { var v4_default = v4; // src/overlay/caching.ts -var fs10 = __toESM(require("fs")); +var fs11 = __toESM(require("fs")); var actionsCache3 = __toESM(require_cache4()); var semver6 = __toESM(require_semver2()); var OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_MB = 7500; @@ -152313,7 +152348,7 @@ var CACHE_PREFIX = "codeql-overlay-base-database"; var MAX_CACHE_OPERATION_MS3 = 6e5; async function checkOverlayBaseDatabase(codeql, config, logger, warningPrefix) { const baseDatabaseOidsFilePath = getBaseDatabaseOidsFilePath(config); - if (!fs10.existsSync(baseDatabaseOidsFilePath)) { + if (!fs11.existsSync(baseDatabaseOidsFilePath)) { logger.warning( `${warningPrefix}: ${baseDatabaseOidsFilePath} does not exist` ); @@ -152602,7 +152637,7 @@ async function getCodeQlVersionsForOverlayBaseDatabases(rawLanguages, logger) { // src/tar.ts var import_child_process = require("child_process"); -var fs11 = __toESM(require("fs")); +var fs12 = __toESM(require("fs")); var stream = __toESM(require("stream")); var import_toolrunner = __toESM(require_toolrunner()); var io4 = __toESM(require_io()); @@ -152675,7 +152710,7 @@ async function isZstdAvailable(logger) { } } async function extract(tarPath, dest, compressionMethod, tarVersion, logger) { - fs11.mkdirSync(dest, { recursive: true }); + fs12.mkdirSync(dest, { recursive: true }); switch (compressionMethod) { case "gzip": return await toolcache.extractTar(tarPath, dest); @@ -152759,9 +152794,9 @@ function inferCompressionMethod(tarPath) { } // src/tools-download.ts -var fs12 = __toESM(require("fs")); +var fs13 = __toESM(require("fs")); var os3 = __toESM(require("os")); -var path11 = __toESM(require("path")); +var path12 = __toESM(require("path")); var import_perf_hooks2 = require("perf_hooks"); var core9 = __toESM(require_core()); var import_http_client = __toESM(require_lib()); @@ -152866,7 +152901,7 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat }; } async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorization, headers, tarVersion, logger) { - fs12.mkdirSync(dest, { recursive: true }); + fs13.mkdirSync(dest, { recursive: true }); const agent = new import_http_client.HttpClient().getAgent(codeqlURL); headers = Object.assign( { "User-Agent": "CodeQL Action" }, @@ -152894,7 +152929,7 @@ async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorizatio await extractTarZst(response, dest, tarVersion, logger); } function getToolcacheDirectory(version) { - return path11.join( + return path12.join( getRequiredEnvParam("RUNNER_TOOL_CACHE"), TOOLCACHE_TOOL_NAME, semver8.clean(version) || version, @@ -152903,7 +152938,7 @@ function getToolcacheDirectory(version) { } function writeToolcacheMarkerFile(extractedPath, logger) { const markerFilePath = `${extractedPath}.complete`; - fs12.writeFileSync(markerFilePath, ""); + fs13.writeFileSync(markerFilePath, ""); logger.info(`Created toolcache marker file ${markerFilePath}`); } function sanitizeUrlForStatusReport(url2) { @@ -153038,7 +153073,7 @@ async function findOverridingToolsInCache(humanReadableVersion, logger) { const candidates = toolcache3.findAllVersions("CodeQL").filter(isGoodVersion).map((version) => ({ folder: toolcache3.find("CodeQL", version), version - })).filter(({ folder }) => fs13.existsSync(path12.join(folder, "pinned-version"))); + })).filter(({ folder }) => fs14.existsSync(path13.join(folder, "pinned-version"))); if (candidates.length === 1) { const candidate = candidates[0]; logger.debug( @@ -153530,7 +153565,7 @@ async function useZstdBundle(cliVersion2, tarSupportsZstd) { ); } function getTempExtractionDir(tempDir) { - return path12.join(tempDir, v4_default()); + return path13.join(tempDir, v4_default()); } async function getNightlyToolsUrl(logger) { const zstdAvailability = await isZstdAvailable(logger); @@ -153578,8 +153613,8 @@ function isReservedToolsValue(tools) { } // src/tracer-config.ts -var fs14 = __toESM(require("fs")); -var path13 = __toESM(require("path")); +var fs15 = __toESM(require("fs")); +var path14 = __toESM(require("path")); async function shouldEnableIndirectTracing(codeql, config) { if (config.buildMode === "none" /* None */) { return false; @@ -153594,18 +153629,18 @@ async function endTracingForCluster(codeql, config, logger) { logger.info( "Unsetting build tracing environment variables. Subsequent steps of this job will not be traced." ); - const envVariablesFile = path13.resolve( + const envVariablesFile = path14.resolve( config.dbLocation, "temp/tracingEnvironment/end-tracing.json" ); - if (!fs14.existsSync(envVariablesFile)) { + if (!fs15.existsSync(envVariablesFile)) { throw new Error( `Environment file for ending tracing not found: ${envVariablesFile}` ); } try { const endTracingEnvVariables = JSON.parse( - fs14.readFileSync(envVariablesFile, "utf8") + fs15.readFileSync(envVariablesFile, "utf8") ); for (const [key, value] of Object.entries(endTracingEnvVariables)) { if (value !== null) { @@ -153622,8 +153657,8 @@ async function endTracingForCluster(codeql, config, logger) { } async function getTracerConfigForCluster(config) { const tracingEnvVariables = JSON.parse( - fs14.readFileSync( - path13.resolve( + fs15.readFileSync( + path14.resolve( config.dbLocation, "temp/tracingEnvironment/start-tracing.json" ), @@ -153642,6 +153677,23 @@ async function getCombinedTracerConfig(codeql, config) { } // src/codeql.ts +function isVersionInfo(x) { + return isObject(x) && validateSchema( + { + version: string, + features: undefinable(object), + overlayVersion: undefinable(number) + }, + x + ); +} +function isResolveLanguagesOutput(x) { + return isObject(x) && isObject(x.extractors) && Object.values(x.extractors).every( + (extractorList) => isArray(extractorList) && extractorList.every( + (extractor) => isObject(extractor) && isString(extractor.extractor_root) + ) + ) && (x.aliases === void 0 || isObject(x.aliases) && Object.values(x.aliases).every((alias) => isString(alias))); +} var cachedCodeQL = void 0; var CODEQL_MINIMUM_VERSION = "2.19.4"; var CODEQL_NEXT_MINIMUM_VERSION = "2.19.4"; @@ -153672,7 +153724,7 @@ async function setupCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliV toolsDownloadStatusReport )}` ); - let codeqlCmd = path14.join(codeqlFolder, "codeql", "codeql"); + let codeqlCmd = path15.join(codeqlFolder, "codeql", "codeql"); if (process.platform === "win32") { codeqlCmd += ".exe"; } else if (process.platform !== "linux" && process.platform !== "darwin") { @@ -153704,27 +153756,28 @@ async function getCodeQL(cmd) { } return cachedCodeQL; } +async function getCachedOrRun(key, cmd, run9, validate) { + let result = getCachedCommandOutput(key, cmd, validate); + if (result === void 0) { + result = await run9(); + cacheCommandOutput(key, cmd, result); + } + return result; +} async function getCodeQLForCmd(cmd, checkVersion) { const codeql = { getPath() { return cmd; }, async getVersion() { - let result = getCachedCodeQlVersion(cmd); - if (result === void 0) { - const output = await runCli(cmd, ["version", "--format=json"], { + return getCachedOrRun( + "version" /* Version */, + cmd, + () => runCliJson(cmd, ["version", "--format=json"], { noStreamStdout: true - }); - try { - result = JSON.parse(output); - } catch { - throw Error( - `Invalid JSON output from \`version --format=json\`: ${output}` - ); - } - cacheCodeQlVersion(cmd, result); - } - return result; + }), + isVersionInfo + ); }, async printVersion() { core10.info(JSON.stringify(await this.getVersion(), null, 2)); @@ -153734,12 +153787,12 @@ async function getCodeQLForCmd(cmd, checkVersion) { }, async isTracedLanguage(language) { const extractorPath = await this.resolveExtractor(language); - const tracingConfigPath = path14.join( + const tracingConfigPath = path15.join( extractorPath, "tools", "tracing-config.lua" ); - return fs15.existsSync(tracingConfigPath); + return fs16.existsSync(tracingConfigPath); }, async isScannedLanguage(language) { return !await this.isTracedLanguage(language); @@ -153819,7 +153872,7 @@ async function getCodeQLForCmd(cmd, checkVersion) { }, async runAutobuild(config, language) { applyAutobuildAzurePipelinesTimeoutFix(); - const autobuildCmd = path14.join( + const autobuildCmd = path15.join( await this.resolveExtractor(language), "tools", process.platform === "win32" ? "autobuild.cmd" : "autobuild.sh" @@ -153881,23 +153934,20 @@ async function getCodeQLForCmd(cmd, checkVersion) { async resolveLanguages({ filterToLanguagesWithQueries } = { filterToLanguagesWithQueries: false }) { - const codeqlArgs = [ - "resolve", - "languages", - "--format=betterjson", - "--extractor-options-verbosity=4", - "--extractor-include-aliases", - ...filterToLanguagesWithQueries ? ["--filter-to-languages-with-queries"] : [], - ...getExtraOptionsFromEnv(["resolve", "languages"]) - ]; - const output = await runCli(cmd, codeqlArgs); - try { - return JSON.parse(output); - } catch (e) { - throw new Error( - `Unexpected output from codeql resolve languages with --format=betterjson: ${e}` - ); - } + return getCachedOrRun( + "resolveLanguages" /* ResolveLanguages */, + cmd, + () => runCliJson(cmd, [ + "resolve", + "languages", + "--format=betterjson", + "--extractor-options-verbosity=4", + "--extractor-include-aliases", + ...filterToLanguagesWithQueries ? ["--filter-to-languages-with-queries"] : [], + ...getExtraOptionsFromEnv(["resolve", "languages"]) + ]), + isResolveLanguagesOutput + ); }, async resolveBuildEnvironment(workingDir, language) { const codeqlArgs = [ @@ -153910,15 +153960,7 @@ async function getCodeQLForCmd(cmd, checkVersion) { if (workingDir !== void 0) { codeqlArgs.push("--working-dir", workingDir); } - const output = await runCli(cmd, codeqlArgs); - try { - return JSON.parse(output); - } catch (e) { - throw new Error( - `Unexpected output from codeql resolve build-environment: ${e} in -${output}` - ); - } + return await runCliJson(cmd, codeqlArgs); }, async databaseRunQueries(databasePath, flags, queries = []) { const codeqlArgs = [ @@ -154051,30 +154093,8 @@ ${output}` await new toolrunner3.ToolRunner(cmd, args).exec(); }, async resolveExtractor(language) { - let extractorPath = ""; - await new toolrunner3.ToolRunner( - cmd, - [ - "resolve", - "extractor", - "--format=json", - `--language=${language}`, - "--extractor-include-aliases", - ...getExtraOptionsFromEnv(["resolve", "extractor"]) - ], - { - silent: true, - listeners: { - stdout: (data) => { - extractorPath += data.toString(); - }, - stderr: (data) => { - process.stderr.write(data); - } - } - } - ).exec(); - return JSON.parse(extractorPath); + const output = await this.resolveLanguages(); + return output.extractors[language][0].extractor_root; }, async resolveQueriesStartingPacks(queries) { const codeqlArgs = [ @@ -154084,14 +154104,9 @@ ${output}` ...getExtraOptionsFromEnv(["resolve", "queries"]), ...queries ]; - const output = await runCli(cmd, codeqlArgs, { noStreamStdout: true }); - try { - return JSON.parse(output); - } catch (e) { - throw new Error( - `Unexpected output from codeql resolve queries --format=startingpacks: ${e}` - ); - } + return await runCliJson(cmd, codeqlArgs, { + noStreamStdout: true + }); }, async resolveDatabase(databasePath) { const codeqlArgs = [ @@ -154101,14 +154116,9 @@ ${output}` "--format=json", ...getExtraOptionsFromEnv(["resolve", "database"]) ]; - const output = await runCli(cmd, codeqlArgs, { noStreamStdout: true }); - try { - return JSON.parse(output); - } catch (e) { - throw new Error( - `Unexpected output from codeql resolve database --format=json: ${e}` - ); - } + return await runCliJson(cmd, codeqlArgs, { + noStreamStdout: true + }); }, async mergeResults(sarifFiles, outputFile, { mergeRunsFromEqualCategory = false @@ -154190,6 +154200,14 @@ async function runCli(cmd, args = [], opts = {}) { throw e; } } +async function runCliJson(cmd, args = [], opts = {}) { + const output = await runCli(cmd, args, opts); + try { + return JSON.parse(output); + } catch { + throw Error(`Invalid JSON output from \`${args.join(" ")}\`: ${output}`); + } +} async function writeCodeScanningConfigFile(config, logger) { const codeScanningConfigFile = getGeneratedCodeScanningConfigPath(config); const augmentedConfig = appendExtraQueryExclusions( @@ -154202,7 +154220,7 @@ async function writeCodeScanningConfigFile(config, logger) { logger.startGroup("Augmented user configuration file contents"); logger.info(dump(augmentedConfig)); logger.endGroup(); - fs15.writeFileSync(codeScanningConfigFile, dump(augmentedConfig)); + fs16.writeFileSync(codeScanningConfigFile, dump(augmentedConfig)); return codeScanningConfigFile; } var TRAP_CACHE_SIZE_MB = 1024; @@ -154225,7 +154243,7 @@ async function getTrapCachingExtractorConfigArgsForLang(config, language) { ]; } function getGeneratedCodeScanningConfigPath(config) { - return path14.resolve(config.tempDir, "user-config.yaml"); + return path15.resolve(config.tempDir, "user-config.yaml"); } function getExtractionVerbosityArguments(enableDebugLogging) { return enableDebugLogging ? [`--verbosity=${EXTRACTION_DEBUG_MODE_VERBOSITY}`] : []; @@ -154662,7 +154680,7 @@ function dbIsFinalized(config, language, logger) { const dbPath = getCodeQLDatabasePath(config, language); try { const dbInfo = load( - fs16.readFileSync(path15.resolve(dbPath, "codeql-database.yml"), "utf8") + fs17.readFileSync(path16.resolve(dbPath, "codeql-database.yml"), "utf8") ); return !("inProgress" in dbInfo); } catch { @@ -154733,7 +154751,7 @@ extensions: data: `; let data = ranges.map((range) => { - const filename = path15.join(checkoutPath, range.path).replaceAll(path15.sep, "/"); + const filename = path16.join(checkoutPath, range.path).replaceAll(path16.sep, "/"); return ` - [${dump(filename, { forceQuotes: true }).trim()}, ${range.startLine}, ${range.endLine}] `; }).join(""); @@ -154746,10 +154764,10 @@ function writeDiffRangeDataExtensionPack(logger, ranges, checkoutPath) { if (ranges.length === 0) { ranges = [{ path: "", startLine: 0, endLine: 0 }]; } - const diffRangeDir = path15.join(getTemporaryDirectory(), "pr-diff-range"); - fs16.mkdirSync(diffRangeDir, { recursive: true }); - fs16.writeFileSync( - path15.join(diffRangeDir, "qlpack.yml"), + const diffRangeDir = path16.join(getTemporaryDirectory(), "pr-diff-range"); + fs17.mkdirSync(diffRangeDir, { recursive: true }); + fs17.writeFileSync( + path16.join(diffRangeDir, "qlpack.yml"), ` name: codeql-action/pr-diff-range version: 0.0.0 @@ -154764,8 +154782,8 @@ dataExtensions: ranges, checkoutPath ); - const extensionFilePath = path15.join(diffRangeDir, "pr-diff-range.yml"); - fs16.writeFileSync(extensionFilePath, extensionContents); + const extensionFilePath = path16.join(diffRangeDir, "pr-diff-range.yml"); + fs17.writeFileSync(extensionFilePath, extensionContents); logger.debug( `Wrote pr-diff-range extension pack to ${extensionFilePath}: ${extensionContents}` @@ -154888,7 +154906,7 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir async function runInterpretResultsFor(analysis, language, queries, enableDebugLogging) { logger.info(`Interpreting ${analysis.name} results for ${language}`); const category = analysis.fixCategory(logger, automationDetailsId); - const sarifFile = path15.join( + const sarifFile = path16.join( sarifFolder, addSarifExtension(analysis, language) ); @@ -154917,7 +154935,7 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir } function getPerQueryAlertCounts(sarifPath) { const sarifObject = JSON.parse( - fs16.readFileSync(sarifPath, "utf8") + fs17.readFileSync(sarifPath, "utf8") ); const perQueryAlertCounts = {}; for (const sarifRun of sarifObject.runs) { @@ -154935,13 +154953,13 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir } async function runFinalize(features, outputDir, threadsFlag, memoryFlag, codeql, config, logger) { try { - await fs16.promises.rm(outputDir, { force: true, recursive: true }); + await fs17.promises.rm(outputDir, { force: true, recursive: true }); } catch (error3) { if (error3?.code !== "ENOENT") { throw error3; } } - await fs16.promises.mkdir(outputDir, { recursive: true }); + await fs17.promises.mkdir(outputDir, { recursive: true }); const timings = await finalizeDatabaseCreation( codeql, features, @@ -154985,7 +155003,7 @@ async function warnIfGoInstalledAfterInit(config, logger) { } // src/database-upload.ts -var fs17 = __toESM(require("fs")); +var fs18 = __toESM(require("fs")); async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetails, features, logger) { if (getRequiredInput("upload-database") !== "true") { logger.debug("Database upload disabled in workflow. Skipping upload."); @@ -155021,7 +155039,7 @@ async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetai const bundledDb = await bundleDb(config, language, codeql, language, { includeDiagnostics: false }); - bundledDbSize = fs17.statSync(bundledDb).size; + bundledDbSize = fs18.statSync(bundledDb).size; const commitOid = await getCommitOid( getRequiredInput("checkout_path") ); @@ -155084,7 +155102,7 @@ async function uploadBundledDatabase(repositoryNwo, language, commitOid, bundled if (uploadsBaseUrl.endsWith("/")) { uploadsBaseUrl = uploadsBaseUrl.slice(0, -1); } - const bundledDbReadStream = fs17.createReadStream(bundledDb); + const bundledDbReadStream = fs18.createReadStream(bundledDb); try { const startTime = performance.now(); await client.request( @@ -155183,7 +155201,11 @@ async function createStatusReportBase(actionName, status, actionStartedAt, confi core12.exportVariable("CODEQL_WORKFLOW_STARTED_AT" /* WORKFLOW_STARTED_AT */, workflowStartedAt); } const runnerOs = getRequiredEnvParam("RUNNER_OS"); - const codeQlCliVersion = getCachedCodeQlVersion(); + const codeQlCliVersion = getCachedCommandOutput( + "version" /* Version */, + void 0, + isVersionInfo + ); const actionRef = process.env["GITHUB_ACTION_REF"] || ""; const testingEnvironment = getTestingEnvironment(); if (testingEnvironment) { @@ -155413,15 +155435,15 @@ __export(upload_lib_exports, { waitForProcessing: () => waitForProcessing, writePostProcessedFiles: () => writePostProcessedFiles }); -var fs21 = __toESM(require("fs")); -var path18 = __toESM(require("path")); +var fs22 = __toESM(require("fs")); +var path19 = __toESM(require("path")); var url = __toESM(require("url")); var import_zlib = __toESM(require("zlib")); var core14 = __toESM(require_core()); var jsonschema2 = __toESM(require_lib2()); // src/fingerprints.ts -var fs18 = __toESM(require("fs")); +var fs19 = __toESM(require("fs")); var import_path3 = __toESM(require("path")); // node_modules/long/index.js @@ -156409,7 +156431,7 @@ async function hash(callback, filepath) { } updateHash(current); }; - const readStream = fs18.createReadStream(filepath, "utf8"); + const readStream = fs19.createReadStream(filepath, "utf8"); for await (const data of readStream) { for (let i = 0; i < data.length; ++i) { processCharacter(data.charCodeAt(i)); @@ -156484,11 +156506,11 @@ function resolveUriToFile(location, artifacts, sourceRoot, logger) { if (!import_path3.default.isAbsolute(uri)) { uri = srcRootPrefix + uri; } - if (!fs18.existsSync(uri)) { + if (!fs19.existsSync(uri)) { logger.debug(`Unable to compute fingerprint for non-existent file: ${uri}`); return void 0; } - if (fs18.statSync(uri).isDirectory()) { + if (fs19.statSync(uri).isDirectory()) { logger.debug(`Unable to compute fingerprint for directory: ${uri}`); return void 0; } @@ -156543,8 +156565,8 @@ async function addFingerprints(sarifLog, sourceRoot, logger) { } // src/init.ts -var fs19 = __toESM(require("fs")); -var path17 = __toESM(require("path")); +var fs20 = __toESM(require("fs")); +var path18 = __toESM(require("path")); var core13 = __toESM(require_core()); var toolrunner4 = __toESM(require_toolrunner()); var github2 = __toESM(require_github()); @@ -156585,7 +156607,7 @@ async function initConfig2(features, inputs) { }); } async function runDatabaseInitCluster(databaseInitEnvironment, codeql, config, sourceRoot, processName, qlconfigFile, logger) { - fs19.mkdirSync(config.dbLocation, { recursive: true }); + fs20.mkdirSync(config.dbLocation, { recursive: true }); await wrapEnvironment( databaseInitEnvironment, async () => await codeql.databaseInitCluster( @@ -156620,25 +156642,25 @@ async function checkPacksForOverlayCompatibility(codeql, config, logger) { } function checkPackForOverlayCompatibility(packDir, codeQlOverlayVersion, logger) { try { - let qlpackPath = path17.join(packDir, "qlpack.yml"); - if (!fs19.existsSync(qlpackPath)) { - qlpackPath = path17.join(packDir, "codeql-pack.yml"); + let qlpackPath = path18.join(packDir, "qlpack.yml"); + if (!fs20.existsSync(qlpackPath)) { + qlpackPath = path18.join(packDir, "codeql-pack.yml"); } const qlpackContents = load( - fs19.readFileSync(qlpackPath, "utf8") + fs20.readFileSync(qlpackPath, "utf8") ); if (!qlpackContents.buildMetadata) { return true; } - const packInfoPath = path17.join(packDir, ".packinfo"); - if (!fs19.existsSync(packInfoPath)) { + const packInfoPath = path18.join(packDir, ".packinfo"); + if (!fs20.existsSync(packInfoPath)) { logger.warning( `The query pack at ${packDir} does not have a .packinfo file, so it cannot support overlay analysis. Recompiling the query pack with the latest CodeQL CLI should solve this problem.` ); return false; } const packInfoFileContents = JSON.parse( - fs19.readFileSync(packInfoPath, "utf8") + fs20.readFileSync(packInfoPath, "utf8") ); const packOverlayVersion = packInfoFileContents.overlayVersion; if (typeof packOverlayVersion !== "number") { @@ -156663,7 +156685,7 @@ function checkPackForOverlayCompatibility(packDir, codeQlOverlayVersion, logger) } async function checkInstallPython311(languages, codeql) { if (languages.includes("python" /* python */) && process.platform === "win32" && !(await codeql.getVersion()).features?.supportsPython312) { - const script = path17.resolve( + const script = path18.resolve( __dirname, "../python-setup", "check_python12.ps1" @@ -156673,8 +156695,8 @@ async function checkInstallPython311(languages, codeql) { ]).exec(); } } -function cleanupDatabaseClusterDirectory(config, logger, options = {}, rmSync5 = fs19.rmSync) { - if (fs19.existsSync(config.dbLocation) && (fs19.statSync(config.dbLocation).isFile() || fs19.readdirSync(config.dbLocation).length > 0)) { +function cleanupDatabaseClusterDirectory(config, logger, options = {}, rmSync5 = fs20.rmSync) { + if (fs20.existsSync(config.dbLocation) && (fs20.statSync(config.dbLocation).isFile() || fs20.readdirSync(config.dbLocation).length > 0)) { if (!options.disableExistingDirectoryWarning) { logger.warning( `The database cluster directory ${config.dbLocation} must be empty. Attempting to clean it up.` @@ -156779,7 +156801,7 @@ To opt out of this change, ${envVarOptOut}`; } // src/sarif/index.ts -var fs20 = __toESM(require("fs")); +var fs21 = __toESM(require("fs")); var InvalidSarifUploadError = class extends Error { }; function getToolNames(sarifFile) { @@ -156794,7 +156816,7 @@ function getToolNames(sarifFile) { return Object.keys(toolNames); } function readSarifFile(sarifFilePath) { - return JSON.parse(fs20.readFileSync(sarifFilePath, "utf8")); + return JSON.parse(fs21.readFileSync(sarifFilePath, "utf8")); } function combineSarifFiles(sarifFiles, logger) { logger.info(`Loading SARIF file(s)`); @@ -156928,10 +156950,10 @@ async function combineSarifFilesUsingCLI(sarifFiles, gitHubVersion, features, lo ); codeQL = initCodeQLResult.codeql; } - const baseTempDir = path18.resolve(tempDir, "combined-sarif"); - fs21.mkdirSync(baseTempDir, { recursive: true }); - const outputDirectory = fs21.mkdtempSync(path18.resolve(baseTempDir, "output-")); - const outputFile = path18.resolve(outputDirectory, "combined-sarif.sarif"); + const baseTempDir = path19.resolve(tempDir, "combined-sarif"); + fs22.mkdirSync(baseTempDir, { recursive: true }); + const outputDirectory = fs22.mkdtempSync(path19.resolve(baseTempDir, "output-")); + const outputFile = path19.resolve(outputDirectory, "combined-sarif.sarif"); await codeQL.mergeResults(sarifFiles, outputFile, { mergeRunsFromEqualCategory: true }); @@ -156964,7 +156986,7 @@ function getAutomationID2(category, analysis_key, environment) { async function uploadPayload(payload, repositoryNwo, logger, analysis) { logger.info("Uploading results"); if (shouldSkipSarifUpload()) { - const payloadSaveFile = path18.join( + const payloadSaveFile = path19.join( getTemporaryDirectory(), `payload-${analysis.kind}.json` ); @@ -156972,7 +156994,7 @@ async function uploadPayload(payload, repositoryNwo, logger, analysis) { `SARIF upload disabled by an environment variable. Saving to ${payloadSaveFile}` ); logger.info(`Payload: ${JSON.stringify(payload, null, 2)}`); - fs21.writeFileSync(payloadSaveFile, JSON.stringify(payload, null, 2)); + fs22.writeFileSync(payloadSaveFile, JSON.stringify(payload, null, 2)); return "dummy-sarif-id"; } const client = getApiClient(); @@ -157006,12 +157028,12 @@ async function uploadPayload(payload, repositoryNwo, logger, analysis) { function findSarifFilesInDir(sarifPath, isSarif) { const sarifFiles = []; const walkSarifFiles = (dir) => { - const entries = fs21.readdirSync(dir, { withFileTypes: true }); + const entries = fs22.readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { if (entry.isFile() && isSarif(entry.name)) { - sarifFiles.push(path18.resolve(dir, entry.name)); + sarifFiles.push(path19.resolve(dir, entry.name)); } else if (entry.isDirectory()) { - walkSarifFiles(path18.resolve(dir, entry.name)); + walkSarifFiles(path19.resolve(dir, entry.name)); } } }; @@ -157019,11 +157041,11 @@ function findSarifFilesInDir(sarifPath, isSarif) { return sarifFiles; } function getSarifFilePaths(sarifPath, isSarif) { - if (!fs21.existsSync(sarifPath)) { + if (!fs22.existsSync(sarifPath)) { throw new ConfigurationError(`Path does not exist: ${sarifPath}`); } let sarifFiles; - if (fs21.lstatSync(sarifPath).isDirectory()) { + if (fs22.lstatSync(sarifPath).isDirectory()) { sarifFiles = findSarifFilesInDir(sarifPath, isSarif); if (sarifFiles.length === 0) { throw new ConfigurationError( @@ -157036,7 +157058,7 @@ function getSarifFilePaths(sarifPath, isSarif) { return sarifFiles; } async function getGroupedSarifFilePaths(logger, sarifPath) { - const stats = fs21.statSync(sarifPath, { throwIfNoEntry: false }); + const stats = fs22.statSync(sarifPath, { throwIfNoEntry: false }); if (stats === void 0) { throw new ConfigurationError(`Path does not exist: ${sarifPath}`); } @@ -157044,7 +157066,7 @@ async function getGroupedSarifFilePaths(logger, sarifPath) { if (stats.isDirectory()) { let unassignedSarifFiles = findSarifFilesInDir( sarifPath, - (name) => path18.extname(name) === ".sarif" + (name) => path19.extname(name) === ".sarif" ); logger.debug( `Found the following .sarif files in ${sarifPath}: ${unassignedSarifFiles.join(", ")}` @@ -157171,7 +157193,7 @@ function buildPayload(commitOid, ref, analysisKey, analysisName, zippedSarif, wo payloadObj.base_sha = mergeBaseCommitOid; } else if (process.env.GITHUB_EVENT_PATH) { const githubEvent = JSON.parse( - fs21.readFileSync(process.env.GITHUB_EVENT_PATH, "utf8") + fs22.readFileSync(process.env.GITHUB_EVENT_PATH, "utf8") ); payloadObj.base_ref = `refs/heads/${githubEvent.pull_request.base.ref}`; payloadObj.base_sha = githubEvent.pull_request.base.sha; @@ -157305,19 +157327,19 @@ async function uploadPostProcessedFiles(logger, checkoutPath, uploadTarget, post }; } function dumpSarifFile(sarifPayload, outputDir, logger, uploadTarget) { - if (!fs21.existsSync(outputDir)) { - fs21.mkdirSync(outputDir, { recursive: true }); - } else if (!fs21.lstatSync(outputDir).isDirectory()) { + if (!fs22.existsSync(outputDir)) { + fs22.mkdirSync(outputDir, { recursive: true }); + } else if (!fs22.lstatSync(outputDir).isDirectory()) { throw new ConfigurationError( `The path that processed SARIF files should be written to exists, but is not a directory: ${outputDir}` ); } - const outputFile = path18.resolve( + const outputFile = path19.resolve( outputDir, `upload${uploadTarget.sarifExtension}` ); logger.info(`Writing processed SARIF file to ${outputFile}`); - fs21.writeFileSync(outputFile, sarifPayload); + fs22.writeFileSync(outputFile, sarifPayload); } var STATUS_CHECK_INITIAL_BACKOFF_MILLISECONDS = 5 * 1e3; var STATUS_CHECK_BACKOFF_MULTIPLIER = 2; @@ -157557,7 +157579,7 @@ function doesGoExtractionOutputExist(config) { "trap", "go" /* go */ ); - return fs22.existsSync(trapDirectory) && fs22.readdirSync(trapDirectory).some( + return fs23.existsSync(trapDirectory) && fs23.readdirSync(trapDirectory).some( (fileName) => [ ".trap", ".trap.gz", @@ -157862,21 +157884,21 @@ async function runWrapper() { } // src/analyze-action-post.ts -var fs25 = __toESM(require("fs")); +var fs26 = __toESM(require("fs")); var core17 = __toESM(require_core()); // src/debug-artifacts.ts -var fs24 = __toESM(require("fs")); -var path21 = __toESM(require("path")); +var fs25 = __toESM(require("fs")); +var path22 = __toESM(require("path")); var artifact = __toESM(require_artifact2()); var artifactLegacy = __toESM(require_artifact_client2()); var core16 = __toESM(require_core()); var import_archiver = __toESM(require_archiver()); // src/artifact-scanner.ts -var fs23 = __toESM(require("fs")); +var fs24 = __toESM(require("fs")); var os6 = __toESM(require("os")); -var path20 = __toESM(require("path")); +var path21 = __toESM(require("path")); var exec = __toESM(require_exec()); var GITHUB_PAT_CLASSIC_PATTERN = { type: "Personal Access Token (Classic)" /* PersonalAccessClassic */, @@ -157921,7 +157943,7 @@ function isAuthToken(value, patterns = GITHUB_TOKEN_PATTERNS) { function scanFileForTokens(filePath, relativePath, logger) { const findings = []; try { - const content = fs23.readFileSync(filePath, "utf8"); + const content = fs24.readFileSync(filePath, "utf8"); for (const { type, pattern } of GITHUB_TOKEN_PATTERNS) { const matches = content.match(pattern); if (matches) { @@ -157954,10 +157976,10 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log findings: [] }; try { - const tempExtractDir = fs23.mkdtempSync( - path20.join(extractDir, `extract-${depth}-`) + const tempExtractDir = fs24.mkdtempSync( + path21.join(extractDir, `extract-${depth}-`) ); - const fileName = path20.basename(archivePath).toLowerCase(); + const fileName = path21.basename(archivePath).toLowerCase(); if (fileName.endsWith(".tar.gz") || fileName.endsWith(".tgz")) { logger.debug(`Extracting tar.gz file: ${archivePath}`); await exec.exec("tar", ["-xzf", archivePath, "-C", tempExtractDir], { @@ -157974,21 +157996,21 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log ); } else if (fileName.endsWith(".zst")) { logger.debug(`Extracting zst file: ${archivePath}`); - const outputFile = path20.join( + const outputFile = path21.join( tempExtractDir, - path20.basename(archivePath, ".zst") + path21.basename(archivePath, ".zst") ); await exec.exec("zstd", ["-d", archivePath, "-o", outputFile], { silent: true }); } else if (fileName.endsWith(".gz")) { logger.debug(`Extracting gz file: ${archivePath}`); - const outputFile = path20.join( + const outputFile = path21.join( tempExtractDir, - path20.basename(archivePath, ".gz") + path21.basename(archivePath, ".gz") ); await exec.exec("gunzip", ["-c", archivePath], { - outStream: fs23.createWriteStream(outputFile), + outStream: fs24.createWriteStream(outputFile), silent: true }); } else if (fileName.endsWith(".zip")) { @@ -158009,7 +158031,7 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log ); result.scannedFiles += scanResult.scannedFiles; result.findings.push(...scanResult.findings); - fs23.rmSync(tempExtractDir, { recursive: true, force: true }); + fs24.rmSync(tempExtractDir, { recursive: true, force: true }); } catch (e) { logger.debug( `Could not extract or scan archive file ${archivePath}: ${getErrorMessage(e)}` @@ -158022,7 +158044,7 @@ async function scanFile(fullPath, relativePath, extractDir, logger, depth = 0) { scannedFiles: 1, findings: [] }; - const fileName = path20.basename(fullPath).toLowerCase(); + const fileName = path21.basename(fullPath).toLowerCase(); const isArchive = fileName.endsWith(".zip") || fileName.endsWith(".tar.gz") || fileName.endsWith(".tgz") || fileName.endsWith(".tar.zst") || fileName.endsWith(".zst") || fileName.endsWith(".gz"); if (isArchive) { const archiveResult = await scanArchiveFile( @@ -158044,10 +158066,10 @@ async function scanDirectory(dirPath, baseRelativePath, logger, depth = 0) { scannedFiles: 0, findings: [] }; - const entries = fs23.readdirSync(dirPath, { withFileTypes: true }); + const entries = fs24.readdirSync(dirPath, { withFileTypes: true }); for (const entry of entries) { - const fullPath = path20.join(dirPath, entry.name); - const relativePath = path20.join(baseRelativePath, entry.name); + const fullPath = path21.join(dirPath, entry.name); + const relativePath = path21.join(baseRelativePath, entry.name); if (entry.isDirectory()) { const subResult = await scanDirectory( fullPath, @@ -158061,7 +158083,7 @@ async function scanDirectory(dirPath, baseRelativePath, logger, depth = 0) { const fileResult = await scanFile( fullPath, relativePath, - path20.dirname(fullPath), + path21.dirname(fullPath), logger, depth ); @@ -158079,11 +158101,11 @@ async function scanArtifactsForTokens(filesToScan, logger) { scannedFiles: 0, findings: [] }; - const tempScanDir = fs23.mkdtempSync(path20.join(os6.tmpdir(), "artifact-scan-")); + const tempScanDir = fs24.mkdtempSync(path21.join(os6.tmpdir(), "artifact-scan-")); try { for (const filePath of filesToScan) { - const stats = fs23.statSync(filePath); - const fileName = path20.basename(filePath); + const stats = fs24.statSync(filePath); + const fileName = path21.basename(filePath); if (stats.isDirectory()) { const dirResult = await scanDirectory(filePath, fileName, logger); result.scannedFiles += dirResult.scannedFiles; @@ -158120,7 +158142,7 @@ async function scanArtifactsForTokens(filesToScan, logger) { } } finally { try { - fs23.rmSync(tempScanDir, { recursive: true, force: true }); + fs24.rmSync(tempScanDir, { recursive: true, force: true }); } catch (e) { logger.debug( `Could not clean up temporary scan directory: ${getErrorMessage(e)}` @@ -158140,14 +158162,14 @@ async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion logger.info( "Uploading available combined SARIF files as Actions debugging artifact..." ); - const baseTempDir = path21.resolve(tempDir, "combined-sarif"); + const baseTempDir = path22.resolve(tempDir, "combined-sarif"); const toUpload = []; - if (fs24.existsSync(baseTempDir)) { - const outputDirs = fs24.readdirSync(baseTempDir); + if (fs25.existsSync(baseTempDir)) { + const outputDirs = fs25.readdirSync(baseTempDir); for (const outputDir of outputDirs) { - const sarifFiles = fs24.readdirSync(path21.resolve(baseTempDir, outputDir)).filter((f) => path21.extname(f) === ".sarif"); + const sarifFiles = fs25.readdirSync(path22.resolve(baseTempDir, outputDir)).filter((f) => path22.extname(f) === ".sarif"); for (const sarifFile of sarifFiles) { - toUpload.push(path21.resolve(baseTempDir, outputDir, sarifFile)); + toUpload.push(path22.resolve(baseTempDir, outputDir, sarifFile)); } } } @@ -158173,17 +158195,17 @@ async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion function tryPrepareSarifDebugArtifact(config, language, logger) { try { const analyzeActionOutputDir = process.env["CODEQL_ACTION_SARIF_RESULTS_OUTPUT_DIR" /* SARIF_RESULTS_OUTPUT_DIR */]; - if (analyzeActionOutputDir !== void 0 && fs24.existsSync(analyzeActionOutputDir) && fs24.lstatSync(analyzeActionOutputDir).isDirectory()) { - const sarifFile = path21.resolve( + if (analyzeActionOutputDir !== void 0 && fs25.existsSync(analyzeActionOutputDir) && fs25.lstatSync(analyzeActionOutputDir).isDirectory()) { + const sarifFile = path22.resolve( analyzeActionOutputDir, `${language}.sarif` ); - if (fs24.existsSync(sarifFile)) { - const sarifInDbLocation = path21.resolve( + if (fs25.existsSync(sarifFile)) { + const sarifInDbLocation = path22.resolve( config.dbLocation, `${language}.sarif` ); - fs24.copyFileSync(sarifFile, sarifInDbLocation); + fs25.copyFileSync(sarifFile, sarifInDbLocation); return sarifInDbLocation; } } @@ -158234,13 +158256,13 @@ async function tryUploadAllAvailableDebugArtifacts(codeql, config, logger, codeQ } logger.info("Preparing database logs debug artifact..."); const databaseDirectory = getCodeQLDatabasePath(config, language); - const logsDirectory = path21.resolve(databaseDirectory, "log"); + const logsDirectory = path22.resolve(databaseDirectory, "log"); if (doesDirectoryExist(logsDirectory)) { filesToUpload.push(...listFolder(logsDirectory)); logger.info("Database logs debug artifact ready for upload."); } logger.info("Preparing database cluster logs debug artifact..."); - const multiLanguageTracingLogsDirectory = path21.resolve( + const multiLanguageTracingLogsDirectory = path22.resolve( config.dbLocation, "log" ); @@ -158327,8 +158349,8 @@ async function uploadArtifacts(logger, toUpload, rootDir, artifactName, ghVarian try { await artifactUploader.uploadArtifact( sanitizeArtifactName(`${artifactName}${suffix}`), - toUpload.map((file) => path21.normalize(file)), - path21.normalize(rootDir), + toUpload.map((file) => path22.normalize(file)), + path22.normalize(rootDir), { // ensure we don't keep the debug artifacts around for too long since they can be large. retentionDays: 7 @@ -158355,17 +158377,17 @@ async function getArtifactUploaderClient(logger, ghVariant) { } async function createPartialDatabaseBundle(config, language) { const databasePath = getCodeQLDatabasePath(config, language); - const databaseBundlePath = path21.resolve( + const databaseBundlePath = path22.resolve( config.dbLocation, `${config.debugDatabaseName}-${language}-partial.zip` ); core16.info( `${config.debugDatabaseName}-${language} is not finalized. Uploading partial database bundle at ${databaseBundlePath}...` ); - if (fs24.existsSync(databaseBundlePath)) { - await fs24.promises.rm(databaseBundlePath, { force: true }); + if (fs25.existsSync(databaseBundlePath)) { + await fs25.promises.rm(databaseBundlePath, { force: true }); } - const output = fs24.createWriteStream(databaseBundlePath); + const output = fs25.createWriteStream(databaseBundlePath); const zip = (0, import_archiver.default)("zip"); zip.on("error", (err) => { throw err; @@ -158418,9 +158440,9 @@ async function runWrapper2() { getCsharpTempDependencyDir() ]; for (const tempDependencyDir of tempDependencyDirs) { - if (fs25.existsSync(tempDependencyDir)) { + if (fs26.existsSync(tempDependencyDir)) { try { - fs25.rmSync(tempDependencyDir, { recursive: true }); + fs26.rmSync(tempDependencyDir, { recursive: true }); } catch (error3) { logger.info( `Failed to remove temporary dependencies directory: ${getErrorMessage(error3)}` @@ -158536,8 +158558,8 @@ async function runWrapper3() { } // src/init-action.ts -var fs27 = __toESM(require("fs")); -var path23 = __toESM(require("path")); +var fs28 = __toESM(require("fs")); +var path24 = __toESM(require("path")); var core20 = __toESM(require_core()); var github3 = __toESM(require_github()); var io7 = __toESM(require_io()); @@ -158561,8 +158583,8 @@ function getConfigFileInput(logger, actions, repositoryProperties) { } // src/workflow.ts -var fs26 = __toESM(require("fs")); -var path22 = __toESM(require("path")); +var fs27 = __toESM(require("fs")); +var path23 = __toESM(require("path")); var import_zlib2 = __toESM(require("zlib")); var core19 = __toESM(require_core()); function toCodedErrors(errors) { @@ -158713,15 +158735,15 @@ async function getWorkflow(logger) { ); } const workflowPath = await getWorkflowAbsolutePath(logger); - return load(fs26.readFileSync(workflowPath, "utf-8")); + return load(fs27.readFileSync(workflowPath, "utf-8")); } async function getWorkflowAbsolutePath(logger) { const relativePath = await getWorkflowRelativePath(); - const absolutePath = path22.join( + const absolutePath = path23.join( getRequiredEnvParam("GITHUB_WORKSPACE"), relativePath ); - if (fs26.existsSync(absolutePath)) { + if (fs27.existsSync(absolutePath)) { logger.debug( `Derived the following absolute path for the currently executing workflow: ${absolutePath}.` ); @@ -158941,7 +158963,7 @@ async function run3(startedAt) { core20.exportVariable("JOB_RUN_UUID" /* JOB_RUN_UUID */, jobRunUuid); core20.exportVariable("CODEQL_ACTION_INIT_HAS_RUN" /* INIT_ACTION_HAS_RUN */, "true"); configFile = getConfigFileInput(logger, actionsEnv, repositoryProperties); - sourceRoot = path23.resolve( + sourceRoot = path24.resolve( getRequiredEnvParam("GITHUB_WORKSPACE"), getOptionalInput("source-root") || "" ); @@ -159140,21 +159162,21 @@ async function run3(startedAt) { )) { try { logger.debug(`Applying static binary workaround for Go`); - const tempBinPath = path23.resolve( + const tempBinPath = path24.resolve( getTemporaryDirectory(), "codeql-action-go-tracing", "bin" ); - fs27.mkdirSync(tempBinPath, { recursive: true }); + fs28.mkdirSync(tempBinPath, { recursive: true }); core20.addPath(tempBinPath); - const goWrapperPath = path23.resolve(tempBinPath, "go"); - fs27.writeFileSync( + const goWrapperPath = path24.resolve(tempBinPath, "go"); + fs28.writeFileSync( goWrapperPath, `#!/bin/bash exec ${goBinaryPath} "$@"` ); - fs27.chmodSync(goWrapperPath, "755"); + fs28.chmodSync(goWrapperPath, "755"); core20.exportVariable("CODEQL_ACTION_GO_BINARY" /* GO_BINARY_LOCATION */, goWrapperPath); } catch (e) { logger.warning( @@ -159375,7 +159397,7 @@ async function runWrapper4() { var core21 = __toESM(require_core()); // src/init-action-post-helper.ts -var fs28 = __toESM(require("fs")); +var fs29 = __toESM(require("fs")); var import_path5 = __toESM(require("path")); var github4 = __toESM(require_github()); function createFailedUploadFailedSarifResult(error3) { @@ -159563,7 +159585,7 @@ async function uploadFailureInfo(uploadAllAvailableDebugArtifacts, printDebugLog } if (isSelfHostedRunner()) { try { - fs28.rmSync(config.dbLocation, { + fs29.rmSync(config.dbLocation, { recursive: true, force: true, maxRetries: 3 @@ -160051,11 +160073,11 @@ async function runWrapper7() { // src/start-proxy-action.ts var import_child_process2 = require("child_process"); -var path27 = __toESM(require("path")); +var path28 = __toESM(require("path")); var core26 = __toESM(require_core()); // src/start-proxy.ts -var path25 = __toESM(require("path")); +var path26 = __toESM(require("path")); var core25 = __toESM(require_core()); var toolcache4 = __toESM(require_tool_cache()); @@ -160525,7 +160547,7 @@ async function getProxyBinaryPath(logger, features) { proxyInfo.version ); } - return path25.join(proxyBin, proxyFileName); + return path26.join(proxyBin, proxyFileName); } // src/start-proxy/ca.ts @@ -160590,8 +160612,8 @@ function generateCertificateAuthority() { } // src/start-proxy/environment.ts -var fs29 = __toESM(require("fs")); -var path26 = __toESM(require("path")); +var fs30 = __toESM(require("fs")); +var path27 = __toESM(require("path")); var toolrunner5 = __toESM(require_toolrunner()); var io8 = __toESM(require_io()); function checkEnvVar(logger, name) { @@ -160656,16 +160678,16 @@ function discoverActionsJdks() { function checkJdkSettings(logger, jdkHome) { const filesToCheck = [ // JDK 9+ - path26.join("conf", "net.properties"), + path27.join("conf", "net.properties"), // JDK 8 and below - path26.join("lib", "net.properties") + path27.join("lib", "net.properties") ]; for (const fileToCheck of filesToCheck) { - const file = path26.join(jdkHome, fileToCheck); + const file = path27.join(jdkHome, fileToCheck); try { - if (fs29.existsSync(file)) { + if (fs30.existsSync(file)) { logger.debug(`Found '${file}'.`); - const lines = String(fs29.readFileSync(file)).split("\n"); + const lines = String(fs30.readFileSync(file)).split("\n"); for (const line of lines) { for (const property of javaProperties) { if (line.startsWith(`${property}=`)) { @@ -160846,7 +160868,7 @@ async function run7(startedAt) { try { persistInputs(); const tempDir = getTemporaryDirectory(); - const proxyLogFilePath = path27.resolve(tempDir, "proxy.log"); + const proxyLogFilePath = path28.resolve(tempDir, "proxy.log"); core26.saveState("proxy-log-file", proxyLogFilePath); const repositoryNwo = getRepositoryNwo(); const gitHubVersion = await getGitHubVersion(); diff --git a/src/codeql.ts b/src/codeql.ts index 04b4685ad2..dbc659b7aa 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -270,8 +270,20 @@ export function isResolveLanguagesOutput( x: unknown, ): x is ResolveLanguagesOutput { return ( - json.isObject(x) - // TODO: finish this with Copilot + json.isObject(x) && + json.isObject(x.extractors) && + Object.values(x.extractors).every( + (extractorList) => + json.isArray(extractorList) && + extractorList.every( + (extractor) => + json.isObject<{ extractor_root: unknown }>(extractor) && + json.isString(extractor.extractor_root), + ), + ) && + (x.aliases === undefined || + (json.isObject(x.aliases) && + Object.values(x.aliases).every((alias) => json.isString(alias)))) ); } @@ -524,6 +536,31 @@ export async function getCodeQLForTesting( return getCodeQLForCmd(cmd, false); } +/** + * Returns the cached output for a `codeql` command, resolving through the three + * caching tiers in order: the in-memory memo, then the temporary file (both via + * {@link getCachedCommandOutput}), and finally the CLI itself by invoking `run` + * on a miss and persisting its result back into the first two tiers. + * + * @param key The cache key identifying the command's output. + * @param cmd The path to the CodeQL CLI the output is obtained from. + * @param run Invokes the CLI to compute the output when it isn't cached. + * @param validate Optional type guard for values loaded from the temporary file. + */ +async function getCachedOrRun( + key: string, + cmd: string, + run: () => Promise, + validate?: (output: unknown) => output is T, +): Promise { + let result = getCachedCommandOutput(key, cmd, validate); + if (result === undefined) { + result = await run(); + cacheCommandOutput(key, cmd, result); + } + return result; +} + /** * Return a CodeQL object for CodeQL CLI access. * @@ -541,20 +578,15 @@ async function getCodeQLForCmd( return cmd; }, async getVersion() { - async function runCliVersion() { - return await runCliJson( - cmd, - ["version", "--format=json"], - { noStreamStdout: true }, - ); - } - - let result = util.getCachedCodeQlVersion(cmd); - if (result === undefined) { - result = await runCliVersion(); - util.cacheCodeQlVersion(cmd, result); - } - return result; + return getCachedOrRun( + CommandCacheKey.Version, + cmd, + () => + runCliJson(cmd, ["version", "--format=json"], { + noStreamStdout: true, + }), + isVersionInfo, + ); }, async printVersion() { // Reuse the cached version information rather than invoking the CLI again. @@ -752,7 +784,13 @@ async function getCodeQLForCmd( ]; await runCli(cmd, args); }, - async resolveLanguages() { + async resolveLanguages( + { + filterToLanguagesWithQueries, + }: { + filterToLanguagesWithQueries: boolean; + } = { filterToLanguagesWithQueries: false }, + ) { return getCachedOrRun( CommandCacheKey.ResolveLanguages, cmd, @@ -955,8 +993,8 @@ async function getCodeQLForCmd( // A previous implementation executed `codeql resolve extractor`. // This can be a bit slow due to the JVM startup cost. Instead, get // the extractor path from resolveLanguages(), which caches its output. - const extractors = await this.resolveLanguages(); - return extractors[language][0]; + const output = await this.resolveLanguages(); + return output.extractors[language][0].extractor_root; }, async resolveQueriesStartingPacks(queries: string[]): Promise { const codeqlArgs = [ From 553eef0d3fb88d9d9478e100a556cf047da13c07 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 18 Jun 2026 10:36:50 -0500 Subject: [PATCH 09/26] Add error handling for undefined extractors in language resolution --- lib/entry-points.js | 8 +++++++- src/codeql.ts | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index d450071b50..7f095b9ca3 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -154094,7 +154094,13 @@ async function getCodeQLForCmd(cmd, checkVersion) { }, async resolveExtractor(language) { const output = await this.resolveLanguages(); - return output.extractors[language][0].extractor_root; + const extractors = output.extractors[language]; + if (extractors === void 0) { + throw new Error( + `Unable to resolve an extractor for the language '${language}'.` + ); + } + return extractors[0].extractor_root; }, async resolveQueriesStartingPacks(queries) { const codeqlArgs = [ diff --git a/src/codeql.ts b/src/codeql.ts index dbc659b7aa..36bd4e5982 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -994,7 +994,13 @@ async function getCodeQLForCmd( // This can be a bit slow due to the JVM startup cost. Instead, get // the extractor path from resolveLanguages(), which caches its output. const output = await this.resolveLanguages(); - return output.extractors[language][0].extractor_root; + const extractors = output.extractors[language]; + if (extractors === undefined) { + throw new Error( + `Unable to resolve an extractor for the language '${language}'.`, + ); + } + return extractors[0].extractor_root; }, async resolveQueriesStartingPacks(queries: string[]): Promise { const codeqlArgs = [ From c8e32e423db7a4baa7df978f7fff4c7773fdd378 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 18 Jun 2026 14:42:03 -0500 Subject: [PATCH 10/26] Refactor `resolveLanguages()` to cache output according to CLI feature support The output of `resolveLanguages()` can vary based on whether the flag `--filter-to-languages-with-queries` is included, but not all versions of the CLI support that. This makes caching a single execution problematic, so I opted to cache it based on whether it's supported. If it's supported, it's used; otherwise, it's not. --- lib/entry-points.js | 34 +++++++++++++++++++--------------- src/codeql.ts | 28 ++++++++++++++-------------- src/config-utils.test.ts | 10 ++++------ src/config-utils.ts | 10 ++++------ 4 files changed, 41 insertions(+), 41 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 7f095b9ca3..f385af4a9d 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -151415,9 +151415,7 @@ async function getSupportedLanguageMap(codeql, logger) { const resolveSupportedLanguagesUsingCli = await codeql.supportsFeature( "builtinExtractorsSpecifyDefaultQueries" /* BuiltinExtractorsSpecifyDefaultQueries */ ); - const resolveResult = await codeql.resolveLanguages({ - filterToLanguagesWithQueries: resolveSupportedLanguagesUsingCli - }); + const resolveResult = await codeql.resolveLanguages(); if (resolveSupportedLanguagesUsingCli) { logger.debug( `The CodeQL CLI supports the following languages: ${Object.keys(resolveResult.extractors).join(", ")}` @@ -153931,21 +153929,27 @@ async function getCodeQLForCmd(cmd, checkVersion) { ]; await runCli(cmd, args); }, - async resolveLanguages({ - filterToLanguagesWithQueries - } = { filterToLanguagesWithQueries: false }) { + async resolveLanguages() { return getCachedOrRun( "resolveLanguages" /* ResolveLanguages */, cmd, - () => runCliJson(cmd, [ - "resolve", - "languages", - "--format=betterjson", - "--extractor-options-verbosity=4", - "--extractor-include-aliases", - ...filterToLanguagesWithQueries ? ["--filter-to-languages-with-queries"] : [], - ...getExtraOptionsFromEnv(["resolve", "languages"]) - ]), + async () => { + const isFilterToLanguagesWithQueriesSupported = await this.supportsFeature( + "builtinExtractorsSpecifyDefaultQueries" /* BuiltinExtractorsSpecifyDefaultQueries */ + ); + return runCliJson(cmd, [ + "resolve", + "languages", + "--format=betterjson", + "--extractor-options-verbosity=4", + "--extractor-include-aliases", + // TODO: Unconditionally include `--filter-to-languages-with-queries` + // once CODEQL_MINIMUM_VERSION is at least v2.23.0 + // — the first version to support this flag. + ...isFilterToLanguagesWithQueriesSupported ? ["--filter-to-languages-with-queries"] : [], + ...getExtraOptionsFromEnv(["resolve", "languages"]) + ]); + }, isResolveLanguagesOutput ); }, diff --git a/src/codeql.ts b/src/codeql.ts index 36bd4e5982..f960ce0233 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -126,9 +126,7 @@ export interface CodeQL { /** * Run 'codeql resolve languages' with '--format=betterjson'. */ - resolveLanguages(options?: { - filterToLanguagesWithQueries: boolean; - }): Promise; + resolveLanguages(): Promise; /** * Run 'codeql resolve build-environment' */ @@ -784,28 +782,30 @@ async function getCodeQLForCmd( ]; await runCli(cmd, args); }, - async resolveLanguages( - { - filterToLanguagesWithQueries, - }: { - filterToLanguagesWithQueries: boolean; - } = { filterToLanguagesWithQueries: false }, - ) { + async resolveLanguages() { return getCachedOrRun( CommandCacheKey.ResolveLanguages, cmd, - () => - runCliJson(cmd, [ + async () => { + const isFilterToLanguagesWithQueriesSupported = + await this.supportsFeature( + ToolsFeature.BuiltinExtractorsSpecifyDefaultQueries, + ); + return runCliJson(cmd, [ "resolve", "languages", "--format=betterjson", "--extractor-options-verbosity=4", "--extractor-include-aliases", - ...(filterToLanguagesWithQueries + // TODO: Unconditionally include `--filter-to-languages-with-queries` + // once CODEQL_MINIMUM_VERSION is at least v2.23.0 + // — the first version to support this flag. + ...(isFilterToLanguagesWithQueriesSupported ? ["--filter-to-languages-with-queries"] : []), ...getExtraOptionsFromEnv(["resolve", "languages"]), - ]), + ]); + }, isResolveLanguagesOutput, ); }, diff --git a/src/config-utils.test.ts b/src/config-utils.test.ts index 27de780ad5..73d5320fc4 100644 --- a/src/config-utils.test.ts +++ b/src/config-utils.test.ts @@ -891,7 +891,7 @@ const mockRepositoryNwo = parseRepositoryNwo("owner/repo"); extractor_root: "", }; const codeQL = createStubCodeQL({ - resolveLanguages: (options) => + resolveLanguages: () => Promise.resolve({ aliases: { "c#": BuiltInLanguage.csharp, @@ -905,11 +905,9 @@ const mockRepositoryNwo = parseRepositoryNwo("owner/repo"); java: [stubExtractorEntry], javascript: [stubExtractorEntry], python: [stubExtractorEntry], - ...(options?.filterToLanguagesWithQueries - ? {} - : { - html: [stubExtractorEntry], - }), + // `html` is an extractor without default queries. It should be + // excluded from the supported language map. + html: [stubExtractorEntry], }, }), }); diff --git a/src/config-utils.ts b/src/config-utils.ts index 972734877a..73532d837c 100644 --- a/src/config-utils.ts +++ b/src/config-utils.ts @@ -266,9 +266,7 @@ async function getSupportedLanguageMap( const resolveSupportedLanguagesUsingCli = await codeql.supportsFeature( ToolsFeature.BuiltinExtractorsSpecifyDefaultQueries, ); - const resolveResult = await codeql.resolveLanguages({ - filterToLanguagesWithQueries: resolveSupportedLanguagesUsingCli, - }); + const resolveResult = await codeql.resolveLanguages(); if (resolveSupportedLanguagesUsingCli) { logger.debug( `The CodeQL CLI supports the following languages: ${Object.keys(resolveResult.extractors).join(", ")}`, @@ -277,9 +275,9 @@ async function getSupportedLanguageMap( const supportedLanguages: Record = {}; // Populate canonical language names for (const extractor of Object.keys(resolveResult.extractors)) { - // If the CLI supports resolving languages with default queries, use these - // as the set of supported languages. Otherwise, require the language to be - // a built-in language. + // TODO: Delete this `if` condition once CODEQL_MINIMUM_VERSION + // is at least v2.23.0 — the first version to support the + // BuiltinExtractorsSpecifyDefaultQueries feature. if ( resolveSupportedLanguagesUsingCli || BuiltInLanguage[extractor] !== undefined From defcf1bff6e0bd3d59991cbe4c608eeb1eedb41e Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 19 Jun 2026 13:55:56 -0500 Subject: [PATCH 11/26] Rename `optional` and `undefinable` functions for clarity; update related schemas to use `optionalOrNull` --- lib/entry-points.js | 24 +++++++++--------- src/codeql.ts | 4 +-- src/json/index.test.ts | 54 ++++++++++++++++++++-------------------- src/json/index.ts | 6 ++--- src/start-proxy/types.ts | 16 ++++++------ 5 files changed, 52 insertions(+), 52 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index f385af4a9d..7a739846f9 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -147520,7 +147520,7 @@ var object = { validate: isObject, required: true }; -function optional(validator) { +function optionalOrNull(validator) { return { validate: (val) => { return val === void 0 || val === null || validator.validate(val); @@ -147528,7 +147528,7 @@ function optional(validator) { required: false }; } -function undefinable(validator) { +function optional(validator) { return { validate: (val) => { return val === void 0 || validator.validate(val); @@ -153679,8 +153679,8 @@ function isVersionInfo(x) { return isObject(x) && validateSchema( { version: string, - features: undefinable(object), - overlayVersion: undefinable(number) + features: optional(object), + overlayVersion: optional(number) }, x ); @@ -160094,14 +160094,14 @@ var toolcache4 = __toESM(require_tool_cache()); // src/start-proxy/types.ts var usernameSchema = { /** The username needed to authenticate to the package registry, if any. */ - username: optional(string) + username: optionalOrNull(string) }; function hasUsername(config) { return "username" in config; } var usernamePasswordSchema = { /** The password needed to authenticate to the package registry, if any. */ - password: optional(string), + password: optionalOrNull(string), ...usernameSchema }; function hasUsernameAndPassword(config) { @@ -160109,7 +160109,7 @@ function hasUsernameAndPassword(config) { } var tokenSchema = { /** The token needed to authenticate to the package registry, if any. */ - token: optional(string), + token: optionalOrNull(string), ...usernameSchema }; function hasToken(config) { @@ -160131,15 +160131,15 @@ var awsConfigSchema = { "role-name": string, domain: string, "domain-owner": string, - audience: optional(string) + audience: optionalOrNull(string) }; function isAWSConfig(config) { return validateSchema(awsConfigSchema, config); } var jfrogConfigSchema = { "jfrog-oidc-provider-name": string, - audience: optional(string), - "identity-mapping-name": optional(string) + audience: optionalOrNull(string), + "identity-mapping-name": optionalOrNull(string) }; function isJFrogConfig(config) { return validateSchema(jfrogConfigSchema, config); @@ -160154,8 +160154,8 @@ function isCloudsmithConfig(config) { } var gcpConfigSchema = { "workload-identity-provider": string, - "service-account": optional(string), - audience: optional(string) + "service-account": optionalOrNull(string), + audience: optionalOrNull(string) }; function isGCPConfig(config) { return validateSchema(gcpConfigSchema, config); diff --git a/src/codeql.ts b/src/codeql.ts index f960ce0233..c7c0b4e9da 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -240,8 +240,8 @@ export function isVersionInfo(x: unknown): x is VersionInfo { json.validateSchema( { version: json.string, - features: json.undefinable(json.object), - overlayVersion: json.undefinable(json.number), + features: json.optional(json.object), + overlayVersion: json.optional(json.number), }, x, ) diff --git a/src/json/index.test.ts b/src/json/index.test.ts index d37a86c370..3e96d7639c 100644 --- a/src/json/index.test.ts +++ b/src/json/index.test.ts @@ -10,8 +10,8 @@ const testSchema = { requiredKey: json.string, }; -const optionalSchema = { - optionalKey: json.optional(json.string), +const optionalOrNullSchema = { + optionalKey: json.optionalOrNull(json.string), }; test("validateSchema - required properties are required", async (t) => { @@ -30,11 +30,34 @@ test("validateSchema - required properties are required", async (t) => { test("validateSchema - optional properties are optional", async (t) => { // Optional fields may be absent + t.true(json.validateSchema(optionalOrNullSchema, {})); + t.true(json.validateSchema(optionalOrNullSchema, { optionalKey: undefined })); + t.true(json.validateSchema(optionalOrNullSchema, { optionalKey: null })); + + // But, if present, should have the expected type + t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: 0 })); + t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: 123 })); + t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: false })); + t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: true })); + t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: [] })); + t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: {} })); + t.true(json.validateSchema(optionalOrNullSchema, { optionalKey: "" })); + t.true(json.validateSchema(optionalOrNullSchema, { optionalKey: "foo" })); +}); + +const optionalSchema = { + optionalKey: json.optional(json.string), +}; + +test("validateSchema - optional properties may be absent or undefined, but reject null", async (t) => { + // Optional fields may be absent or explicitly undefined t.true(json.validateSchema(optionalSchema, {})); t.true(json.validateSchema(optionalSchema, { optionalKey: undefined })); - t.true(json.validateSchema(optionalSchema, { optionalKey: null })); - // But, if present, should have the expected type + // But should reject null + t.false(json.validateSchema(optionalSchema, { optionalKey: null })); + + // And, if present, should have the expected type t.false(json.validateSchema(optionalSchema, { optionalKey: 0 })); t.false(json.validateSchema(optionalSchema, { optionalKey: 123 })); t.false(json.validateSchema(optionalSchema, { optionalKey: false })); @@ -44,26 +67,3 @@ test("validateSchema - optional properties are optional", async (t) => { t.true(json.validateSchema(optionalSchema, { optionalKey: "" })); t.true(json.validateSchema(optionalSchema, { optionalKey: "foo" })); }); - -const undefinableSchema = { - optionalKey: json.undefinable(json.string), -}; - -test("validateSchema - undefinable properties are optional but reject null", async (t) => { - // Optional fields may be absent or explicitly undefined - t.true(json.validateSchema(undefinableSchema, {})); - t.true(json.validateSchema(undefinableSchema, { optionalKey: undefined })); - - // But, unlike `optional`, `null` is rejected - t.false(json.validateSchema(undefinableSchema, { optionalKey: null })); - - // And, if present, should have the expected type - t.false(json.validateSchema(undefinableSchema, { optionalKey: 0 })); - t.false(json.validateSchema(undefinableSchema, { optionalKey: 123 })); - t.false(json.validateSchema(undefinableSchema, { optionalKey: false })); - t.false(json.validateSchema(undefinableSchema, { optionalKey: true })); - t.false(json.validateSchema(undefinableSchema, { optionalKey: [] })); - t.false(json.validateSchema(undefinableSchema, { optionalKey: {} })); - t.true(json.validateSchema(undefinableSchema, { optionalKey: "" })); - t.true(json.validateSchema(undefinableSchema, { optionalKey: "foo" })); -}); diff --git a/src/json/index.ts b/src/json/index.ts index 4a3f65947a..66adc606bd 100644 --- a/src/json/index.ts +++ b/src/json/index.ts @@ -76,7 +76,7 @@ export const object = { * Transforms a validator to be optional, accepting `undefined` or `null` for an * absent value. */ -export function optional(validator: Validator) { +export function optionalOrNull(validator: Validator) { return { validate: (val: unknown) => { return val === undefined || val === null || validator.validate(val); @@ -87,9 +87,9 @@ export function optional(validator: Validator) { /** * Transforms a validator to be optional, accepting `undefined` for an absent - * value but, unlike `optional`, rejecting `null`. + * value but, unlike `optionalOrNull`, rejecting `null`. */ -export function undefinable(validator: Validator) { +export function optional(validator: Validator) { return { validate: (val: unknown): val is T | undefined => { return val === undefined || validator.validate(val); diff --git a/src/start-proxy/types.ts b/src/start-proxy/types.ts index 13a4ce0e8f..13369edbfa 100644 --- a/src/start-proxy/types.ts +++ b/src/start-proxy/types.ts @@ -12,7 +12,7 @@ export type RawCredential = UnvalidatedObject; /** A schema for credential objects with a username. */ export const usernameSchema = { /** The username needed to authenticate to the package registry, if any. */ - username: json.optional(json.string), + username: json.optionalOrNull(json.string), } as const satisfies json.Schema; /** Usernames may be present for both authentication with tokens or passwords. */ @@ -29,7 +29,7 @@ export function hasUsername(config: AuthConfig): config is Username { /** A schema for credential objects with a username and password. */ export const usernamePasswordSchema = { /** The password needed to authenticate to the package registry, if any. */ - password: json.optional(json.string), + password: json.optionalOrNull(json.string), ...usernameSchema, } as const satisfies json.Schema; @@ -52,7 +52,7 @@ export function hasUsernameAndPassword( /** A schema for credential objects for token-based authentication. */ export const tokenSchema = { /** The token needed to authenticate to the package registry, if any. */ - token: json.optional(json.string), + token: json.optionalOrNull(json.string), ...usernameSchema, } as const satisfies json.Schema; @@ -100,7 +100,7 @@ export const awsConfigSchema = { "role-name": json.string, domain: json.string, "domain-owner": json.string, - audience: json.optional(json.string), + audience: json.optionalOrNull(json.string), } as const satisfies json.Schema; /** Configuration for AWS OIDC. */ @@ -116,8 +116,8 @@ export function isAWSConfig( /** A schema for JFrog OIDC configurations. */ export const jfrogConfigSchema = { "jfrog-oidc-provider-name": json.string, - audience: json.optional(json.string), - "identity-mapping-name": json.optional(json.string), + audience: json.optionalOrNull(json.string), + "identity-mapping-name": json.optionalOrNull(json.string), } as const satisfies json.Schema; /** Configuration for JFrog OIDC. */ @@ -150,8 +150,8 @@ export function isCloudsmithConfig( /** A schema for GCP OIDC configurations. */ export const gcpConfigSchema = { "workload-identity-provider": json.string, - "service-account": json.optional(json.string), - audience: json.optional(json.string), + "service-account": json.optionalOrNull(json.string), + audience: json.optionalOrNull(json.string), } as const satisfies json.Schema; /** Configuration for GCP OIDC. */ From 420c97eadde1b53f6fb590ecf837b21d11a01cd8 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 19 Jun 2026 14:12:27 -0500 Subject: [PATCH 12/26] Improve documentation for cache file and command keys in CLI --- src/cache.ts | 12 +++++------- src/codeql.ts | 2 ++ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/cache.ts b/src/cache.ts index f14583a982..c094bf17b5 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -4,15 +4,13 @@ import * as path from "path"; import { getTemporaryDirectory } from "./actions-util"; import * as json from "./json"; -/** The name of the temporary file backing the cache (tier 2). */ -const COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; - /** - * The keys under which the output of cached `codeql` commands is stored. Each - * key is shared by the producer (the corresponding method in `codeql.ts`) and - * any consumers (e.g. `status-report.ts`, which peeks the cached version - * without invoking the CLI). + * The name of the temporary file that backs the on-disk cache of + * CLI responses between workflow steps. */ +const COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; + +/** The keys for cached CLI commands. */ export enum CommandCacheKey { Version = "version", ResolveLanguages = "resolveLanguages", diff --git a/src/codeql.ts b/src/codeql.ts index c7c0b4e9da..6ade356e0d 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -234,6 +234,7 @@ export interface VersionInfo { overlayVersion?: number; } +/** Returns true if `x` is a {@link VersionInfo}. */ export function isVersionInfo(x: unknown): x is VersionInfo { return ( json.isObject(x) && @@ -264,6 +265,7 @@ export interface ResolveLanguagesOutput { }; } +/** Returns true if `x` is a {@link ResolveLanguagesOutput}. */ export function isResolveLanguagesOutput( x: unknown, ): x is ResolveLanguagesOutput { From dd7ff302052d32dd1ffd25528cf0ac83e33d755f Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 19 Jun 2026 14:47:05 -0500 Subject: [PATCH 13/26] Replace `string` with `CommandCacheKey` for better type safety --- lib/entry-points.js | 10 +++++++--- src/cache.test.ts | 32 ++++++++++++++++++++------------ src/cache.ts | 20 ++++++++++++-------- src/codeql.ts | 2 +- 4 files changed, 40 insertions(+), 24 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 7a739846f9..2c0d5ff814 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -149867,6 +149867,10 @@ var toolrunner3 = __toESM(require_toolrunner()); var fs6 = __toESM(require("fs")); var path6 = __toESM(require("path")); var COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; +var CommandCacheKey = { + Version: "version", + ResolveLanguages: "resolveLanguages" +}; var inMemoryCache = /* @__PURE__ */ new Map(); function getCommandCacheFilePath() { return path6.join(getTemporaryDirectory(), COMMAND_CACHE_FILENAME); @@ -153769,7 +153773,7 @@ async function getCodeQLForCmd(cmd, checkVersion) { }, async getVersion() { return getCachedOrRun( - "version" /* Version */, + CommandCacheKey.Version, cmd, () => runCliJson(cmd, ["version", "--format=json"], { noStreamStdout: true @@ -153931,7 +153935,7 @@ async function getCodeQLForCmd(cmd, checkVersion) { }, async resolveLanguages() { return getCachedOrRun( - "resolveLanguages" /* ResolveLanguages */, + CommandCacheKey.ResolveLanguages, cmd, async () => { const isFilterToLanguagesWithQueriesSupported = await this.supportsFeature( @@ -155212,7 +155216,7 @@ async function createStatusReportBase(actionName, status, actionStartedAt, confi } const runnerOs = getRequiredEnvParam("RUNNER_OS"); const codeQlCliVersion = getCachedCommandOutput( - "version" /* Version */, + CommandCacheKey.Version, void 0, isVersionInfo ); diff --git a/src/cache.test.ts b/src/cache.test.ts index b4b72ecea2..6f9757e030 100644 --- a/src/cache.test.ts +++ b/src/cache.test.ts @@ -174,7 +174,7 @@ test.serial( "cacheCommandOutput persists the output to both the memo and the file", async (t) => { await withCacheDir((cacheFilePath) => { - cacheCommandOutput("some-command", "/path/to/codeql", { + cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", { hello: "world", }); @@ -182,16 +182,17 @@ test.serial( const onDisk = JSON.parse( fs.readFileSync(cacheFilePath, "utf8"), ) as Record; - t.deepEqual(onDisk["some-command"], { + t.deepEqual(onDisk[CommandCacheKey.Version], { cmd: "/path/to/codeql", output: { hello: "world" }, }); // Tier 1: the value is served from the memo even after the file is gone. fs.rmSync(cacheFilePath); - t.deepEqual(getCachedCommandOutput("some-command", "/path/to/codeql"), { - hello: "world", - }); + t.deepEqual( + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), + { hello: "world" }, + ); }); }, ); @@ -200,15 +201,18 @@ test.serial( "getCachedCommandOutput prefers the in-memory memo over the file", async (t) => { await withCacheDir((cacheFilePath) => { - cacheCommandOutput("some-command", "/path/to/codeql", { value: 1 }); + cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", { + value: 1, + }); // Overwrite the file with a different value; the memo (tier 1) should win. writeCacheFile(cacheFilePath, { - "some-command": { cmd: "/path/to/codeql", output: { value: 2 } }, - }); - t.deepEqual(getCachedCommandOutput("some-command", "/path/to/codeql"), { - value: 1, + [CommandCacheKey.Version]: { cmd: "/path/to/codeql", output: { value: 2 } }, }); + t.deepEqual( + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), + { value: 1 }, + ); }); }, ); @@ -217,9 +221,13 @@ test.serial( "cacheCommandOutput throws if called twice for the same key", async (t) => { await withCacheDir(() => { - cacheCommandOutput("some-command", "/path/to/codeql", { value: 1 }); + cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", { + value: 1, + }); t.throws(() => - cacheCommandOutput("some-command", "/path/to/codeql", { value: 2 }), + cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", { + value: 2, + }), ); }); }, diff --git a/src/cache.ts b/src/cache.ts index c094bf17b5..e0d50c0cd4 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -10,11 +10,15 @@ import * as json from "./json"; */ const COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; -/** The keys for cached CLI commands. */ -export enum CommandCacheKey { - Version = "version", - ResolveLanguages = "resolveLanguages", -} +/** Named keys for the CLI command-output cache. */ +export const CommandCacheKey = { + Version: "version", + ResolveLanguages: "resolveLanguages", +} as const; + +/** A key used to identify cached command output. */ +export type CommandCacheKey = + (typeof CommandCacheKey)[keyof typeof CommandCacheKey]; /** A single cached command output together with the CLI path it came from. */ interface CacheEntry { @@ -32,7 +36,7 @@ interface CacheEntry { * whenever a value is read from the file (tier 2) or computed via the CLI * (tier 3). */ -const inMemoryCache = new Map(); +const inMemoryCache = new Map(); function getCommandCacheFilePath(): string { return path.join(getTemporaryDirectory(), COMMAND_CACHE_FILENAME); @@ -81,7 +85,7 @@ function writeCommandCacheFile(data: Record): void { * served from the memo rather than recomputed. */ export function cacheCommandOutput( - key: string, + key: CommandCacheKey, cmd: string, output: unknown, ): void { @@ -110,7 +114,7 @@ export function cacheCommandOutput( * CLI). */ export function getCachedCommandOutput( - key: string, + key: CommandCacheKey, cmd?: string, validate?: (output: unknown) => output is T, ): T | undefined { diff --git a/src/codeql.ts b/src/codeql.ts index 6ade356e0d..0a00cda610 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -548,7 +548,7 @@ export async function getCodeQLForTesting( * @param validate Optional type guard for values loaded from the temporary file. */ async function getCachedOrRun( - key: string, + key: CommandCacheKey, cmd: string, run: () => Promise, validate?: (output: unknown) => output is T, From 126166c21209f7c4537f0bd342c2b5907460e656 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 19 Jun 2026 15:07:56 -0500 Subject: [PATCH 14/26] Rename `CacheEntry` to `CommandCacheEntry` for consistency --- src/cache.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cache.ts b/src/cache.ts index e0d50c0cd4..a9fbbc47c1 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -21,7 +21,7 @@ export type CommandCacheKey = (typeof CommandCacheKey)[keyof typeof CommandCacheKey]; /** A single cached command output together with the CLI path it came from. */ -interface CacheEntry { +interface CommandCacheEntry { /** * The path to the CodeQL CLI that produced `output`. Persisted so that a * different step using a different CodeQL bundle doesn't pick up a stale @@ -36,7 +36,7 @@ interface CacheEntry { * whenever a value is read from the file (tier 2) or computed via the CLI * (tier 3). */ -const inMemoryCache = new Map(); +const inMemoryCache = new Map(); function getCommandCacheFilePath(): string { return path.join(getTemporaryDirectory(), COMMAND_CACHE_FILENAME); @@ -46,7 +46,7 @@ function getCommandCacheFilePath(): string { * Reads and parses the temporary cache file. Best-effort: a missing, malformed, * or otherwise unreadable file is treated as an empty cache. */ -function readCommandCacheFile(): Record { +function readCommandCacheFile(): Record { let contents: string; try { contents = fs.readFileSync(getCommandCacheFilePath(), "utf8"); @@ -68,7 +68,7 @@ function readCommandCacheFile(): Record { * Persists the cache to the temporary file. Best-effort: a failure to write * just means a later step re-runs the CLI. */ -function writeCommandCacheFile(data: Record): void { +function writeCommandCacheFile(data: Record): void { try { fs.writeFileSync(getCommandCacheFilePath(), JSON.stringify(data)); } catch { @@ -94,7 +94,7 @@ export function cacheCommandOutput( `cacheCommandOutput() should be called only once per key, but was called more than once for '${key}'.`, ); } - const entry: CacheEntry = { cmd, output }; + const entry: CommandCacheEntry = { cmd, output }; inMemoryCache.set(key, entry); const data = readCommandCacheFile(); @@ -127,7 +127,7 @@ export function getCachedCommandOutput( // Tier 2: the temporary file persisted by an earlier step, if any. const entry = readCommandCacheFile()[key] as unknown; if ( - !json.isObject(entry) || + !json.isObject(entry) || !json.isString(entry.cmd) || (cmd !== undefined && entry.cmd !== cmd) || (validate !== undefined && !validate(entry.output)) From 94b12602ac7a37849b55dd401b0c1207f3438564 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 19 Jun 2026 15:41:47 -0500 Subject: [PATCH 15/26] Refactor cache file reading to check for existence before attempting to read --- lib/entry-points.js | 6 ++---- src/cache.ts | 6 ++---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 2c0d5ff814..fda1030e2d 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -149876,13 +149876,11 @@ function getCommandCacheFilePath() { return path6.join(getTemporaryDirectory(), COMMAND_CACHE_FILENAME); } function readCommandCacheFile() { - let contents; - try { - contents = fs6.readFileSync(getCommandCacheFilePath(), "utf8"); - } catch { + if (!fs6.existsSync(getCommandCacheFilePath())) { return {}; } try { + const contents = fs6.readFileSync(getCommandCacheFilePath(), "utf8"); const parsed = parseString(contents); if (isObject(parsed)) { return parsed; diff --git a/src/cache.ts b/src/cache.ts index a9fbbc47c1..ca766bf746 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -47,13 +47,11 @@ function getCommandCacheFilePath(): string { * or otherwise unreadable file is treated as an empty cache. */ function readCommandCacheFile(): Record { - let contents: string; - try { - contents = fs.readFileSync(getCommandCacheFilePath(), "utf8"); - } catch { + if (!fs.existsSync(getCommandCacheFilePath())) { return {}; } try { + const contents = fs.readFileSync(getCommandCacheFilePath(), "utf8"); const parsed = json.parseString(contents); if (json.isObject(parsed)) { return parsed; From d1bd5ec7b0d24e2aece3fc1fb9d8761318d83943 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 19 Jun 2026 16:07:35 -0500 Subject: [PATCH 16/26] Add logging for command cache file read/write failures --- lib/entry-points.js | 2283 ++++++++++++++++++++++--------------------- src/cache.ts | 10 +- 2 files changed, 1149 insertions(+), 1144 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index fda1030e2d..965223138b 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -22743,20 +22743,20 @@ var dist_src_exports = {}; __export(dist_src_exports, { Octokit: () => Octokit }); -function createLogger(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop2; +function createLogger(logger2 = {}) { + if (typeof logger2.debug !== "function") { + logger2.debug = noop2; } - if (typeof logger.info !== "function") { - logger.info = noop2; + if (typeof logger2.info !== "function") { + logger2.info = noop2; } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn; + if (typeof logger2.warn !== "function") { + logger2.warn = consoleWarn; } - if (typeof logger.error !== "function") { - logger.error = consoleError; + if (typeof logger2.error !== "function") { + logger2.error = consoleError; } - return logger; + return logger2; } var noop2, consoleWarn, consoleError, userAgentTrail, Octokit; var init_dist_src2 = __esm({ @@ -34908,9 +34908,9 @@ var require_logger = __commonJS({ } logLevel = level; const enabledNamespaces = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces.push(logger.namespace); + for (const logger2 of registeredLoggers) { + if (shouldEnable(logger2)) { + enabledNamespaces.push(logger2.namespace); } } debug_js_1.default.enable(enabledNamespaces.join(",")); @@ -34922,20 +34922,20 @@ var require_logger = __commonJS({ console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`); } } - function shouldEnable(logger) { - return Boolean(logLevel && levelMap[logger.level] <= levelMap[logLevel]); + function shouldEnable(logger2) { + return Boolean(logLevel && levelMap[logger2.level] <= levelMap[logLevel]); } function createLogger2(parent, level) { - const logger = Object.assign(parent.extend(level), { + const logger2 = Object.assign(parent.extend(level), { level }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { + patchLogMethod(parent, logger2); + if (shouldEnable(logger2)) { const enabledNamespaces = debug_js_1.default.disable(); - debug_js_1.default.enable(enabledNamespaces + "," + logger.namespace); + debug_js_1.default.enable(enabledNamespaces + "," + logger2.namespace); } - registeredLoggers.add(logger); - return logger; + registeredLoggers.add(logger2); + return logger2; } function contextGetLogLevel() { return logLevel; @@ -35964,7 +35964,7 @@ var require_logPolicy = __commonJS({ var sanitizer_js_1 = require_sanitizer(); exports2.logPolicyName = "logPolicy"; function logPolicy(options = {}) { - const logger = options.logger ?? log_js_1.logger.info; + const logger2 = options.logger ?? log_js_1.logger.info; const sanitizer = new sanitizer_js_1.Sanitizer({ additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, additionalAllowedQueryParameters: options.additionalAllowedQueryParameters @@ -35972,13 +35972,13 @@ var require_logPolicy = __commonJS({ return { name: exports2.logPolicyName, async sendRequest(request3, next) { - if (!logger.enabled) { + if (!logger2.enabled) { return next(request3); } - logger(`Request: ${sanitizer.sanitize(request3)}`); + logger2(`Request: ${sanitizer.sanitize(request3)}`); const response = await next(request3); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); + logger2(`Response status code: ${response.status}`); + logger2(`Headers: ${sanitizer.sanitize(response.headers)}`); return response; } }; @@ -36338,7 +36338,7 @@ var require_retryPolicy = __commonJS({ var retryPolicyLogger = (0, logger_js_1.createClientLogger)("ts-http-runtime retryPolicy"); var retryPolicyName = "retryPolicy"; function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) { - const logger = options.logger || retryPolicyLogger; + const logger2 = options.logger || retryPolicyLogger; return { name: retryPolicyName, async sendRequest(request3, next) { @@ -36350,11 +36350,11 @@ var require_retryPolicy = __commonJS({ response = void 0; responseError = void 0; try { - logger.info(`Retry ${retryCount}: Attempting to send request`, request3.requestId); + logger2.info(`Retry ${retryCount}: Attempting to send request`, request3.requestId); response = await next(request3); - logger.info(`Retry ${retryCount}: Received a response from request`, request3.requestId); + logger2.info(`Retry ${retryCount}: Received a response from request`, request3.requestId); } catch (e) { - logger.error(`Retry ${retryCount}: Received an error from request`, request3.requestId); + logger2.error(`Retry ${retryCount}: Received an error from request`, request3.requestId); responseError = e; if (!e || responseError.name !== "RestError") { throw e; @@ -36362,12 +36362,12 @@ var require_retryPolicy = __commonJS({ response = responseError.response; } if (request3.abortSignal?.aborted) { - logger.error(`Retry ${retryCount}: Request aborted.`); + logger2.error(`Retry ${retryCount}: Request aborted.`); const abortError = new AbortError_js_1.AbortError(); throw abortError; } if (retryCount >= (options.maxRetries ?? constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) { - logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); + logger2.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); if (responseError) { throw responseError; } else if (response) { @@ -36376,9 +36376,9 @@ var require_retryPolicy = __commonJS({ throw new Error("Maximum retries reached with no response or error to throw"); } } - logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); + logger2.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); strategiesLoop: for (const strategy of strategies) { - const strategyLogger = strategy.logger || logger; + const strategyLogger = strategy.logger || logger2; strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); const modifiers = strategy.retry({ retryCount, @@ -36406,11 +36406,11 @@ var require_retryPolicy = __commonJS({ } } if (responseError) { - logger.info(`None of the retry strategies could work with the received error. Throwing it.`); + logger2.info(`None of the retry strategies could work with the received error. Throwing it.`); throw responseError; } if (response) { - logger.info(`None of the retry strategies could work with the received response. Returning it.`); + logger2.info(`None of the retry strategies could work with the received response. Returning it.`); return response; } } @@ -40846,7 +40846,7 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ } function bearerTokenAuthenticationPolicy(options) { const { credential, scopes, challengeCallbacks } = options; - const logger = options.logger || log_js_1.logger; + const logger2 = options.logger || log_js_1.logger; const callbacks = { authorizeRequest: challengeCallbacks?.authorizeRequest?.bind(challengeCallbacks) ?? defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks?.authorizeRequestOnChallenge?.bind(challengeCallbacks) @@ -40878,7 +40878,7 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ scopes: Array.isArray(scopes) ? scopes : [scopes], request: request3, getAccessToken, - logger + logger: logger2 }); let response; let error3; @@ -40891,7 +40891,7 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ try { parsedClaim = atob(claims); } catch (e) { - logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`); + logger2.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`); return response; } shouldSendRequest = await authorizeRequestOnCaeChallenge({ @@ -40899,7 +40899,7 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ response, request: request3, getAccessToken, - logger + logger: logger2 }, parsedClaim); if (shouldSendRequest) { [response, error3] = await trySendRequest(request3, next); @@ -40910,7 +40910,7 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ request: request3, response, getAccessToken, - logger + logger: logger2 }); if (shouldSendRequest) { [response, error3] = await trySendRequest(request3, next); @@ -40922,7 +40922,7 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ try { parsedClaim = atob(claims); } catch (e) { - logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`); + logger2.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`); return response; } shouldSendRequest = await authorizeRequestOnCaeChallenge({ @@ -40930,7 +40930,7 @@ var require_bearerTokenAuthenticationPolicy = __commonJS({ response, request: request3, getAccessToken, - logger + logger: logger2 }, parsedClaim); if (shouldSendRequest) { [response, error3] = await trySendRequest(request3, next); @@ -41020,7 +41020,7 @@ var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ } function auxiliaryAuthenticationHeaderPolicy(options) { const { credentials, scopes } = options; - const logger = options.logger || log_js_1.logger; + const logger2 = options.logger || log_js_1.logger; const tokenCyclerMap = /* @__PURE__ */ new WeakMap(); return { name: exports2.auxiliaryAuthenticationHeaderPolicyName, @@ -41029,7 +41029,7 @@ var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs."); } if (!credentials || credentials.length === 0) { - logger.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); + logger2.info(`${exports2.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`); return next(request3); } const tokenPromises = []; @@ -41043,12 +41043,12 @@ var require_auxiliaryAuthenticationHeaderPolicy = __commonJS({ scopes: Array.isArray(scopes) ? scopes : [scopes], request: request3, getAccessToken, - logger + logger: logger2 })); } const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token)); if (auxiliaryTokens.length === 0) { - logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); + logger2.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`); return next(request3); } request3.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", ")); @@ -43245,16 +43245,16 @@ var require_authorizeRequestOnClaimChallenge = __commonJS({ } async function authorizeRequestOnClaimChallenge(onChallengeOptions) { const { scopes, response } = onChallengeOptions; - const logger = onChallengeOptions.logger || log_js_1.logger; + const logger2 = onChallengeOptions.logger || log_js_1.logger; const challenge = response.headers.get("WWW-Authenticate"); if (!challenge) { - logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`); + logger2.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`); return false; } const challenges = parseCAEChallenge(challenge) || []; const parsedChallenge = challenges.find((x) => x.claims); if (!parsedChallenge) { - logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`); + logger2.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`); return false; } const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, { @@ -116273,20 +116273,20 @@ var require_dist_node8 = __commonJS({ }; var consoleWarn2 = console.warn.bind(console); var consoleError2 = console.error.bind(console); - function createLogger2(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop3; + function createLogger2(logger2 = {}) { + if (typeof logger2.debug !== "function") { + logger2.debug = noop3; } - if (typeof logger.info !== "function") { - logger.info = noop3; + if (typeof logger2.info !== "function") { + logger2.info = noop3; } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn2; + if (typeof logger2.warn !== "function") { + logger2.warn = consoleWarn2; } - if (typeof logger.error !== "function") { - logger.error = consoleError2; + if (typeof logger2.error !== "function") { + logger2.error = consoleError2; } - return logger; + return logger2; } var userAgentTrail2 = `octokit-core.js/${VERSION8} ${(0, import_universal_user_agent5.getUserAgent)()}`; var Octokit2 = class { @@ -143715,13 +143715,13 @@ var require_log7 = __commonJS({ forge.log.logMessage = function(message) { var messageLevelIndex = sLevelInfo[message.level].index; for (var i2 = 0; i2 < sLoggers.length; ++i2) { - var logger2 = sLoggers[i2]; - if (logger2.flags & forge.log.NO_LEVEL_CHECK) { - logger2.f(message); + var logger3 = sLoggers[i2]; + if (logger3.flags & forge.log.NO_LEVEL_CHECK) { + logger3.f(message); } else { - var loggerLevelIndex = sLevelInfo[logger2.level].index; + var loggerLevelIndex = sLevelInfo[logger3.level].index; if (messageLevelIndex <= loggerLevelIndex) { - logger2.f(logger2, message); + logger3.f(logger3, message); } } } @@ -143769,20 +143769,20 @@ var require_log7 = __commonJS({ var levels; var i; forge.log.makeLogger = function(logFunction) { - var logger2 = { + var logger3 = { flags: 0, f: logFunction }; - forge.log.setLevel(logger2, "none"); - return logger2; + forge.log.setLevel(logger3, "none"); + return logger3; }; - forge.log.setLevel = function(logger2, level2) { + forge.log.setLevel = function(logger3, level2) { var rval = false; - if (logger2 && !(logger2.flags & forge.log.LEVEL_LOCKED)) { + if (logger3 && !(logger3.flags & forge.log.LEVEL_LOCKED)) { for (var i2 = 0; i2 < forge.log.levels.length; ++i2) { var aValidLevel = forge.log.levels[i2]; if (level2 == aValidLevel) { - logger2.level = level2; + logger3.level = level2; rval = true; break; } @@ -143790,15 +143790,15 @@ var require_log7 = __commonJS({ } return rval; }; - forge.log.lock = function(logger2, lock2) { + forge.log.lock = function(logger3, lock2) { if (typeof lock2 === "undefined" || lock2) { - logger2.flags |= forge.log.LEVEL_LOCKED; + logger3.flags |= forge.log.LEVEL_LOCKED; } else { - logger2.flags &= ~forge.log.LEVEL_LOCKED; + logger3.flags &= ~forge.log.LEVEL_LOCKED; } }; - forge.log.addLogger = function(logger2) { - sLoggers.push(logger2); + forge.log.addLogger = function(logger3) { + sLoggers.push(logger3); }; if (typeof console !== "undefined" && "log" in console) { if (console.error && console.warn && console.info && console.debug) { @@ -143809,31 +143809,31 @@ var require_log7 = __commonJS({ debug: console.debug, verbose: console.debug }; - f = function(logger2, message) { + f = function(logger3, message) { forge.log.prepareStandard(message); var handler2 = levelHandlers[message.level]; var args = [message.standard]; args = args.concat(message["arguments"].slice()); handler2.apply(console, args); }; - logger = forge.log.makeLogger(f); + logger2 = forge.log.makeLogger(f); } else { - f = function(logger2, message) { + f = function(logger3, message) { forge.log.prepareStandardFull(message); console.log(message.standardFull); }; - logger = forge.log.makeLogger(f); + logger2 = forge.log.makeLogger(f); } - forge.log.setLevel(logger, "debug"); - forge.log.addLogger(logger); - sConsoleLogger = logger; + forge.log.setLevel(logger2, "debug"); + forge.log.addLogger(logger2); + sConsoleLogger = logger2; } else { console = { log: function() { } }; } - var logger; + var logger2; var levelHandlers; var f; if (sConsoleLogger !== null && typeof window !== "undefined" && window.location) { @@ -147609,74 +147609,74 @@ function getMemoryFlagValueForPlatform(userInput, totalMemoryBytes, platform2) { } return Math.floor(memoryToUseMegaBytes); } -function getTotalMemoryBytes(logger) { +function getTotalMemoryBytes(logger2) { const limits = [os.totalmem()]; if (os.platform() === "linux") { limits.push( ...[ "/sys/fs/cgroup/memory/memory.limit_in_bytes", "/sys/fs/cgroup/memory.max" - ].map((file) => getCgroupMemoryLimitBytes(file, logger)).filter((limit2) => limit2 !== void 0).map((limit2) => limit2) + ].map((file) => getCgroupMemoryLimitBytes(file, logger2)).filter((limit2) => limit2 !== void 0).map((limit2) => limit2) ); } const limit = Math.min(...limits); - logger.debug( + logger2.debug( `While resolving RAM, determined that the total memory available to the Action is ${limit / (1024 * 1024)} MiB.` ); return limit; } -function getCgroupMemoryLimitBytes(limitFile, logger) { +function getCgroupMemoryLimitBytes(limitFile, logger2) { if (!fs.existsSync(limitFile)) { - logger.debug( + logger2.debug( `While resolving RAM, did not find a cgroup memory limit at ${limitFile}.` ); return void 0; } const limit = Number(fs.readFileSync(limitFile, "utf8")); if (!Number.isInteger(limit)) { - logger.debug( + logger2.debug( `While resolving RAM, ignored the file ${limitFile} that may contain a cgroup memory limit as this file did not contain an integer.` ); return void 0; } const displayLimit = `${Math.floor(limit / (1024 * 1024))} MiB`; if (limit > os.totalmem()) { - logger.debug( + logger2.debug( `While resolving RAM, ignored the file ${limitFile} that may contain a cgroup memory limit as its contents ${displayLimit} were greater than the total amount of system memory.` ); return void 0; } if (limit < MINIMUM_CGROUP_MEMORY_LIMIT_BYTES) { - logger.info( + logger2.info( `While resolving RAM, ignored a cgroup limit of ${displayLimit} in ${limitFile} as it was below ${MINIMUM_CGROUP_MEMORY_LIMIT_BYTES / (1024 * 1024)} MiB.` ); return void 0; } - logger.info( + logger2.info( `While resolving RAM, found a cgroup limit of ${displayLimit} in ${limitFile}.` ); return limit; } -function getCodeQLMemoryLimit(userInput, logger) { +function getCodeQLMemoryLimit(userInput, logger2) { return getMemoryFlagValueForPlatform( userInput, - getTotalMemoryBytes(logger), + getTotalMemoryBytes(logger2), process.platform ); } -function getMemoryFlag(userInput, logger) { - const megabytes = getCodeQLMemoryLimit(userInput, logger); +function getMemoryFlag(userInput, logger2) { + const megabytes = getCodeQLMemoryLimit(userInput, logger2); return `--ram=${megabytes}`; } -function getThreadsFlagValue(userInput, logger) { +function getThreadsFlagValue(userInput, logger2) { let numThreads; const maxThreadsCandidates = [os.cpus().length]; if (os.platform() === "linux") { maxThreadsCandidates.push( - ...["/sys/fs/cgroup/cpuset.cpus.effective", "/sys/fs/cgroup/cpuset.cpus"].map((file) => getCgroupCpuCountFromCpus(file, logger)).filter((count) => count !== void 0 && count > 0).map((count) => count) + ...["/sys/fs/cgroup/cpuset.cpus.effective", "/sys/fs/cgroup/cpuset.cpus"].map((file) => getCgroupCpuCountFromCpus(file, logger2)).filter((count) => count !== void 0 && count > 0).map((count) => count) ); maxThreadsCandidates.push( - ...["/sys/fs/cgroup/cpu.max"].map((file) => getCgroupCpuCountFromCpuMax(file, logger)).filter((count) => count !== void 0 && count > 0).map((count) => count) + ...["/sys/fs/cgroup/cpu.max"].map((file) => getCgroupCpuCountFromCpuMax(file, logger2)).filter((count) => count !== void 0 && count > 0).map((count) => count) ); } const maxThreads = Math.min(...maxThreadsCandidates); @@ -147688,14 +147688,14 @@ function getThreadsFlagValue(userInput, logger) { ); } if (numThreads > maxThreads) { - logger.info( + logger2.info( `Clamping desired number of threads (${numThreads}) to max available (${maxThreads}).` ); numThreads = maxThreads; } const minThreads = -maxThreads; if (numThreads < minThreads) { - logger.info( + logger2.info( `Clamping desired number of free threads (${numThreads}) to max available (${minThreads}).` ); numThreads = minThreads; @@ -147705,9 +147705,9 @@ function getThreadsFlagValue(userInput, logger) { } return numThreads; } -function getCgroupCpuCountFromCpuMax(cpuMaxFile, logger) { +function getCgroupCpuCountFromCpuMax(cpuMaxFile, logger2) { if (!fs.existsSync(cpuMaxFile)) { - logger.debug( + logger2.debug( `While resolving threads, did not find a cgroup CPU file at ${cpuMaxFile}.` ); return void 0; @@ -147715,7 +147715,7 @@ function getCgroupCpuCountFromCpuMax(cpuMaxFile, logger) { const cpuMaxString = fs.readFileSync(cpuMaxFile, "utf-8"); const cpuMaxStringSplit = cpuMaxString.split(" "); if (cpuMaxStringSplit.length !== 2) { - logger.debug( + logger2.debug( `While resolving threads, did not use cgroup CPU file at ${cpuMaxFile} because it contained ${cpuMaxStringSplit.length} value(s) rather than the two expected.` ); return void 0; @@ -147726,14 +147726,14 @@ function getCgroupCpuCountFromCpuMax(cpuMaxFile, logger) { } const duration = cpuMaxStringSplit[1]; const cpuCount = Math.floor(parseInt(cpuLimit) / parseInt(duration)); - logger.info( + logger2.info( `While resolving threads, found a cgroup CPU file with ${cpuCount} CPUs in ${cpuMaxFile}.` ); return cpuCount; } -function getCgroupCpuCountFromCpus(cpusFile, logger) { +function getCgroupCpuCountFromCpus(cpusFile, logger2) { if (!fs.existsSync(cpusFile)) { - logger.debug( + logger2.debug( `While resolving threads, did not find a cgroup CPUs file at ${cpusFile}.` ); return void 0; @@ -147752,13 +147752,13 @@ function getCgroupCpuCountFromCpus(cpusFile, logger) { cpuCount += cpuEndIndex - cpuStartIndex + 1; } } - logger.info( + logger2.info( `While resolving threads, found a cgroup CPUs file with ${cpuCount} CPUs in ${cpusFile}.` ); return cpuCount; } -function getThreadsFlag(userInput, logger) { - return `--threads=${getThreadsFlagValue(userInput, logger)}`; +function getThreadsFlag(userInput, logger2) { + return `--threads=${getThreadsFlagValue(userInput, logger2)}`; } function getCodeQLDatabasePath(config, language) { return path.resolve(config.dbLocation, language); @@ -147801,7 +147801,7 @@ function parseGitHubUrl(inputUrl) { } var CODEQL_ACTION_WARNED_ABOUT_VERSION_ENV_VAR = "CODEQL_ACTION_WARNED_ABOUT_VERSION"; var hasBeenWarnedAboutVersion = false; -function checkGitHubVersionInRange(version, logger) { +function checkGitHubVersionInRange(version, logger2) { if (hasBeenWarnedAboutVersion || version.type !== "GitHub Enterprise Server" /* GHES */) { return; } @@ -147811,12 +147811,12 @@ function checkGitHubVersionInRange(version, logger) { maximumVersion ); if (disallowedAPIVersionReason === 0 /* ACTION_TOO_OLD */) { - logger.warning( + logger2.warning( `The CodeQL Action version you are using is too old to be compatible with GitHub Enterprise ${version.version}. If you experience issues, please upgrade to a more recent version of the CodeQL Action.` ); } if (disallowedAPIVersionReason === 1 /* ACTION_TOO_NEW */) { - logger.warning( + logger2.warning( `GitHub Enterprise ${version.version} is too old to be compatible with this version of the CodeQL Action. If you experience issues, please upgrade to a more recent version of GitHub Enterprise or use an older version of the CodeQL Action.` ); } @@ -147962,12 +147962,12 @@ function listFolder(dir) { } return files; } -async function tryGetFolderBytes(cacheDir2, logger, quiet = false) { +async function tryGetFolderBytes(cacheDir2, logger2, quiet = false) { try { return await getFolderSize.loose(cacheDir2); } catch (e) { - if (!quiet || logger.isDebug()) { - logger.warning( + if (!quiet || logger2.isDebug()) { + logger2.warning( `Encountered an error while getting size of '${cacheDir2}': ${e}` ); } @@ -148024,7 +148024,7 @@ function getErrorMessage(error3) { function prettyPrintPack(pack) { return `${pack.name}${pack.version ? `@${pack.version}` : ""}${pack.path ? `:${pack.path}` : ""}`; } -async function checkDiskUsage(logger) { +async function checkDiskUsage(logger2) { try { const diskUsage = await fsPromises.statfs( getRequiredEnvParam("GITHUB_WORKSPACE") @@ -148035,9 +148035,9 @@ async function checkDiskUsage(logger) { if (diskUsage.bavail < 2 * numBlocksPerGb) { const message = `The Actions runner is running low on disk space (${(diskUsage.bavail / numBlocksPerMb).toPrecision(4)} MB available).`; if (process.env["CODEQL_ACTION_HAS_WARNED_ABOUT_DISK_SPACE" /* HAS_WARNED_ABOUT_DISK_SPACE */] !== "true") { - logger.warning(message); + logger2.warning(message); } else { - logger.debug(message); + logger2.debug(message); } core2.exportVariable("CODEQL_ACTION_HAS_WARNED_ABOUT_DISK_SPACE" /* HAS_WARNED_ABOUT_DISK_SPACE */, "true"); } @@ -148046,7 +148046,7 @@ async function checkDiskUsage(logger) { numTotalBytes: diskUsage.blocks * blockSizeInBytes }; } catch (error3) { - logger.warning( + logger2.warning( `Failed to check available disk space: ${getErrorMessage(error3)}` ); return void 0; @@ -148083,24 +148083,24 @@ var BuildMode = /* @__PURE__ */ ((BuildMode3) => { function cloneObject(obj) { return JSON.parse(JSON.stringify(obj)); } -async function cleanUpPath(file, name, logger) { - logger.debug(`Cleaning up ${name}.`); +async function cleanUpPath(file, name, logger2) { + logger2.debug(`Cleaning up ${name}.`); try { await fs.promises.rm(file, { force: true, recursive: true }); } catch (e) { - logger.warning(`Failed to clean up ${name}: ${e}.`); + logger2.warning(`Failed to clean up ${name}: ${e}.`); } } -async function isBinaryAccessible(binary, logger) { +async function isBinaryAccessible(binary, logger2) { try { await io.which(binary, true); - logger.debug(`Found ${binary}.`); + logger2.debug(`Found ${binary}.`); return true; } catch (e) { - logger.debug(`Could not find ${binary}: ${e}`); + logger2.debug(`Could not find ${binary}: ${e}`); return false; } } @@ -148441,13 +148441,13 @@ var qualityCategoryMapping = { typescript: "javascript-typescript", kotlin: "java-kotlin" }; -function fixCodeQualityCategory(logger, category) { +function fixCodeQualityCategory(logger2, category) { if (category !== void 0 && isDefaultSetup() && category.startsWith("/language:")) { const language = category.substring("/language:".length); const mappedLanguage = qualityCategoryMapping[language]; if (mappedLanguage) { const newCategory = `/language:${mappedLanguage}`; - logger.info( + logger2.info( `Adjusted category for Code Quality from '${category}' to '${newCategory}'.` ); return newCategory; @@ -148599,12 +148599,12 @@ function getApiClient() { function getApiClientWithExternalAuth(apiDetails) { return createApiClientWithDetails(apiDetails, { allowExternal: true }); } -function getAuthorizationHeaderFor(logger, apiDetails, url2) { +function getAuthorizationHeaderFor(logger2, apiDetails, url2) { if (url2.startsWith(`${apiDetails.url}/`) || apiDetails.apiURL && url2.startsWith(`${apiDetails.apiURL}/`)) { - logger.debug(`Providing an authorization token.`); + logger2.debug(`Providing an authorization token.`); return `token ${apiDetails.auth}`; } - logger.debug(`Not using an authorization token.`); + logger2.debug(`Not using an authorization token.`); return void 0; } var cachedGitHubVersion = void 0; @@ -149038,7 +149038,7 @@ async function writeBaseDatabaseOidsFile(config, sourceRoot) { const baseDatabaseOidsFilePath = getBaseDatabaseOidsFilePath(config); await fs4.promises.writeFile(baseDatabaseOidsFilePath, gitFileOidsJson); } -async function readBaseDatabaseOidsFile(config, logger) { +async function readBaseDatabaseOidsFile(config, logger2) { const baseDatabaseOidsFilePath = getBaseDatabaseOidsFilePath(config); try { const contents = await fs4.promises.readFile( @@ -149047,27 +149047,27 @@ async function readBaseDatabaseOidsFile(config, logger) { ); return JSON.parse(contents); } catch (e) { - logger.error( + logger2.error( `Failed to read overlay-base file OIDs from ${baseDatabaseOidsFilePath}: ${e.message || e}` ); throw e; } } -async function writeOverlayChangesFile(config, sourceRoot, logger) { - const baseFileOids = await readBaseDatabaseOidsFile(config, logger); +async function writeOverlayChangesFile(config, sourceRoot, logger2) { + const baseFileOids = await readBaseDatabaseOidsFile(config, logger2); const overlayFileOids = await getFileOidsUnderPath(sourceRoot); const oidChangedFiles = computeChangedFiles(baseFileOids, overlayFileOids); - logger.info( + logger2.info( `Found ${oidChangedFiles.length} changed file(s) under ${sourceRoot} from OID comparison.` ); - const diffRangeFiles = await getDiffRangeFilePaths(sourceRoot, logger); + const diffRangeFiles = await getDiffRangeFilePaths(sourceRoot, logger2); const changedFiles = [.../* @__PURE__ */ new Set([...oidChangedFiles, ...diffRangeFiles])]; const changedFilesJson = JSON.stringify({ changes: changedFiles }); const overlayChangesFile = path4.join( getTemporaryDirectory(), "overlay-changes.json" ); - logger.debug( + logger2.debug( `Writing overlay changed files to ${overlayChangesFile}: ${changedFilesJson}` ); await fs4.promises.writeFile(overlayChangesFile, changedFilesJson); @@ -149087,10 +149087,10 @@ function computeChangedFiles(baseFileOids, overlayFileOids) { } return changes; } -async function getDiffRangeFilePaths(sourceRoot, logger) { +async function getDiffRangeFilePaths(sourceRoot, logger2) { const jsonFilePath = getDiffRangesJsonFilePath(); if (!fs4.existsSync(jsonFilePath)) { - logger.debug( + logger2.debug( `No diff ranges JSON file found at ${jsonFilePath}; skipping.` ); return []; @@ -149099,7 +149099,7 @@ async function getDiffRangeFilePaths(sourceRoot, logger) { try { contents = await fs4.promises.readFile(jsonFilePath, "utf8"); } catch (e) { - logger.warning( + logger2.warning( `Failed to read diff ranges JSON file at ${jsonFilePath}: ${e}` ); return []; @@ -149108,12 +149108,12 @@ async function getDiffRangeFilePaths(sourceRoot, logger) { try { diffRanges = JSON.parse(contents); } catch (e) { - logger.warning( + logger2.warning( `Failed to parse diff ranges JSON file at ${jsonFilePath}: ${e}` ); return []; } - logger.debug( + logger2.debug( `Read ${diffRanges.length} diff range(s) from ${jsonFilePath} for overlay changes.` ); const repoRoot = await getGitRoot(sourceRoot); @@ -149123,7 +149123,7 @@ async function getDiffRangeFilePaths(sourceRoot, logger) { "Cannot determine git root to convert diff range paths relative to source-root. Failing to avoid omitting files from the analysis." ); } - logger.warning( + logger2.warning( "Cannot determine git root; returning diff range paths as-is." ); return [...new Set(diffRanges.map((r) => r.path))]; @@ -149377,8 +149377,8 @@ var featureConfig = { }; var FEATURE_FLAGS_FILE_NAME = "cached-feature-flags.json"; var OfflineFeatures = class { - constructor(logger) { - this.logger = logger; + constructor(logger2) { + this.logger = logger2; } logger; async getEnabledDefaultCliVersions(_variant) { @@ -149480,12 +149480,12 @@ var OfflineFeatures = class { }; var Features = class extends OfflineFeatures { gitHubFeatureFlags; - constructor(repositoryNwo, tempDir, logger) { - super(logger); + constructor(repositoryNwo, tempDir, logger2) { + super(logger2); this.gitHubFeatureFlags = new GitHubFeatureFlags( repositoryNwo, path5.join(tempDir, FEATURE_FLAGS_FILE_NAME), - logger + logger2 ); } async getEnabledDefaultCliVersions(variant) { @@ -149522,10 +149522,10 @@ var Features = class extends OfflineFeatures { } }; var GitHubFeatureFlags = class { - constructor(repositoryNwo, featureFlagsFile, logger) { + constructor(repositoryNwo, featureFlagsFile, logger2) { this.repositoryNwo = repositoryNwo; this.featureFlagsFile = featureFlagsFile; - this.logger = logger; + this.logger = logger2; this.hasAccessedRemoteFeatureFlags = false; } repositoryNwo; @@ -149693,14 +149693,14 @@ var GitHubFeatureFlags = class { function supportsFeatureFlags(githubVariant) { return githubVariant === "GitHub.com" /* DOTCOM */ || githubVariant === "GitHub Enterprise Cloud with data residency" /* GHEC_DR */; } -function initFeatures(gitHubVersion, repositoryNwo, tempDir, logger) { +function initFeatures(gitHubVersion, repositoryNwo, tempDir, logger2) { if (!supportsFeatureFlags(gitHubVersion.type)) { - logger.debug( + logger2.debug( "Not running against github.com. Using default values for all features." ); - return new OfflineFeatures(logger); + return new OfflineFeatures(logger2); } else { - return new Features(repositoryNwo, tempDir, logger); + return new Features(repositoryNwo, tempDir, logger2); } } @@ -149740,7 +149740,7 @@ function isOnlyCodeScanningEnabled(analysisKinds) { function makeAnalysisKindUsageError(message) { return `The \`analysis-kinds\` input is experimental and for GitHub-internal use only. Its behaviour may change at any time or be removed entirely. ${message}`; } -async function getAnalysisKinds(logger, features, skipCache = false) { +async function getAnalysisKinds(logger2, features, skipCache = false) { if (!skipCache && cachedAnalysisKinds !== void 0) { return cachedAnalysisKinds; } @@ -149749,7 +149749,7 @@ async function getAnalysisKinds(logger, features, skipCache = false) { ); if (!isInTestMode() && !isDynamicWorkflow() && !isOnlyCodeScanningEnabled(analysisKinds)) { const codeQualityHint = analysisKinds.includes("code-quality" /* CodeQuality */) ? " If your intention is to use quality queries outside of Code Quality, use the `queries` input with `code-quality` instead." : ""; - logger.error( + logger2.error( makeAnalysisKindUsageError( `An analysis kind other than \`code-scanning\` was specified in a custom workflow. This is not supported and will become a fatal error in a future version of the CodeQL Action.${codeQualityHint}` ) @@ -149757,7 +149757,7 @@ async function getAnalysisKinds(logger, features, skipCache = false) { } const qualityQueriesInput = getOptionalInput("quality-queries"); if (qualityQueriesInput !== void 0) { - logger.warning( + logger2.warning( "The `quality-queries` input is deprecated and will be removed in a future version of the CodeQL Action. Use the `analysis-kinds` input to configure different analysis kinds instead." ); } @@ -149775,7 +149775,7 @@ async function getAnalysisKinds(logger, features, skipCache = false) { } } if (!isInTestMode() && analysisKinds.length > 1 && !await features.getValue("allow_multiple_analysis_kinds" /* AllowMultipleAnalysisKinds */)) { - logger.error( + logger2.error( makeAnalysisKindUsageError( "Specifying multiple values as input is no longer supported. Continuing with only `analysis-kinds: code-scanning`." ) @@ -149866,12 +149866,56 @@ var toolrunner3 = __toESM(require_toolrunner()); // src/cache.ts var fs6 = __toESM(require("fs")); var path6 = __toESM(require("path")); + +// src/logging.ts +var core6 = __toESM(require_core()); +function getActionsLogger() { + return { + debug: core6.debug, + info: core6.info, + warning: core6.warning, + error: core6.error, + isDebug: core6.isDebug, + startGroup: core6.startGroup, + endGroup: core6.endGroup + }; +} +function withGroup(groupName, f) { + core6.startGroup(groupName); + try { + return f(); + } finally { + core6.endGroup(); + } +} +async function withGroupAsync(groupName, f) { + core6.startGroup(groupName); + try { + return await f(); + } finally { + core6.endGroup(); + } +} +function formatDuration(durationMs) { + if (durationMs < 1e3) { + return `${durationMs}ms`; + } + if (durationMs < 60 * 1e3) { + return `${(durationMs / 1e3).toFixed(1)}s`; + } + const minutes = Math.floor(durationMs / (60 * 1e3)); + const seconds = Math.floor(durationMs % (60 * 1e3) / 1e3); + return `${minutes}m${seconds}s`; +} + +// src/cache.ts var COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; var CommandCacheKey = { Version: "version", ResolveLanguages: "resolveLanguages" }; var inMemoryCache = /* @__PURE__ */ new Map(); +var logger = getActionsLogger(); function getCommandCacheFilePath() { return path6.join(getTemporaryDirectory(), COMMAND_CACHE_FILENAME); } @@ -149885,14 +149929,16 @@ function readCommandCacheFile() { if (isObject(parsed)) { return parsed; } - } catch { + } catch (e) { + logger.warning(`Failed to read or parse command cache file: ${e}`); } return {}; } function writeCommandCacheFile(data) { try { fs6.writeFileSync(getCommandCacheFilePath(), JSON.stringify(data)); - } catch { + } catch (e) { + logger.warning(`Failed to write command cache file: ${e}`); } } function cacheCommandOutput(key, cmd, output) { @@ -150176,10 +150222,10 @@ var core8 = __toESM(require_core()); // src/caching-utils.ts var crypto2 = __toESM(require("crypto")); -var core6 = __toESM(require_core()); -async function getTotalCacheSize(paths, logger, quiet = false) { +var core7 = __toESM(require_core()); +async function getTotalCacheSize(paths, logger2, quiet = false) { const sizes = await Promise.all( - paths.map((cacheDir2) => tryGetFolderBytes(cacheDir2, logger, quiet)) + paths.map((cacheDir2) => tryGetFolderBytes(cacheDir2, logger2, quiet)) ); return sizes.map((a) => a || 0).reduce((a, b) => a + b, 0); } @@ -150205,7 +150251,7 @@ function getCachingKind(input) { case "restore": return "restore" /* Restore */; default: - core6.warning( + core7.warning( `Unrecognized 'dependency-caching' input: ${input}. Defaulting to 'none'.` ); return "none" /* None */; @@ -150309,7 +150355,7 @@ var repositoryPropertyParsers = { ["github-codeql-extra-queries" /* EXTRA_QUERIES */]: stringProperty, ["github-codeql-file-coverage-on-prs" /* FILE_COVERAGE_ON_PRS */]: booleanProperty }; -async function loadPropertiesFromApi(logger, repositoryNwo) { +async function loadPropertiesFromApi(logger2, repositoryNwo) { try { const response = await getRepositoryProperties(repositoryNwo); const remoteProperties = response.data; @@ -150318,7 +150364,7 @@ async function loadPropertiesFromApi(logger, repositoryNwo) { `Expected repository properties API to return an array, but got: ${JSON.stringify(response.data)}` ); } - logger.debug( + logger2.debug( `Retrieved ${remoteProperties.length} repository properties: ${remoteProperties.map((p) => p.property_name).join(", ")}` ); const properties = {}; @@ -150330,26 +150376,26 @@ async function loadPropertiesFromApi(logger, repositoryNwo) { ); } if (isKnownPropertyName(property.property_name)) { - setProperty(properties, property.property_name, property.value, logger); + setProperty(properties, property.property_name, property.value, logger2); } else if (property.property_name.startsWith(GITHUB_CODEQL_PROPERTY_PREFIX) && !isDynamicWorkflow()) { unrecognisedProperties.push(property.property_name); } } if (Object.keys(properties).length === 0) { - logger.debug("No known repository properties were found."); + logger2.debug("No known repository properties were found."); } else { - logger.debug( + logger2.debug( "Loaded the following values for the repository properties:" ); for (const [property, value] of Object.entries(properties).sort( ([nameA], [nameB]) => nameA.localeCompare(nameB) )) { - logger.debug(` ${property}: ${value}`); + logger2.debug(` ${property}: ${value}`); } } if (unrecognisedProperties.length > 0) { const unrecognisedPropertyList = unrecognisedProperties.map((name) => `'${name}'`).join(", "); - logger.warning( + logger2.warning( `Found repository properties (${unrecognisedPropertyList}), which look like CodeQL Action repository properties, but which are not understood by this version of the CodeQL Action. Do you need to update to a newer version?` ); } @@ -150360,19 +150406,19 @@ async function loadPropertiesFromApi(logger, repositoryNwo) { ); } } -function setProperty(properties, name, value, logger) { +function setProperty(properties, name, value, logger2) { const propertyOptions = repositoryPropertyParsers[name]; if (propertyOptions.validate(value)) { - properties[name] = propertyOptions.parse(name, value, logger); + properties[name] = propertyOptions.parse(name, value, logger2); } else { throw new Error( `Unexpected value for repository property '${name}' (${typeof value}), got: ${JSON.stringify(value)}` ); } } -function parseBooleanRepositoryProperty(name, value, logger) { +function parseBooleanRepositoryProperty(name, value, logger2) { if (value !== "true" && value !== "false") { - logger.warning( + logger2.warning( `Repository property '${name}' has unexpected value '${value}'. Expected 'true' or 'false'. Defaulting to false.` ); } @@ -150534,14 +150580,14 @@ function parseQueriesFromInput(rawQueriesInput, queriesInputCombines, errorToThr } return trimmedInput.split(",").map((query) => ({ uses: query.trim() })); } -function combineQueries(logger, config, augmentationProperties) { +function combineQueries(logger2, config, augmentationProperties) { const result = []; if (augmentationProperties.repoPropertyQueries?.input) { - logger.info( + logger2.info( `Found query configuration in the repository properties (${"github-codeql-extra-queries" /* EXTRA_QUERIES */}): ${augmentationProperties.repoPropertyQueries.input.map((q) => q.uses).join(", ")}` ); if (!augmentationProperties.repoPropertyQueries.combines) { - logger.info( + logger2.info( `The queries configured in the repository properties don't allow combining with other query settings. Any queries configured elsewhere will be ignored.` ); return augmentationProperties.repoPropertyQueries.input; @@ -150561,14 +150607,14 @@ function combineQueries(logger, config, augmentationProperties) { } return result; } -function generateCodeScanningConfig(logger, originalUserInput, augmentationProperties) { +function generateCodeScanningConfig(logger2, originalUserInput, augmentationProperties) { const augmentedConfig = cloneObject(originalUserInput); augmentedConfig.queries = combineQueries( - logger, + logger2, augmentedConfig, augmentationProperties ); - logger.debug( + logger2.debug( `Combined queries: ${augmentedConfig.queries?.map((q) => q.uses).join(",")}` ); if (augmentedConfig.queries?.length === 0) { @@ -150595,7 +150641,7 @@ function generateCodeScanningConfig(logger, originalUserInput, augmentationPrope } return augmentedConfig; } -function parseUserConfig(logger, pathInput, contents, validateConfig) { +function parseUserConfig(logger2, pathInput, contents, validateConfig) { try { const schema = ( // eslint-disable-next-line @typescript-eslint/no-require-imports @@ -150606,7 +150652,7 @@ function parseUserConfig(logger, pathInput, contents, validateConfig) { const result = new jsonschema.Validator().validate(doc, schema); if (result.errors.length > 0) { for (const error3 of result.errors) { - logger.error(error3.stack); + logger2.error(error3.stack); } throw new ConfigurationError( getInvalidConfigFileMessage( @@ -150630,49 +150676,6 @@ function parseUserConfig(logger, pathInput, contents, validateConfig) { // src/diagnostics.ts var import_fs = require("fs"); var import_path = __toESM(require("path")); - -// src/logging.ts -var core7 = __toESM(require_core()); -function getActionsLogger() { - return { - debug: core7.debug, - info: core7.info, - warning: core7.warning, - error: core7.error, - isDebug: core7.isDebug, - startGroup: core7.startGroup, - endGroup: core7.endGroup - }; -} -function withGroup(groupName, f) { - core7.startGroup(groupName); - try { - return f(); - } finally { - core7.endGroup(); - } -} -async function withGroupAsync(groupName, f) { - core7.startGroup(groupName); - try { - return await f(); - } finally { - core7.endGroup(); - } -} -function formatDuration(durationMs) { - if (durationMs < 1e3) { - return `${durationMs}ms`; - } - if (durationMs < 60 * 1e3) { - return `${(durationMs / 1e3).toFixed(1)}s`; - } - const minutes = Math.floor(durationMs / (60 * 1e3)); - const seconds = Math.floor(durationMs % (60 * 1e3) / 1e3); - return `${minutes}m${seconds}s`; -} - -// src/diagnostics.ts var unwrittenDiagnostics = []; var unwrittenDefaultLanguageDiagnostics = []; var diagnosticCounter = 0; @@ -150684,12 +150687,12 @@ function makeDiagnostic(id, name, data = void 0) { }; } function addDiagnostic(config, language, diagnostic) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); const databasePath = language ? getCodeQLDatabasePath(config, language) : config.dbLocation; if ((0, import_fs.existsSync)(databasePath)) { writeDiagnostic(config, language, diagnostic); } else { - logger.debug( + logger2.debug( `Writing a diagnostic for ${language}, but the database at ${databasePath} does not exist yet.` ); unwrittenDiagnostics.push({ diagnostic, language }); @@ -150709,7 +150712,7 @@ function addNoLanguageDiagnostic(config, diagnostic) { } } function writeDiagnostic(config, language, diagnostic) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); const databasePath = language ? getCodeQLDatabasePath(config, language) : config.dbLocation; const diagnosticsPath = import_path.default.resolve( databasePath, @@ -150729,26 +150732,26 @@ function writeDiagnostic(config, language, diagnostic) { ); (0, import_fs.writeFileSync)(jsonPath, JSON.stringify(diagnostic)); } catch (err) { - logger.warning(`Unable to write diagnostic message to database: ${err}`); - logger.debug(JSON.stringify(diagnostic)); + logger2.warning(`Unable to write diagnostic message to database: ${err}`); + logger2.debug(JSON.stringify(diagnostic)); } } function logUnwrittenDiagnostics() { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); const num = unwrittenDiagnostics.length; if (num > 0) { - logger.warning( + logger2.warning( `${num} diagnostic(s) could not be written to the database and will not appear on the Tool Status Page.` ); for (const unwritten of unwrittenDiagnostics) { - logger.debug(JSON.stringify(unwritten.diagnostic)); + logger2.debug(JSON.stringify(unwritten.diagnostic)); } } } function flushDiagnostics(config) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); const diagnosticsCount = unwrittenDiagnostics.length + unwrittenDefaultLanguageDiagnostics.length; - logger.debug(`Writing ${diagnosticsCount} diagnostic(s) to database.`); + logger2.debug(`Writing ${diagnosticsCount} diagnostic(s) to database.`); for (const unwritten of unwrittenDiagnostics) { writeDiagnostic(config, unwritten.language, unwritten.diagnostic); } @@ -150771,7 +150774,7 @@ function makeTelemetryDiagnostic(id, name, attributes) { // src/diff-informed-analysis-utils.ts var fs7 = __toESM(require("fs")); -async function getDiffInformedAnalysisBranches(codeql, features, logger) { +async function getDiffInformedAnalysisBranches(codeql, features, logger2) { if (!await features.getValue("diff_informed_queries" /* DiffInformedQueries */, codeql)) { return void 0; } @@ -150781,18 +150784,18 @@ async function getDiffInformedAnalysisBranches(codeql, features, logger) { } const branches = getPullRequestBranches(); if (!branches) { - logger.info( + logger2.info( "Not performing diff-informed analysis because we are not analyzing a pull request." ); } return branches; } -async function prepareDiffInformedAnalysis(codeql, features, logger) { +async function prepareDiffInformedAnalysis(codeql, features, logger2) { let branches; try { - branches = await getDiffInformedAnalysisBranches(codeql, features, logger); + branches = await getDiffInformedAnalysisBranches(codeql, features, logger2); } catch (e) { - logger.warning( + logger2.warning( `Failed to determine branch information for diff-informed analysis: ${getErrorMessage(e)}` ); return false; @@ -150801,57 +150804,57 @@ async function prepareDiffInformedAnalysis(codeql, features, logger) { return false; } try { - return await computeAndPersistDiffRanges(branches, logger); + return await computeAndPersistDiffRanges(branches, logger2); } catch (e) { - logger.warning( + logger2.warning( `Failed to compute diff-informed analysis ranges: ${getErrorMessage(e)}` ); return false; } } -function writeDiffRangesJsonFile(logger, ranges) { +function writeDiffRangesJsonFile(logger2, ranges) { const jsonContents = JSON.stringify(ranges, null, 2); const jsonFilePath = getDiffRangesJsonFilePath(); fs7.writeFileSync(jsonFilePath, jsonContents); - logger.debug( + logger2.debug( `Wrote pr-diff-range JSON file to ${jsonFilePath}: ${jsonContents}` ); } -function readDiffRangesJsonFile(logger) { +function readDiffRangesJsonFile(logger2) { const jsonFilePath = getDiffRangesJsonFilePath(); if (!fs7.existsSync(jsonFilePath)) { - logger.debug(`Diff ranges JSON file does not exist at ${jsonFilePath}`); + logger2.debug(`Diff ranges JSON file does not exist at ${jsonFilePath}`); return void 0; } const jsonContents = fs7.readFileSync(jsonFilePath, "utf8"); - logger.debug( + logger2.debug( `Read pr-diff-range JSON file from ${jsonFilePath}: ${jsonContents}` ); try { return JSON.parse(jsonContents); } catch (e) { - logger.warning( + logger2.warning( `Failed to parse diff ranges JSON file at ${jsonFilePath}: ${e}` ); return void 0; } } -async function getPullRequestEditedDiffRanges(branches, logger) { - const fileDiffs = await getFileDiffsWithBasehead(branches, logger); +async function getPullRequestEditedDiffRanges(branches, logger2) { + const fileDiffs = await getFileDiffsWithBasehead(branches, logger2); if (fileDiffs === void 0) { return void 0; } if (fileDiffs.length >= 300) { - logger.warning( + logger2.warning( `Cannot retrieve the full diff because there are too many (${fileDiffs.length}) changed files in the pull request.` ); return void 0; } const results = []; for (const filediff of fileDiffs) { - const diffRanges = getDiffRanges(filediff, logger); + const diffRanges = getDiffRanges(filediff, logger2); if (diffRanges === void 0) { return void 0; } @@ -150859,20 +150862,20 @@ async function getPullRequestEditedDiffRanges(branches, logger) { } return results; } -async function computeAndPersistDiffRanges(branches, logger) { - logger.info("Computing PR diff ranges..."); - const ranges = await getPullRequestEditedDiffRanges(branches, logger); +async function computeAndPersistDiffRanges(branches, logger2) { + logger2.info("Computing PR diff ranges..."); + const ranges = await getPullRequestEditedDiffRanges(branches, logger2); if (ranges === void 0) { return false; } - writeDiffRangesJsonFile(logger, ranges); + writeDiffRangesJsonFile(logger2, ranges); const distinctFiles = new Set(ranges.map((r) => r.path)).size; - logger.info( + logger2.info( `Persisted ${ranges.length} diff range(s) across ${distinctFiles} file(s).` ); return true; } -async function getFileDiffsWithBasehead(branches, logger) { +async function getFileDiffsWithBasehead(branches, logger2) { const repositoryNwo = getRepositoryNwoFromEnv( "CODE_SCANNING_REPOSITORY", "GITHUB_REPOSITORY" @@ -150887,15 +150890,15 @@ async function getFileDiffsWithBasehead(branches, logger) { per_page: 1 } ); - logger.debug( + logger2.debug( `Response from compareCommitsWithBasehead(${basehead}): ${JSON.stringify(response, null, 2)}` ); return response.data.files; } catch (error3) { if (error3.status) { - logger.warning(`Error retrieving diff ${basehead}: ${error3.message}`); - logger.debug( + logger2.warning(`Error retrieving diff ${basehead}: ${error3.message}`); + logger2.debug( `Error running compareCommitsWithBasehead(${basehead}): Request: ${JSON.stringify(error3.request, null, 2)} Error Response: ${JSON.stringify(error3.response, null, 2)}` @@ -150906,7 +150909,7 @@ Error Response: ${JSON.stringify(error3.response, null, 2)}` } } } -function getDiffRanges(fileDiff, logger) { +function getDiffRanges(fileDiff, logger2) { if (fileDiff.patch === void 0) { if (fileDiff.changes === 0) { return []; @@ -150946,7 +150949,7 @@ function getDiffRanges(fileDiff, logger) { if (diffLine.startsWith("@@ ")) { const match = diffLine.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/); if (match === null) { - logger.warning( + logger2.warning( `Cannot parse diff hunk header for ${fileDiff.filename}: ${diffLine}` ); return void 0; @@ -151100,23 +151103,23 @@ function createOverlayStatus(attributes, checkRunId) { job }; } -async function shouldSkipOverlayAnalysis(codeql, languages, diskUsage, logger) { - const status = await getOverlayStatus(codeql, languages, diskUsage, logger); +async function shouldSkipOverlayAnalysis(codeql, languages, diskUsage, logger2) { + const status = await getOverlayStatus(codeql, languages, diskUsage, logger2); if (status === void 0) { return false; } if (status.attemptedToBuildOverlayBaseDatabase && !status.builtOverlayBaseDatabase) { - logger.debug( + logger2.debug( "Cached overlay status indicates that building an overlay base database was unsuccessful." ); return true; } - logger.debug( + logger2.debug( "Cached overlay status does not indicate a previous unsuccessful attempt to build an overlay base database." ); return false; } -async function getOverlayStatus(codeql, languages, diskUsage, logger) { +async function getOverlayStatus(codeql, languages, diskUsage, logger2) { const cacheKey3 = await getCacheKey(codeql, languages, diskUsage); const statusFile = getStatusFilePath(languages); try { @@ -151125,15 +151128,15 @@ async function getOverlayStatus(codeql, languages, diskUsage, logger) { MAX_CACHE_OPERATION_MS, actionsCache.restoreCache([statusFile], cacheKey3), () => { - logger.warning("Timed out restoring overlay status from cache."); + logger2.warning("Timed out restoring overlay status from cache."); } ); if (foundKey === void 0) { - logger.debug("No overlay status found in Actions cache."); + logger2.debug("No overlay status found in Actions cache."); return void 0; } if (!fs8.existsSync(statusFile)) { - logger.debug( + logger2.debug( "Overlay status cache entry found but status file is missing." ); return void 0; @@ -151141,20 +151144,20 @@ async function getOverlayStatus(codeql, languages, diskUsage, logger) { const contents = await fs8.promises.readFile(statusFile, "utf-8"); const parsed = JSON.parse(contents); if (!isObject(parsed) || typeof parsed["attemptedToBuildOverlayBaseDatabase"] !== "boolean" || typeof parsed["builtOverlayBaseDatabase"] !== "boolean") { - logger.debug( + logger2.debug( "Ignoring overlay status cache entry with unexpected format." ); return void 0; } return parsed; } catch (error3) { - logger.warning( + logger2.warning( `Failed to restore overlay status from cache: ${getErrorMessage(error3)}` ); return void 0; } } -async function saveOverlayStatus(codeql, languages, diskUsage, status, logger) { +async function saveOverlayStatus(codeql, languages, diskUsage, status, logger2) { const cacheKey3 = await getCacheKey(codeql, languages, diskUsage); const statusFile = getStatusFilePath(languages); try { @@ -151164,16 +151167,16 @@ async function saveOverlayStatus(codeql, languages, diskUsage, status, logger) { MAX_CACHE_OPERATION_MS, actionsCache.saveCache([statusFile], cacheKey3), () => { - logger.warning("Timed out saving overlay status to cache."); + logger2.warning("Timed out saving overlay status to cache."); } ); if (cacheId === void 0) { return false; } - logger.debug(`Saved overlay status to Actions cache with key ${cacheKey3}`); + logger2.debug(`Saved overlay status to Actions cache with key ${cacheKey3}`); return true; } catch (error3) { - logger.warning( + logger2.warning( `Failed to save overlay status to cache: ${getErrorMessage(error3)}` ); return false; @@ -151192,14 +151195,14 @@ var CACHE_VERSION = 1; var CODEQL_TRAP_CACHE_PREFIX = "codeql-trap"; var MINIMUM_CACHE_MB_TO_UPLOAD = 10; var MAX_CACHE_OPERATION_MS2 = 12e4; -async function downloadTrapCaches(codeql, languages, logger) { +async function downloadTrapCaches(codeql, languages, logger2) { const result = {}; const languagesSupportingCaching = await getLanguagesSupportingCaching( codeql, languages, - logger + logger2 ); - logger.info( + logger2.info( `Found ${languagesSupportingCaching.length} languages that support TRAP caching` ); if (languagesSupportingCaching.length === 0) return result; @@ -151213,7 +151216,7 @@ async function downloadTrapCaches(codeql, languages, logger) { result[language] = cacheDir2; } if (await isAnalyzingDefaultBranch()) { - logger.info( + logger2.info( "Analyzing default branch. Skipping downloading of TRAP caches." ); return result; @@ -151228,7 +151231,7 @@ async function downloadTrapCaches(codeql, languages, logger) { const cacheDir2 = result[language]; if (cacheDir2 === void 0) continue; const preferredKey = await cacheKey(codeql, language, baseSha); - logger.info( + logger2.info( `Looking in Actions cache for TRAP cache with key ${preferredKey}` ); const found = await waitForResultWithTimeLimit( @@ -151238,32 +151241,32 @@ async function downloadTrapCaches(codeql, languages, logger) { await cachePrefix(codeql, language) ]), () => { - logger.info( + logger2.info( `Timed out downloading cache for ${language}, will continue without it` ); } ); if (found === void 0) { - logger.info(`No TRAP cache found in Actions cache for ${language}`); + logger2.info(`No TRAP cache found in Actions cache for ${language}`); delete result[language]; } } return result; } -async function uploadTrapCaches(codeql, config, logger) { +async function uploadTrapCaches(codeql, config, logger2) { if (!await isAnalyzingDefaultBranch()) return false; for (const language of config.languages) { const cacheDir2 = config.trapCaches[language]; if (cacheDir2 === void 0) continue; - const trapFolderSize = await tryGetFolderBytes(cacheDir2, logger); + const trapFolderSize = await tryGetFolderBytes(cacheDir2, logger2); if (trapFolderSize === void 0) { - logger.info( + logger2.info( `Skipping upload of TRAP cache for ${language} as we couldn't determine its size` ); continue; } if (trapFolderSize < MINIMUM_CACHE_MB_TO_UPLOAD * 1048576) { - logger.info( + logger2.info( `Skipping upload of TRAP cache for ${language} as it is too small` ); continue; @@ -151273,12 +151276,12 @@ async function uploadTrapCaches(codeql, config, logger) { language, process.env.GITHUB_SHA || "unknown" ); - logger.info(`Uploading TRAP cache to Actions cache with key ${key}`); + logger2.info(`Uploading TRAP cache to Actions cache with key ${key}`); await waitForResultWithTimeLimit( MAX_CACHE_OPERATION_MS2, actionsCache2.saveCache([cacheDir2], key), () => { - logger.info( + logger2.info( `Timed out waiting for TRAP cache for ${language} to upload, will continue without uploading` ); } @@ -151286,13 +151289,13 @@ async function uploadTrapCaches(codeql, config, logger) { } return true; } -async function cleanupTrapCaches(config, features, logger) { +async function cleanupTrapCaches(config, features, logger2) { if (!await features.getValue("cleanup_trap_caches" /* CleanupTrapCaches */)) { return { trap_cache_cleanup_skipped_because: "feature disabled" }; } - logger.warning( + logger2.warning( "TRAP cache cleanup is deprecated and will be removed in May 2026. We recommend instead disabling TRAP caching by passing the `trap-caching: false` input to the `init` Action." ); if (!await isAnalyzingDefaultBranch()) { @@ -151311,19 +151314,19 @@ async function cleanupTrapCaches(config, features, logger) { const cachesToRemove = await getTrapCachesForLanguage( allCaches, language, - logger + logger2 ); cachesToRemove.sort((a, b) => a.created_at.localeCompare(b.created_at)); const mostRecentCache = cachesToRemove.pop(); - logger.debug( + logger2.debug( `Keeping most recent TRAP cache (${JSON.stringify(mostRecentCache)})` ); if (cachesToRemove.length === 0) { - logger.info(`No TRAP caches to clean up for ${language}.`); + logger2.info(`No TRAP caches to clean up for ${language}.`); continue; } for (const cache of cachesToRemove) { - logger.debug(`Cleaning up TRAP cache (${JSON.stringify(cache)})`); + logger2.debug(`Cleaning up TRAP cache (${JSON.stringify(cache)})`); await deleteActionsCache(cache.id); } const bytesCleanedUp = cachesToRemove.reduce( @@ -151332,7 +151335,7 @@ async function cleanupTrapCaches(config, features, logger) { ); totalBytesCleanedUp += bytesCleanedUp; const megabytesCleanedUp = (bytesCleanedUp / (1024 * 1024)).toFixed(2); - logger.info( + logger2.info( `Cleaned up ${megabytesCleanedUp} MiB of old TRAP caches for ${language}.` ); } @@ -151340,17 +151343,17 @@ async function cleanupTrapCaches(config, features, logger) { return { trap_cache_cleanup_size_bytes: totalBytesCleanedUp }; } catch (e) { if (asHTTPError(e)?.status === 403) { - logger.warning( + logger2.warning( `Could not cleanup TRAP caches as the token did not have the required permissions. To clean up TRAP caches, ensure the token has the "actions:write" permission. See ${"https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs" /* ASSIGNING_PERMISSIONS_TO_JOBS */} for more information.` ); } else { - logger.info(`Failed to cleanup TRAP caches, continuing. Details: ${e}`); + logger2.info(`Failed to cleanup TRAP caches, continuing. Details: ${e}`); } return { trap_cache_cleanup_error: getErrorMessage(e) }; } } -async function getTrapCachesForLanguage(allCaches, language, logger) { - logger.debug(`Listing TRAP caches for ${language}`); +async function getTrapCachesForLanguage(allCaches, language, logger2) { + logger2.debug(`Listing TRAP caches for ${language}`); for (const cache of allCaches) { if (!cache.created_at || !cache.id || !cache.key || !cache.size_in_bytes) { throw new Error( @@ -151362,19 +151365,19 @@ async function getTrapCachesForLanguage(allCaches, language, logger) { return cache.key?.includes(`-${language}-`); }); } -async function getLanguagesSupportingCaching(codeql, languages, logger) { +async function getLanguagesSupportingCaching(codeql, languages, logger2) { const result = []; const resolveResult = await codeql.resolveLanguages(); outer: for (const lang of languages) { const extractorsForLanguage = resolveResult.extractors[lang]; if (extractorsForLanguage === void 0) { - logger.info( + logger2.info( `${lang} does not support TRAP caching (couldn't find an extractor)` ); continue; } if (extractorsForLanguage.length !== 1) { - logger.info( + logger2.info( `${lang} does not support TRAP caching (found multiple extractors)` ); continue; @@ -151382,14 +151385,14 @@ async function getLanguagesSupportingCaching(codeql, languages, logger) { const extractor = extractorsForLanguage[0]; const trapCacheOptions = extractor.extractor_options?.trap?.properties?.cache?.properties; if (trapCacheOptions === void 0) { - logger.info( + logger2.info( `${lang} does not support TRAP caching (missing option group)` ); continue; } for (const requiredOpt of ["dir", "bound", "write"]) { if (!(requiredOpt in trapCacheOptions)) { - logger.info( + logger2.info( `${lang} does not support TRAP caching (missing ${requiredOpt} option)` ); continue outer; @@ -151413,13 +151416,13 @@ var OVERLAY_MINIMUM_AVAILABLE_DISK_SPACE_V2_MB = 14e3; var OVERLAY_MINIMUM_AVAILABLE_DISK_SPACE_V2_BYTES = OVERLAY_MINIMUM_AVAILABLE_DISK_SPACE_V2_MB * 1e6; var OVERLAY_MINIMUM_MEMORY_MB = 5 * 1024; var CODEQL_VERSION_REDUCED_OVERLAY_MEMORY_USAGE = "2.24.3"; -async function getSupportedLanguageMap(codeql, logger) { +async function getSupportedLanguageMap(codeql, logger2) { const resolveSupportedLanguagesUsingCli = await codeql.supportsFeature( "builtinExtractorsSpecifyDefaultQueries" /* BuiltinExtractorsSpecifyDefaultQueries */ ); const resolveResult = await codeql.resolveLanguages(); if (resolveSupportedLanguagesUsingCli) { - logger.debug( + logger2.debug( `The CodeQL CLI supports the following languages: ${Object.keys(resolveResult.extractors).join(", ")}` ); } @@ -151442,33 +151445,33 @@ function hasActionsWorkflows(sourceRoot) { const stats = fs10.lstatSync(workflowsPath, { throwIfNoEntry: false }); return stats !== void 0 && stats.isDirectory() && fs10.readdirSync(workflowsPath).length > 0; } -async function getRawLanguagesInRepo(repository, sourceRoot, logger) { - logger.debug( +async function getRawLanguagesInRepo(repository, sourceRoot, logger2) { + logger2.debug( `Automatically detecting languages (${repository.owner}/${repository.repo})` ); const response = await getApiClient().rest.repos.listLanguages({ owner: repository.owner, repo: repository.repo }); - logger.debug(`Languages API response: ${JSON.stringify(response)}`); + logger2.debug(`Languages API response: ${JSON.stringify(response)}`); const result = Object.keys(response.data).map( (language) => language.trim().toLowerCase() ); if (hasActionsWorkflows(sourceRoot)) { - logger.debug(`Found a .github/workflows directory`); + logger2.debug(`Found a .github/workflows directory`); result.push("actions"); } - logger.debug(`Raw languages in repository: ${result.join(", ")}`); + logger2.debug(`Raw languages in repository: ${result.join(", ")}`); return result; } -async function getLanguages(codeql, languagesInput, repository, sourceRoot, logger) { +async function getLanguages(codeql, languagesInput, repository, sourceRoot, logger2) { const { rawLanguages, autodetected } = await getRawLanguages( languagesInput, repository, sourceRoot, - logger + logger2 ); - const languageMap = await getSupportedLanguageMap(codeql, logger); + const languageMap = await getSupportedLanguageMap(codeql, logger2); const languagesSet = /* @__PURE__ */ new Set(); const unknownLanguages = []; for (const language of rawLanguages) { @@ -151489,22 +151492,22 @@ async function getLanguages(codeql, languagesInput, repository, sourceRoot, logg throw new ConfigurationError(getNoLanguagesError()); } if (autodetected) { - logger.info(`Autodetected languages: ${languages.join(", ")}`); + logger2.info(`Autodetected languages: ${languages.join(", ")}`); } else { - logger.info(`Languages from configuration: ${languages.join(", ")}`); + logger2.info(`Languages from configuration: ${languages.join(", ")}`); } return languages; } function getRawLanguagesNoAutodetect(languagesInput) { return (languagesInput || "").split(",").map((x) => x.trim().toLowerCase()).filter((x) => x.length > 0); } -async function getRawLanguages(languagesInput, repository, sourceRoot, logger) { +async function getRawLanguages(languagesInput, repository, sourceRoot, logger2) { const languagesFromInput = getRawLanguagesNoAutodetect(languagesInput); if (languagesFromInput.length > 0) { return { rawLanguages: languagesFromInput, autodetected: false }; } return { - rawLanguages: await getRawLanguagesInRepo(repository, sourceRoot, logger), + rawLanguages: await getRawLanguagesInRepo(repository, sourceRoot, logger2), autodetected: true }; } @@ -151526,7 +151529,7 @@ async function initActionState({ features, repositoryProperties, analysisKinds, - logger, + logger: logger2, enableFileCoverageInformation }, userConfig) { const languages = await getLanguages( @@ -151534,13 +151537,13 @@ async function initActionState({ languagesInput, repository, sourceRoot, - logger + logger2 ); const buildMode = await parseBuildModeInput( buildModeInput, languages, features, - logger + logger2 ); const augmentationProperties = await calculateAugmentation( packsInput, @@ -151549,7 +151552,7 @@ async function initActionState({ languages ); if (analysisKinds.length === 1 && analysisKinds.includes("code-quality" /* CodeQuality */) && augmentationProperties.repoPropertyQueries.input) { - logger.info( + logger2.info( `Ignoring queries configured in the repository properties, because query customisations are not supported for Code Quality analyses.` ); augmentationProperties.repoPropertyQueries = { @@ -151558,7 +151561,7 @@ async function initActionState({ }; } const computedConfig = generateCodeScanningConfig( - logger, + logger2, userConfig, augmentationProperties ); @@ -151588,13 +151591,13 @@ async function initActionState({ enableFileCoverageInformation }; } -async function downloadCacheWithTime(codeQL, languages, logger) { +async function downloadCacheWithTime(codeQL, languages, logger2) { const start = import_perf_hooks.performance.now(); - const trapCaches = await downloadTrapCaches(codeQL, languages, logger); + const trapCaches = await downloadTrapCaches(codeQL, languages, logger2); const trapCacheDownloadTime = import_perf_hooks.performance.now() - start; return { trapCaches, trapCacheDownloadTime }; } -async function loadUserConfig(logger, configFile, workspacePath, apiDetails, tempDir, validateConfig) { +async function loadUserConfig(logger2, configFile, workspacePath, apiDetails, tempDir, validateConfig) { if (isLocal(configFile)) { if (configFile !== userConfigFromActionPath(tempDir)) { configFile = path11.resolve(workspacePath, configFile); @@ -151604,10 +151607,10 @@ async function loadUserConfig(logger, configFile, workspacePath, apiDetails, tem ); } } - return getLocalConfig(logger, configFile, validateConfig); + return getLocalConfig(logger2, configFile, validateConfig); } else { return await getRemoteConfig( - logger, + logger2, configFile, apiDetails, validateConfig @@ -151657,53 +151660,53 @@ async function checkOverlayAnalysisFeatureEnabled(features, codeql, languages, c } return new Success(void 0); } -function runnerHasSufficientDiskSpace(diskUsage, logger, useV2ResourceChecks) { +function runnerHasSufficientDiskSpace(diskUsage, logger2, useV2ResourceChecks) { const minimumDiskSpaceBytes = useV2ResourceChecks ? OVERLAY_MINIMUM_AVAILABLE_DISK_SPACE_V2_BYTES : OVERLAY_MINIMUM_AVAILABLE_DISK_SPACE_BYTES; if (diskUsage.numAvailableBytes < minimumDiskSpaceBytes) { const diskSpaceMb = Math.round(diskUsage.numAvailableBytes / 1e6); const minimumDiskSpaceMb = Math.round(minimumDiskSpaceBytes / 1e6); - logger.info( + logger2.info( `Setting overlay database mode to ${"none" /* None */} due to insufficient disk space (${diskSpaceMb} MB, needed ${minimumDiskSpaceMb} MB).` ); return false; } return true; } -async function runnerHasSufficientMemory(codeql, ramInput, logger) { +async function runnerHasSufficientMemory(codeql, ramInput, logger2) { if (await codeQlVersionAtLeast( codeql, CODEQL_VERSION_REDUCED_OVERLAY_MEMORY_USAGE )) { - logger.debug( + logger2.debug( `Skipping memory check for overlay analysis because CodeQL version is at least ${CODEQL_VERSION_REDUCED_OVERLAY_MEMORY_USAGE}.` ); return true; } - const memoryFlagValue = getCodeQLMemoryLimit(ramInput, logger); + const memoryFlagValue = getCodeQLMemoryLimit(ramInput, logger2); if (memoryFlagValue < OVERLAY_MINIMUM_MEMORY_MB) { - logger.info( + logger2.info( `Setting overlay database mode to ${"none" /* None */} due to insufficient memory for CodeQL analysis (${memoryFlagValue} MB, needed ${OVERLAY_MINIMUM_MEMORY_MB} MB).` ); return false; } - logger.debug( + logger2.debug( `Memory available for CodeQL analysis is ${memoryFlagValue} MB, which is above the minimum of ${OVERLAY_MINIMUM_MEMORY_MB} MB.` ); return true; } -async function checkRunnerResources(codeql, diskUsage, ramInput, logger, useV2ResourceChecks) { - if (!runnerHasSufficientDiskSpace(diskUsage, logger, useV2ResourceChecks)) { +async function checkRunnerResources(codeql, diskUsage, ramInput, logger2, useV2ResourceChecks) { + if (!runnerHasSufficientDiskSpace(diskUsage, logger2, useV2ResourceChecks)) { return new Failure("insufficient-disk-space" /* InsufficientDiskSpace */); } - if (!await runnerHasSufficientMemory(codeql, ramInput, logger)) { + if (!await runnerHasSufficientMemory(codeql, ramInput, logger2)) { return new Failure("insufficient-memory" /* InsufficientMemory */); } return new Success(void 0); } -async function checkOverlayEnablement(codeql, features, languages, sourceRoot, buildMode, ramInput, codeScanningConfig, repositoryProperties, gitVersion, logger) { +async function checkOverlayEnablement(codeql, features, languages, sourceRoot, buildMode, ramInput, codeScanningConfig, repositoryProperties, gitVersion, logger2) { const modeEnv = process.env.CODEQL_OVERLAY_DATABASE_MODE; if (modeEnv === "overlay" /* Overlay */ || modeEnv === "overlay-base" /* OverlayBase */ || modeEnv === "none" /* None */) { - logger.info( + logger2.info( `Setting overlay database mode to ${modeEnv} from the CODEQL_OVERLAY_DATABASE_MODE environment variable.` ); if (modeEnv === "none" /* None */) { @@ -151718,11 +151721,11 @@ async function checkOverlayEnablement(codeql, features, languages, sourceRoot, b sourceRoot, buildMode, gitVersion, - logger + logger2 ); } if (repositoryProperties["github-codeql-disable-overlay" /* DISABLE_OVERLAY */] === true) { - logger.info( + logger2.info( `Setting overlay database mode to ${"none" /* None */} because the ${"github-codeql-disable-overlay" /* DISABLE_OVERLAY */} repository property is set to true.` ); return new Failure("disabled-by-repository-property" /* DisabledByRepositoryProperty */); @@ -151747,9 +151750,9 @@ async function checkOverlayEnablement(codeql, features, languages, sourceRoot, b "overlay_analysis_status_check" /* OverlayAnalysisStatusCheck */ ); const needDiskUsage = performResourceChecks || checkOverlayStatus; - const diskUsage = needDiskUsage ? await checkDiskUsage(logger) : void 0; + const diskUsage = needDiskUsage ? await checkDiskUsage(logger2) : void 0; if (needDiskUsage && diskUsage === void 0) { - logger.warning( + logger2.warning( `Unable to determine disk usage, therefore setting overlay database mode to ${"none" /* None */}.` ); return new Failure("unable-to-determine-disk-usage" /* UnableToDetermineDiskUsage */); @@ -151758,14 +151761,14 @@ async function checkOverlayEnablement(codeql, features, languages, sourceRoot, b codeql, diskUsage, ramInput, - logger, + logger2, useV2ResourceChecks ) : new Success(void 0); if (resourceResult.isFailure()) { return resourceResult; } - if (checkOverlayStatus && diskUsage !== void 0 && await shouldSkipOverlayAnalysis(codeql, languages, diskUsage, logger)) { - logger.info( + if (checkOverlayStatus && diskUsage !== void 0 && await shouldSkipOverlayAnalysis(codeql, languages, diskUsage, logger2)) { + logger2.info( `Setting overlay database mode to ${"none" /* None */} because overlay analysis previously failed with this combination of languages, disk space, and CodeQL version.` ); return new Failure("skipped-due-to-cached-status" /* SkippedDueToCachedStatus */); @@ -151773,12 +151776,12 @@ async function checkOverlayEnablement(codeql, features, languages, sourceRoot, b let overlayDatabaseMode; if (isAnalyzingPullRequest()) { overlayDatabaseMode = "overlay" /* Overlay */; - logger.info( + logger2.info( `Setting overlay database mode to ${overlayDatabaseMode} with caching because we are analyzing a pull request.` ); } else if (await isAnalyzingDefaultBranch()) { overlayDatabaseMode = "overlay-base" /* OverlayBase */; - logger.info( + logger2.info( `Setting overlay database mode to ${overlayDatabaseMode} with caching because we are analyzing the default branch.` ); } else { @@ -151793,10 +151796,10 @@ async function checkOverlayEnablement(codeql, features, languages, sourceRoot, b sourceRoot, buildMode, gitVersion, - logger + logger2 ); } -async function validateOverlayDatabaseMode(overlayDatabaseMode, useOverlayDatabaseCaching, overlayModeSetExplicitly, codeql, languages, sourceRoot, buildMode, gitVersion, logger) { +async function validateOverlayDatabaseMode(overlayDatabaseMode, useOverlayDatabaseCaching, overlayModeSetExplicitly, codeql, languages, sourceRoot, buildMode, gitVersion, logger2) { if (buildMode !== "none" /* None */ && (await Promise.all( languages.map( async (l) => l !== "go" /* go */ && // Workaround to allow overlay analysis for Go with any build @@ -151806,33 +151809,33 @@ async function validateOverlayDatabaseMode(overlayDatabaseMode, useOverlayDataba await codeql.isTracedLanguage(l) ) )).some(Boolean)) { - logger.warning( + logger2.warning( `Cannot build an ${overlayDatabaseMode} database because build-mode is set to "${buildMode}" instead of "none". Falling back to creating a normal full database instead.` ); return new Failure("incompatible-build-mode" /* IncompatibleBuildMode */); } if (!await codeQlVersionAtLeast(codeql, CODEQL_OVERLAY_MINIMUM_VERSION)) { - logger.warning( + logger2.warning( `Cannot build an ${overlayDatabaseMode} database because the CodeQL CLI is older than ${CODEQL_OVERLAY_MINIMUM_VERSION}. Falling back to creating a normal full database instead.` ); return new Failure("incompatible-codeql" /* IncompatibleCodeQl */); } const gitRoot = await getGitRoot(sourceRoot); if (gitRoot === void 0) { - logger.warning( + logger2.warning( `Cannot build an ${overlayDatabaseMode} database because the source root "${sourceRoot}" is not inside a git repository. Falling back to creating a normal full database instead.` ); return new Failure("no-git-root" /* NoGitRoot */); } if (hasSubmodules(gitRoot)) { if (gitVersion === void 0) { - logger.warning( + logger2.warning( `Cannot build an ${overlayDatabaseMode} database because the repository has submodules and the Git version could not be determined. Falling back to creating a normal full database instead.` ); return new Failure("incompatible-git" /* IncompatibleGit */); } if (!gitVersion.isAtLeast(GIT_MINIMUM_VERSION_FOR_OVERLAY_WITH_SUBMODULES)) { - logger.warning( + logger2.warning( `Cannot build an ${overlayDatabaseMode} database because the repository has submodules and the installed Git version is older than ${GIT_MINIMUM_VERSION_FOR_OVERLAY_WITH_SUBMODULES}. Falling back to creating a normal full database instead.` ); return new Failure("incompatible-git" /* IncompatibleGit */); @@ -151853,18 +151856,18 @@ async function isTrapCachingEnabled(features, overlayDatabaseMode) { } return true; } -async function setCppTrapCachingEnvironmentVariables(config, logger) { +async function setCppTrapCachingEnvironmentVariables(config, logger2) { if (config.languages.includes("cpp" /* cpp */)) { const envVar = "CODEQL_EXTRACTOR_CPP_TRAP_CACHING"; if (process.env[envVar]) { - logger.info( + logger2.info( `Environment variable ${envVar} already set, leaving it unchanged.` ); } else if (config.trapCaches["cpp" /* cpp */]) { - logger.info("Enabling TRAP caching for C/C++."); + logger2.info("Enabling TRAP caching for C/C++."); core8.exportVariable(envVar, "true"); } else { - logger.debug(`Disabling TRAP caching for C/C++.`); + logger2.debug(`Disabling TRAP caching for C/C++.`); core8.exportVariable(envVar, "false"); } } @@ -151878,9 +151881,9 @@ function userConfigFromActionPath(tempDir) { function hasQueryCustomisation(userConfig) { return isDefined2(userConfig["disable-default-queries"]) || isDefined2(userConfig.queries) || isDefined2(userConfig["query-filters"]); } -async function applyIncrementalAnalysisSettings(config, hasDiffRanges, codeql, logger) { +async function applyIncrementalAnalysisSettings(config, hasDiffRanges, codeql, logger2) { if (config.overlayDatabaseMode === "overlay" /* Overlay */ && !hasDiffRanges && !config.overlayModeSetExplicitly) { - logger.info( + logger2.info( `Reverting overlay database mode to ${"none" /* None */} because the PR diff ranges could not be computed.` ); config.overlayDatabaseMode = "none" /* None */; @@ -151898,25 +151901,25 @@ async function applyIncrementalAnalysisSettings(config, hasDiffRanges, codeql, l } } async function initConfig(features, inputs) { - const { logger, tempDir } = inputs; + const { logger: logger2, tempDir } = inputs; if (inputs.configInput) { if (inputs.configFile) { - logger.warning( + logger2.warning( `Both a config file and config input were provided. Ignoring config file.` ); } inputs.configFile = userConfigFromActionPath(tempDir); fs10.writeFileSync(inputs.configFile, inputs.configInput); - logger.debug(`Using config from action input: ${inputs.configFile}`); + logger2.debug(`Using config from action input: ${inputs.configFile}`); } let userConfig = {}; if (!inputs.configFile) { - logger.debug("No configuration file was provided"); + logger2.debug("No configuration file was provided"); } else { - logger.debug(`Using configuration file: ${inputs.configFile}`); + logger2.debug(`Using configuration file: ${inputs.configFile}`); const validateConfig = await features.getValue("validate_db_config" /* ValidateDbConfig */); userConfig = await loadUserConfig( - logger, + logger2, inputs.configFile, inputs.workspacePath, inputs.apiDetails, @@ -151939,10 +151942,10 @@ async function initConfig(features, inputs) { let gitVersion = void 0; try { gitVersion = await getGitVersionOrThrow(); - logger.info(`Using Git version ${gitVersion.fullVersion}`); + logger2.info(`Using Git version ${gitVersion.fullVersion}`); await logGitVersionTelemetry(config, gitVersion); } catch (e) { - logger.warning(`Could not determine Git version: ${getErrorMessage(e)}`); + logger2.warning(`Could not determine Git version: ${getErrorMessage(e)}`); if (isInTestMode() && process.env["CODEQL_ACTION_TOLERATE_MISSING_GIT_VERSION" /* TOLERATE_MISSING_GIT_VERSION */] !== "true") { throw e; } @@ -151957,11 +151960,11 @@ async function initConfig(features, inputs) { if (generatedFiles.length > 0) { config.computedConfig["paths-ignore"] ??= []; config.computedConfig["paths-ignore"].push(...generatedFiles); - logger.info( + logger2.info( `Detected ${generatedFiles.length} generated file(s), which will be excluded from analysis: ${joinAtMost(generatedFiles, ", ", 10)}` ); } else { - logger.info(`Found no generated files.`); + logger2.info(`Found no generated files.`); } await logGeneratedFilesTelemetry( config, @@ -151969,10 +151972,10 @@ async function initConfig(features, inputs) { generatedFiles.length ); } catch (error3) { - logger.info(`Cannot ignore generated files: ${getErrorMessage(error3)}`); + logger2.info(`Cannot ignore generated files: ${getErrorMessage(error3)}`); } } else { - logger.debug(`Skipping check for generated files.`); + logger2.debug(`Skipping check for generated files.`); } const overlayDatabaseModeResult = await checkOverlayEnablement( inputs.codeql, @@ -151984,7 +151987,7 @@ async function initConfig(features, inputs) { config.computedConfig, config.repositoryProperties, gitVersion, - logger + logger2 ); if (overlayDatabaseModeResult.isSuccess()) { const { @@ -151992,7 +151995,7 @@ async function initConfig(features, inputs) { useOverlayDatabaseCaching, overlayModeSetExplicitly } = overlayDatabaseModeResult.value; - logger.info( + logger2.info( `Using overlay database mode: ${overlayDatabaseMode} ${useOverlayDatabaseCaching ? "with" : "without"} caching.` ); config.overlayDatabaseMode = overlayDatabaseMode; @@ -152000,7 +152003,7 @@ async function initConfig(features, inputs) { config.overlayModeSetExplicitly = overlayModeSetExplicitly; } else { const overlayDisabledReason = overlayDatabaseModeResult.value; - logger.info( + logger2.info( `Using overlay database mode: ${"none" /* None */} without caching.` ); config.overlayDatabaseMode = "none" /* None */; @@ -152014,24 +152017,24 @@ async function initConfig(features, inputs) { const hasDiffRanges = await prepareDiffInformedAnalysis( inputs.codeql, inputs.features, - logger + logger2 ); await applyIncrementalAnalysisSettings( config, hasDiffRanges, inputs.codeql, - logger + logger2 ); if (await isTrapCachingEnabled(features, config.overlayDatabaseMode)) { const { trapCaches, trapCacheDownloadTime } = await downloadCacheWithTime( inputs.codeql, config.languages, - logger + logger2 ); config.trapCaches = trapCaches; config.trapCacheDownloadTime = trapCacheDownloadTime; } - await setCppTrapCachingEnvironmentVariables(config, logger); + await setCppTrapCachingEnvironmentVariables(config, logger2); return config; } function parseRegistries(registriesInput) { @@ -152055,20 +152058,20 @@ function isLocal(configPath) { } return configPath.indexOf("@") === -1; } -function getLocalConfig(logger, configFile, validateConfig) { +function getLocalConfig(logger2, configFile, validateConfig) { if (!fs10.existsSync(configFile)) { throw new ConfigurationError( getConfigFileDoesNotExistErrorMessage(configFile) ); } return parseUserConfig( - logger, + logger2, configFile, fs10.readFileSync(configFile, "utf-8"), validateConfig ); } -async function getRemoteConfig(logger, configFile, apiDetails, validateConfig) { +async function getRemoteConfig(logger2, configFile, apiDetails, validateConfig) { const format = new RegExp( "(?[^/]+)/(?[^/]+)/(?[^@]+)@(?.*)" ); @@ -152097,7 +152100,7 @@ async function getRemoteConfig(logger, configFile, apiDetails, validateConfig) { ); } return parseUserConfig( - logger, + logger2, configFile, Buffer.from(fileContents, "base64").toString("binary"), validateConfig @@ -152106,22 +152109,22 @@ async function getRemoteConfig(logger, configFile, apiDetails, validateConfig) { function getPathToParsedConfigFile(tempDir) { return path11.join(tempDir, "config"); } -async function saveConfig(config, logger) { +async function saveConfig(config, logger2) { const configString = JSON.stringify(config); const configFile = getPathToParsedConfigFile(config.tempDir); fs10.mkdirSync(path11.dirname(configFile), { recursive: true }); fs10.writeFileSync(configFile, configString, "utf8"); - logger.debug("Saved config:"); - logger.debug(configString); + logger2.debug("Saved config:"); + logger2.debug(configString); } -async function getConfig(tempDir, logger) { +async function getConfig(tempDir, logger2) { const configFile = getPathToParsedConfigFile(tempDir); if (!fs10.existsSync(configFile)) { return void 0; } const configString = fs10.readFileSync(configFile, "utf8"); - logger.debug("Loaded config:"); - logger.debug(configString); + logger2.debug("Loaded config:"); + logger2.debug(configString); const config = JSON.parse(configString); if (config.version === void 0) { throw new ConfigurationError( @@ -152135,7 +152138,7 @@ async function getConfig(tempDir, logger) { } return config; } -async function generateRegistries(registriesInput, tempDir, logger) { +async function generateRegistries(registriesInput, tempDir, logger2) { const registries = parseRegistries(registriesInput); let registriesAuthTokens; let qlconfigFile; @@ -152144,12 +152147,12 @@ async function generateRegistries(registriesInput, tempDir, logger) { qlconfigFile = path11.join(tempDir, "qlconfig.yml"); const qlconfigContents = dump(qlconfig); fs10.writeFileSync(qlconfigFile, qlconfigContents, "utf8"); - logger.debug("Generated qlconfig.yml:"); - logger.debug(qlconfigContents); + logger2.debug("Generated qlconfig.yml:"); + logger2.debug(qlconfigContents); registriesAuthTokens = registries.map((registry) => `${registry.url}=${registry.token}`).join(","); } if (typeof process.env.CODEQL_REGISTRIES_AUTH === "string") { - logger.debug( + logger2.debug( "Using CODEQL_REGISTRIES_AUTH environment variable to authenticate with registries." ); } @@ -152193,7 +152196,7 @@ async function wrapEnvironment(env, operation) { } } } -async function parseBuildModeInput(input, languages, features, logger) { +async function parseBuildModeInput(input, languages, features, logger2) { if (input === void 0) { return void 0; } @@ -152205,13 +152208,13 @@ async function parseBuildModeInput(input, languages, features, logger) { ); } if (languages.includes("csharp" /* csharp */) && await features.getValue("disable_csharp_buildless" /* DisableCsharpBuildless */)) { - logger.warning( + logger2.warning( "Scanning C# code without a build is temporarily unavailable. Falling back to 'autobuild' build mode." ); return "autobuild" /* Autobuild */; } if (languages.includes("java" /* java */) && await features.getValue("disable_java_buildless_enabled" /* DisableJavaBuildlessEnabled */)) { - logger.warning( + logger2.warning( "Scanning Java code without a build is temporarily unavailable. Falling back to 'autobuild' build mode." ); return "autobuild" /* Autobuild */; @@ -152346,10 +152349,10 @@ var OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_BYTES = OVERLAY_BASE_DATABASE_MAX_UPLO var CACHE_VERSION2 = 1; var CACHE_PREFIX = "codeql-overlay-base-database"; var MAX_CACHE_OPERATION_MS3 = 6e5; -async function checkOverlayBaseDatabase(codeql, config, logger, warningPrefix) { +async function checkOverlayBaseDatabase(codeql, config, logger2, warningPrefix) { const baseDatabaseOidsFilePath = getBaseDatabaseOidsFilePath(config); if (!fs11.existsSync(baseDatabaseOidsFilePath)) { - logger.warning( + logger2.warning( `${warningPrefix}: ${baseDatabaseOidsFilePath} does not exist` ); return false; @@ -152359,36 +152362,36 @@ async function checkOverlayBaseDatabase(codeql, config, logger, warningPrefix) { try { const resolveDatabaseOutput = await codeql.resolveDatabase(dbPath); if (resolveDatabaseOutput === void 0 || !("overlayBaseSpecifier" in resolveDatabaseOutput)) { - logger.info(`${warningPrefix}: no overlayBaseSpecifier defined`); + logger2.info(`${warningPrefix}: no overlayBaseSpecifier defined`); return false; } else { - logger.debug( + logger2.debug( `Overlay base specifier for ${language} overlay-base database found: ${resolveDatabaseOutput.overlayBaseSpecifier}` ); } } catch (e) { - logger.warning(`${warningPrefix}: failed to resolve database: ${e}`); + logger2.warning(`${warningPrefix}: failed to resolve database: ${e}`); return false; } } return true; } -async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger) { +async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger2) { const overlayDatabaseMode = config.overlayDatabaseMode; if (overlayDatabaseMode !== "overlay-base" /* OverlayBase */) { - logger.debug( + logger2.debug( `Overlay database mode is ${overlayDatabaseMode}. Skip uploading overlay-base database to cache.` ); return false; } if (!config.useOverlayDatabaseCaching) { - logger.debug( + logger2.debug( "Overlay database caching is disabled. Skip uploading overlay-base database to cache." ); return false; } if (isInTestMode()) { - logger.debug( + logger2.debug( "In test mode. Skip uploading overlay-base database to cache." ); return false; @@ -152396,7 +152399,7 @@ async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger const databaseIsValid = await checkOverlayBaseDatabase( codeql, config, - logger, + logger2, "Abort uploading overlay-base database to cache" ); if (!databaseIsValid) { @@ -152406,16 +152409,16 @@ async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger await codeql.databaseCleanupCluster(config, "overlay" /* Overlay */); }); const dbLocation = config.dbLocation; - const databaseSizeBytes = await tryGetFolderBytes(dbLocation, logger); + const databaseSizeBytes = await tryGetFolderBytes(dbLocation, logger2); if (databaseSizeBytes === void 0) { - logger.warning( + logger2.warning( "Failed to determine database size. Skip uploading overlay-base database to cache." ); return false; } if (databaseSizeBytes > OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_BYTES) { const databaseSizeMB = Math.round(databaseSizeBytes / 1e6); - logger.warning( + logger2.warning( `Database size (${databaseSizeMB} MB) exceeds maximum upload size (${OVERLAY_BASE_DATABASE_MAX_UPLOAD_SIZE_MB} MB). Skip uploading overlay-base database to cache.` ); return false; @@ -152426,9 +152429,9 @@ async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger config, codeQlVersion, checkoutPath, - logger + logger2 ); - logger.info( + logger2.info( `Uploading overlay-base database to Actions cache with key ${cacheSaveKey}` ); try { @@ -152439,34 +152442,34 @@ async function cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger } ); if (cacheId === void 0) { - logger.warning("Timed out while uploading overlay-base database"); + logger2.warning("Timed out while uploading overlay-base database"); return false; } } catch (error3) { - logger.warning( + logger2.warning( `Failed to upload overlay-base database to cache: ${error3 instanceof Error ? error3.message : String(error3)}` ); return false; } - logger.info(`Successfully uploaded overlay-base database from ${dbLocation}`); + logger2.info(`Successfully uploaded overlay-base database from ${dbLocation}`); return true; } -async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger) { +async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger2) { const overlayDatabaseMode = config.overlayDatabaseMode; if (overlayDatabaseMode !== "overlay" /* Overlay */) { - logger.debug( + logger2.debug( `Overlay database mode is ${overlayDatabaseMode}. Skip downloading overlay-base database from cache.` ); return void 0; } if (!config.useOverlayDatabaseCaching) { - logger.debug( + logger2.debug( "Overlay database caching is disabled. Skip downloading overlay-base database from cache." ); return void 0; } if (isInTestMode()) { - logger.debug( + logger2.debug( "In test mode. Skip downloading overlay-base database from cache." ); return void 0; @@ -152477,7 +152480,7 @@ async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger) { config, codeQlVersion ); - logger.info( + logger2.info( `Looking in Actions cache for overlay-base database with restore key ${cacheRestoreKeyPrefix}` ); let databaseDownloadDurationMs = 0; @@ -152517,21 +152520,21 @@ async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger) { } ), () => { - logger.info("Timed out downloading overlay-base database from cache"); + logger2.info("Timed out downloading overlay-base database from cache"); } ); databaseDownloadDurationMs = Math.round( performance.now() - databaseDownloadStart ); if (foundKey === void 0) { - logger.info("No overlay-base database found in Actions cache"); + logger2.info("No overlay-base database found in Actions cache"); return void 0; } - logger.info( + logger2.info( `Downloaded overlay-base database in cache with key ${foundKey}` ); } catch (error3) { - logger.warning( + logger2.warning( `Failed to download overlay-base database from cache: ${error3 instanceof Error ? error3.message : String(error3)}` ); return void 0; @@ -152539,34 +152542,34 @@ async function downloadOverlayBaseDatabaseFromCache(codeql, config, logger) { const databaseIsValid = await checkOverlayBaseDatabase( codeql, config, - logger, + logger2, "Downloaded overlay-base database is invalid" ); if (!databaseIsValid) { - logger.warning("Downloaded overlay-base database failed validation"); + logger2.warning("Downloaded overlay-base database failed validation"); return void 0; } - const databaseSizeBytes = await tryGetFolderBytes(dbLocation, logger); + const databaseSizeBytes = await tryGetFolderBytes(dbLocation, logger2); if (databaseSizeBytes === void 0) { - logger.info( + logger2.info( "Filesystem error while accessing downloaded overlay-base database" ); return void 0; } - logger.info(`Successfully downloaded overlay-base database to ${dbLocation}`); + logger2.info(`Successfully downloaded overlay-base database to ${dbLocation}`); return { databaseSizeBytes: Math.round(databaseSizeBytes), databaseDownloadDurationMs }; } -async function getCacheSaveKey(config, codeQlVersion, checkoutPath, logger) { +async function getCacheSaveKey(config, codeQlVersion, checkoutPath, logger2) { let runId = 1; let attemptId = 1; try { runId = getWorkflowRunID(); attemptId = getWorkflowRunAttempt(); } catch (e) { - logger.warning( + logger2.warning( `Failed to get workflow run ID or attempt ID. Reason: ${getErrorMessage(e)}` ); } @@ -152589,10 +152592,10 @@ async function getCacheKeyPrefixBase(parsedLanguages) { const componentsHash = createCacheKeyHash(cacheKeyComponents); return `${CACHE_PREFIX}-${CACHE_VERSION2}-${componentsHash}-${languagesComponent}-`; } -async function getCodeQlVersionsForOverlayBaseDatabases(rawLanguages, logger) { +async function getCodeQlVersionsForOverlayBaseDatabases(rawLanguages, logger2) { const languages = rawLanguages.map(parseBuiltInLanguage); if (languages.includes(void 0)) { - logger.warning( + logger2.warning( "One or more provided languages are not recognized as built-in languages. Skipping searching for overlay-base databases in cache." ); return void 0; @@ -152601,15 +152604,15 @@ async function getCodeQlVersionsForOverlayBaseDatabases(rawLanguages, logger) { ...new Set(languages.filter((l) => l !== void 0)) ]; const cacheKeyPrefix = await getCacheKeyPrefixBase(dedupedLanguages); - logger.debug( + logger2.debug( `Searching for overlay-base databases in Actions cache with prefix ${cacheKeyPrefix}` ); const caches = await listActionsCaches(cacheKeyPrefix); if (caches.length === 0) { - logger.info("No overlay-base databases found in Actions cache."); + logger2.info("No overlay-base databases found in Actions cache."); return []; } - logger.info( + logger2.info( `Found ${caches.length} overlay-base ${caches.length === 1 ? "database" : "databases"} in the Actions cache.` ); const versionRegex = /^([\d.]+)-/; @@ -152623,13 +152626,13 @@ async function getCodeQlVersionsForOverlayBaseDatabases(rawLanguages, logger) { } } if (versionSet.size === 0) { - logger.info( + logger2.info( "Could not parse any CodeQL versions from overlay-base database cache keys." ); return []; } const versions = [...versionSet].sort(semver6.rcompare); - logger.info( + logger2.info( `Found overlay databases for the following CodeQL versions in the Actions cache: ${versions.join(", ")}` ); return versions; @@ -152674,12 +152677,12 @@ async function getTarVersion() { throw new Error("Unknown tar version"); } } -async function isZstdAvailable(logger) { - const foundZstdBinary = await isBinaryAccessible("zstd", logger); +async function isZstdAvailable(logger2) { + const foundZstdBinary = await isBinaryAccessible("zstd", logger2); try { const tarVersion = await getTarVersion(); const { type, version } = tarVersion; - logger.info(`Found ${type} tar version ${version}.`); + logger2.info(`Found ${type} tar version ${version}.`); switch (type) { case "gnu": return { @@ -152703,13 +152706,13 @@ async function isZstdAvailable(logger) { assertNever(type); } } catch (e) { - logger.warning( + logger2.warning( `Failed to determine tar version, therefore will assume zstd is not available. The underlying error was: ${e}` ); return { available: false, foundZstdBinary }; } } -async function extract(tarPath, dest, compressionMethod, tarVersion, logger) { +async function extract(tarPath, dest, compressionMethod, tarVersion, logger2) { fs12.mkdirSync(dest, { recursive: true }); switch (compressionMethod) { case "gzip": @@ -152720,13 +152723,13 @@ async function extract(tarPath, dest, compressionMethod, tarVersion, logger) { "Could not determine tar version, which is required to extract a Zstandard archive." ); } - await extractTarZst(tarPath, dest, tarVersion, logger); + await extractTarZst(tarPath, dest, tarVersion, logger2); return dest; } } } -async function extractTarZst(tar, dest, tarVersion, logger) { - logger.debug( +async function extractTarZst(tar, dest, tarVersion, logger2) { + logger2.debug( `Extracting to ${dest}.${tar instanceof stream.Readable ? ` Input stream has high water mark ${tar.readableHighWaterMark}.` : ""}` ); try { @@ -152776,7 +152779,7 @@ async function extractTarZst(tar, dest, tarVersion, logger) { }); }); } catch (e) { - await cleanUpPath(dest, "extraction destination directory", logger); + await cleanUpPath(dest, "extraction destination directory", logger2); throw e; } } @@ -152821,13 +152824,13 @@ function makeStreamedToolsDownloadDurations(combinedDurationMs) { streamExtraction: true }; } -async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorization, headers, tarVersion, logger) { - logger.info( +async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorization, headers, tarVersion, logger2) { + logger2.info( `Downloading CodeQL tools from ${codeqlURL} . This may take a while.` ); try { if (compressionMethod === "zstd" && process.platform === "linux") { - logger.info(`Streaming the extraction of the CodeQL bundle.`); + logger2.info(`Streaming the extraction of the CodeQL bundle.`); const toolsInstallStart = import_perf_hooks2.performance.now(); await downloadAndExtractZstdWithStreaming( codeqlURL, @@ -152835,12 +152838,12 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat authorization, headers, tarVersion, - logger + logger2 ); const combinedDurationMs = Math.round( import_perf_hooks2.performance.now() - toolsInstallStart ); - logger.info( + logger2.info( `Finished downloading and extracting CodeQL bundle to ${dest} (${formatDuration( combinedDurationMs )}).` @@ -152856,7 +152859,7 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat `Failed to download and extract CodeQL bundle using streaming with error: ${getErrorMessage(e)}` ); core9.warning(`Falling back to downloading the bundle before extracting.`); - await cleanUpPath(dest, "CodeQL bundle", logger); + await cleanUpPath(dest, "CodeQL bundle", logger2); } const toolsDownloadStart = import_perf_hooks2.performance.now(); const archivedBundlePath = await toolcache2.downloadTool( @@ -152866,30 +152869,30 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat headers ); const downloadDurationMs = Math.round(import_perf_hooks2.performance.now() - toolsDownloadStart); - logger.info( + logger2.info( `Finished downloading CodeQL bundle to ${archivedBundlePath} (${formatDuration( downloadDurationMs )}).` ); let extractionDurationMs; try { - logger.info("Extracting CodeQL bundle."); + logger2.info("Extracting CodeQL bundle."); const extractionStart = import_perf_hooks2.performance.now(); await extract( archivedBundlePath, dest, compressionMethod, tarVersion, - logger + logger2 ); extractionDurationMs = Math.round(import_perf_hooks2.performance.now() - extractionStart); - logger.info( + logger2.info( `Finished extracting CodeQL bundle to ${dest} (${formatDuration( extractionDurationMs )}).` ); } finally { - await cleanUpPath(archivedBundlePath, "CodeQL bundle archive", logger); + await cleanUpPath(archivedBundlePath, "CodeQL bundle archive", logger2); } return { compressionMethod, @@ -152900,7 +152903,7 @@ async function downloadAndExtract(codeqlURL, compressionMethod, dest, authorizat ) }; } -async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorization, headers, tarVersion, logger) { +async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorization, headers, tarVersion, logger2) { fs13.mkdirSync(dest, { recursive: true }); const agent = new import_http_client.HttpClient().getAgent(codeqlURL); headers = Object.assign( @@ -152926,7 +152929,7 @@ async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorizatio `Failed to download CodeQL bundle from ${codeqlURL}. HTTP status code: ${response.statusCode}.` ); } - await extractTarZst(response, dest, tarVersion, logger); + await extractTarZst(response, dest, tarVersion, logger2); } function getToolcacheDirectory(version) { return path12.join( @@ -152936,10 +152939,10 @@ function getToolcacheDirectory(version) { os3.arch() || "" ); } -function writeToolcacheMarkerFile(extractedPath, logger) { +function writeToolcacheMarkerFile(extractedPath, logger2) { const markerFilePath = `${extractedPath}.complete`; fs13.writeFileSync(markerFilePath, ""); - logger.info(`Created toolcache marker file ${markerFilePath}`); + logger2.info(`Created toolcache marker file ${markerFilePath}`); } function sanitizeUrlForStatusReport(url2) { return ["github/codeql-action", "dsp-testing/codeql-cli-nightlies"].some( @@ -152978,17 +152981,17 @@ function getCodeQLBundleName(compressionMethod) { } return `codeql-bundle-${platform2}${extension}`; } -function getCodeQLActionRepository(logger) { +function getCodeQLActionRepository(logger2) { if (isRunningLocalAction()) { - logger.info( + logger2.info( "The CodeQL Action is checked out locally. Using the default CodeQL Action repository." ); return CODEQL_DEFAULT_ACTION_REPOSITORY; } return getRequiredEnvParam("GITHUB_ACTION_REPOSITORY"); } -async function getCodeQLBundleDownloadURL(tagName, apiDetails, compressionMethod, logger) { - const codeQLActionRepository = getCodeQLActionRepository(logger); +async function getCodeQLBundleDownloadURL(tagName, apiDetails, compressionMethod, logger2) { + const codeQLActionRepository = getCodeQLActionRepository(logger2); const potentialDownloadSources = [ // This GitHub instance, and this Action. [apiDetails.url, codeQLActionRepository], @@ -153017,37 +153020,37 @@ async function getCodeQLBundleDownloadURL(tagName, apiDetails, compressionMethod }); for (const asset of release2.data.assets) { if (asset.name === codeQLBundleName) { - logger.info( + logger2.info( `Found CodeQL bundle ${codeQLBundleName} in ${repository} on ${apiURL} with URL ${asset.url}.` ); return asset.url; } } } catch (e) { - logger.info( + logger2.info( `Looked for CodeQL bundle ${codeQLBundleName} in ${repository} on ${apiURL} but got error ${e}.` ); } } return `https://github.com/${CODEQL_DEFAULT_ACTION_REPOSITORY}/releases/download/${tagName}/${codeQLBundleName}`; } -function tryGetBundleVersionFromTagName(tagName, logger) { +function tryGetBundleVersionFromTagName(tagName, logger2) { const match = tagName.match(/^codeql-bundle-(.*)$/); if (match === null || match.length < 2) { - logger.debug(`Could not determine bundle version from tag ${tagName}.`); + logger2.debug(`Could not determine bundle version from tag ${tagName}.`); return void 0; } return match[1]; } -function tryGetTagNameFromUrl(url2, logger) { +function tryGetTagNameFromUrl(url2, logger2) { const matches = [...url2.matchAll(/\/(codeql-bundle-[^/]*)\//g)]; if (matches.length === 0) { - logger.debug(`Could not determine tag name for URL ${url2}.`); + logger2.debug(`Could not determine tag name for URL ${url2}.`); return void 0; } const match = matches[matches.length - 1]; if (match?.length !== 2) { - logger.debug( + logger2.debug( `Could not determine tag name for URL ${url2}. Matched ${JSON.stringify( match )}.` @@ -153056,9 +153059,9 @@ function tryGetTagNameFromUrl(url2, logger) { } return match[1]; } -function convertToSemVer(version, logger) { +function convertToSemVer(version, logger2) { if (!semver9.valid(version)) { - logger.debug( + logger2.debug( `Bundle version ${version} is not in SemVer format. Will treat it as pre-release 0.0.0-${version}.` ); version = `0.0.0-${version}`; @@ -153069,14 +153072,14 @@ function convertToSemVer(version, logger) { } return s; } -async function findOverridingToolsInCache(humanReadableVersion, logger) { +async function findOverridingToolsInCache(humanReadableVersion, logger2) { const candidates = toolcache3.findAllVersions("CodeQL").filter(isGoodVersion).map((version) => ({ folder: toolcache3.find("CodeQL", version), version })).filter(({ folder }) => fs14.existsSync(path13.join(folder, "pinned-version"))); if (candidates.length === 1) { const candidate = candidates[0]; - logger.debug( + logger2.debug( `CodeQL tools version ${candidate.version} in toolcache overriding version ${humanReadableVersion}.` ); return { @@ -153085,17 +153088,17 @@ async function findOverridingToolsInCache(humanReadableVersion, logger) { toolsVersion: candidate.version }; } else if (candidates.length === 0) { - logger.debug( + logger2.debug( "Did not find any candidate pinned versions of the CodeQL tools in the toolcache." ); } else { - logger.debug( + logger2.debug( "Could not use CodeQL tools from the toolcache since more than one candidate pinned version was found in the toolcache." ); } return void 0; } -async function getEnabledVersionsWithOverlayBaseDatabases(defaultCliVersion, rawLanguages, features, logger) { +async function getEnabledVersionsWithOverlayBaseDatabases(defaultCliVersion, rawLanguages, features, logger2) { if (rawLanguages === void 0 || rawLanguages.length === 0) { return []; } @@ -153110,10 +153113,10 @@ async function getEnabledVersionsWithOverlayBaseDatabases(defaultCliVersion, raw try { cachedVersions = await getCodeQlVersionsForOverlayBaseDatabases( rawLanguages, - logger + logger2 ); } catch (e) { - logger.warning( + logger2.warning( `Could not list overlay-base databases in the Actions cache while choosing a default CodeQL CLI version, falling back to the highest enabled version. Details: ${getErrorMessage(e)}` ); return []; @@ -153147,14 +153150,14 @@ async function getEnabledVersionsWithOverlayBaseDatabases(defaultCliVersion, raw ); } if (isDryRun) { - logger.debug( + logger2.debug( `Overlay-aware default CodeQL version selection is running in dry-run mode. Would have used version ${overlayVersions[0].cliVersion}.` ); return []; } return overlayVersions; } -async function resolveDefaultCliVersion(defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger) { +async function resolveDefaultCliVersion(defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger2) { if (!useOverlayAwareDefaultCliVersion || !isAnalyzingPullRequest()) { return defaultCliVersion.enabledVersions[0]; } @@ -153162,19 +153165,19 @@ async function resolveDefaultCliVersion(defaultCliVersion, rawLanguages, useOver defaultCliVersion, rawLanguages, features, - logger + logger2 ); if (overlayVersions.length > 0) { - logger.info( + logger2.info( `Using CodeQL version ${overlayVersions[0].cliVersion} since this is the highest enabled version that has a cached overlay-base database.` ); return overlayVersions[0]; } return defaultCliVersion.enabledVersions[0]; } -async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, apiDetails, variant, tarSupportsZstd, features, logger) { +async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, apiDetails, variant, tarSupportsZstd, features, logger2) { if (toolsInput && !isReservedToolsValue(toolsInput) && !toolsInput.startsWith("http")) { - logger.info(`Using CodeQL CLI from local path ${toolsInput}`); + logger2.info(`Using CodeQL CLI from local path ${toolsInput}`); const compressionMethod2 = inferCompressionMethod(toolsInput); if (compressionMethod2 === void 0) { throw new ConfigurationError( @@ -153197,7 +153200,7 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO const nightlyRequestedByToolsInput = toolsInput !== void 0 && CODEQL_NIGHTLY_TOOLS_INPUTS.includes(toolsInput); if (forceNightly || nightlyRequestedByToolsInput) { if (forceNightly) { - logger.info( + logger2.info( `Using the latest CodeQL CLI nightly, as forced by the ${"force_nightly" /* ForceNightly */} feature flag.` ); addNoLanguageDiagnostic( @@ -153217,21 +153220,21 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO ) ); } else { - logger.info( + logger2.info( `Using the latest CodeQL CLI nightly, as requested by 'tools: ${toolsInput}'.` ); } - toolsInput = await getNightlyToolsUrl(logger); + toolsInput = await getNightlyToolsUrl(logger2); } const forceShippedTools = toolsInput && CODEQL_BUNDLE_VERSION_ALIAS.includes(toolsInput); if (forceShippedTools) { cliVersion2 = cliVersion; tagName = bundleVersion; - logger.info( + logger2.info( `'tools: ${toolsInput}' was requested, so using CodeQL version ${cliVersion2}, the version shipped with the Action.` ); if (toolsInput === "latest") { - logger.warning( + logger2.warning( "`tools: latest` has been renamed to `tools: linked`, but the old name is still supported. No action is required." ); } @@ -153242,26 +153245,26 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO ); const allowToolcacheValue = allowToolcacheValueFF && (isDynamicWorkflow() || isInTestMode()); if (allowToolcacheValue) { - logger.info( + logger2.info( `Attempting to use the latest CodeQL CLI version in the toolcache, as requested by 'tools: ${toolsInput}'.` ); - latestToolcacheVersion = getLatestToolcacheVersion(logger); + latestToolcacheVersion = getLatestToolcacheVersion(logger2); if (latestToolcacheVersion) { cliVersion2 = latestToolcacheVersion; } } if (latestToolcacheVersion === void 0) { if (allowToolcacheValue) { - logger.info( + logger2.info( `Found no CodeQL CLI in the toolcache, ignoring 'tools: ${toolsInput}'...` ); } else { if (allowToolcacheValueFF) { - logger.warning( + logger2.warning( `Ignoring 'tools: ${toolsInput}' because the workflow was not triggered dynamically.` ); } else { - logger.info( + logger2.info( `Ignoring 'tools: ${toolsInput}' because the feature is not enabled.` ); } @@ -153271,18 +153274,18 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO rawLanguages, useOverlayAwareDefaultCliVersion, features, - logger + logger2 ); cliVersion2 = version.cliVersion; tagName = version.tagName; } } else if (toolsInput !== void 0) { - tagName = tryGetTagNameFromUrl(toolsInput, logger); + tagName = tryGetTagNameFromUrl(toolsInput, logger2); url2 = toolsInput; if (tagName) { - const bundleVersion3 = tryGetBundleVersionFromTagName(tagName, logger); + const bundleVersion3 = tryGetBundleVersionFromTagName(tagName, logger2); if (bundleVersion3 && semver9.valid(bundleVersion3)) { - cliVersion2 = convertToSemVer(bundleVersion3, logger); + cliVersion2 = convertToSemVer(bundleVersion3, logger2); } } } else { @@ -153291,25 +153294,25 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO rawLanguages, useOverlayAwareDefaultCliVersion, features, - logger + logger2 ); cliVersion2 = version.cliVersion; tagName = version.tagName; } - const bundleVersion2 = tagName && tryGetBundleVersionFromTagName(tagName, logger); - const humanReadableVersion = cliVersion2 ?? (bundleVersion2 && convertToSemVer(bundleVersion2, logger)) ?? tagName ?? url2 ?? "unknown"; - logger.debug( + const bundleVersion2 = tagName && tryGetBundleVersionFromTagName(tagName, logger2); + const humanReadableVersion = cliVersion2 ?? (bundleVersion2 && convertToSemVer(bundleVersion2, logger2)) ?? tagName ?? url2 ?? "unknown"; + logger2.debug( `Attempting to obtain CodeQL tools. CLI version: ${cliVersion2 ?? "unknown"}, bundle tag name: ${tagName ?? "unknown"}, URL: ${url2 ?? "unspecified"}.` ); let codeqlFolder; if (cliVersion2) { codeqlFolder = toolcache3.find("CodeQL", cliVersion2); if (!codeqlFolder) { - logger.debug( + logger2.debug( `Didn't find a version of the CodeQL tools in the toolcache with a version number exactly matching ${cliVersion2}.` ); const allVersions = toolcache3.findAllVersions("CodeQL"); - logger.debug( + logger2.debug( `Found the following versions of the CodeQL tools in the toolcache: ${JSON.stringify( allVersions )}.` @@ -153318,19 +153321,19 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO (version) => version.startsWith(`${cliVersion2}-`) ); if (candidateVersions.length === 1) { - logger.debug( + logger2.debug( `Exactly one version of the CodeQL tools starting with ${cliVersion2} found in the toolcache, using that.` ); codeqlFolder = toolcache3.find("CodeQL", candidateVersions[0]); } else if (candidateVersions.length === 0) { - logger.debug( + logger2.debug( `Didn't find any versions of the CodeQL tools starting with ${cliVersion2} in the toolcache. Trying next fallback method.` ); } else { - logger.warning( + logger2.warning( `Found ${candidateVersions.length} versions of the CodeQL tools starting with ${cliVersion2} in the toolcache, but at most one was expected.` ); - logger.debug("Trying next fallback method."); + logger2.debug("Trying next fallback method."); } } } @@ -153338,32 +153341,32 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO const fallbackVersion = await tryGetFallbackToolcacheVersion( cliVersion2, tagName, - logger + logger2 ); if (fallbackVersion) { codeqlFolder = toolcache3.find("CodeQL", fallbackVersion); } else { - logger.debug( + logger2.debug( `Could not determine a fallback toolcache version number for CodeQL tools version ${humanReadableVersion}.` ); } } if (codeqlFolder) { - logger.info( + logger2.info( `Found CodeQL tools version ${humanReadableVersion} in the toolcache.` ); } else { - logger.info( + logger2.info( `Did not find CodeQL tools version ${humanReadableVersion} in the toolcache.` ); } if (codeqlFolder) { if (cliVersion2) { - logger.info( + logger2.info( `Using CodeQL CLI version ${cliVersion2} from toolcache at ${codeqlFolder}` ); } else { - logger.info(`Using CodeQL CLI from toolcache at ${codeqlFolder}`); + logger2.info(`Using CodeQL CLI from toolcache at ${codeqlFolder}`); } return { codeqlFolder, @@ -153374,7 +153377,7 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO if (variant === "GitHub Enterprise Server" /* GHES */ && !forceShippedTools && !toolsInput) { const result = await findOverridingToolsInCache( humanReadableVersion, - logger + logger2 ); if (result !== void 0) { return result; @@ -153387,7 +153390,7 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO tagName, apiDetails, compressionMethod, - logger + logger2 ); } else { const method = inferCompressionMethod(url2); @@ -153399,12 +153402,12 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO compressionMethod = method; } if (cliVersion2) { - logger.info(`Using CodeQL CLI version ${cliVersion2} sourced from ${url2} .`); + logger2.info(`Using CodeQL CLI version ${cliVersion2} sourced from ${url2} .`); } else { - logger.info(`Using CodeQL CLI sourced from ${url2} .`); + logger2.info(`Using CodeQL CLI sourced from ${url2} .`); } return { - bundleVersion: tagName && tryGetBundleVersionFromTagName(tagName, logger), + bundleVersion: tagName && tryGetBundleVersionFromTagName(tagName, logger2), cliVersion: cliVersion2, codeqlURL: url2, compressionMethod, @@ -153412,18 +153415,18 @@ async function getCodeQLSource(toolsInput, defaultCliVersion, rawLanguages, useO toolsVersion: cliVersion2 ?? humanReadableVersion }; } -async function tryGetFallbackToolcacheVersion(cliVersion2, tagName, logger) { - const bundleVersion2 = tryGetBundleVersionFromTagName(tagName, logger); +async function tryGetFallbackToolcacheVersion(cliVersion2, tagName, logger2) { + const bundleVersion2 = tryGetBundleVersionFromTagName(tagName, logger2); if (!bundleVersion2) { return void 0; } - const fallbackVersion = convertToSemVer(bundleVersion2, logger); - logger.debug( + const fallbackVersion = convertToSemVer(bundleVersion2, logger2); + logger2.debug( `Computed a fallback toolcache version number of ${fallbackVersion} for CodeQL version ${cliVersion2 ?? tagName}.` ); return fallbackVersion; } -var downloadCodeQL = async function(codeqlURL, compressionMethod, maybeBundleVersion, maybeCliVersion, apiDetails, tarVersion, tempDir, logger) { +var downloadCodeQL = async function(codeqlURL, compressionMethod, maybeBundleVersion, maybeCliVersion, apiDetails, tarVersion, tempDir, logger2) { const parsedCodeQLURL = new URL(codeqlURL); const searchParams = new URLSearchParams(parsedCodeQLURL.search); const headers = { @@ -153431,10 +153434,10 @@ var downloadCodeQL = async function(codeqlURL, compressionMethod, maybeBundleVer }; let authorization = void 0; if (searchParams.has("token")) { - logger.debug("CodeQL tools URL contains an authorization token."); + logger2.debug("CodeQL tools URL contains an authorization token."); } else { authorization = getAuthorizationHeaderFor( - logger, + logger2, apiDetails, codeqlURL ); @@ -153442,7 +153445,7 @@ var downloadCodeQL = async function(codeqlURL, compressionMethod, maybeBundleVer const toolcacheInfo = getToolcacheDestinationInfo( maybeBundleVersion, maybeCliVersion, - logger + logger2 ); const extractedBundlePath = toolcacheInfo?.path ?? getTempExtractionDir(tempDir); const statusReport = await downloadAndExtract( @@ -153452,10 +153455,10 @@ var downloadCodeQL = async function(codeqlURL, compressionMethod, maybeBundleVer authorization, { "User-Agent": "CodeQL Action", ...headers }, tarVersion, - logger + logger2 ); if (!toolcacheInfo) { - logger.debug( + logger2.debug( `Could not cache CodeQL tools because we could not determine the bundle version from the URL ${codeqlURL}.` ); return { @@ -153464,19 +153467,19 @@ var downloadCodeQL = async function(codeqlURL, compressionMethod, maybeBundleVer toolsVersion: maybeCliVersion ?? "unknown" }; } - writeToolcacheMarkerFile(toolcacheInfo.path, logger); + writeToolcacheMarkerFile(toolcacheInfo.path, logger2); return { codeqlFolder: extractedBundlePath, statusReport, toolsVersion: maybeCliVersion ?? toolcacheInfo.version }; }; -function getToolcacheDestinationInfo(maybeBundleVersion, maybeCliVersion, logger) { +function getToolcacheDestinationInfo(maybeBundleVersion, maybeCliVersion, logger2) { if (maybeBundleVersion) { const version = getCanonicalToolcacheVersion( maybeCliVersion, maybeBundleVersion, - logger + logger2 ); return { path: getToolcacheDirectory(version), @@ -153485,19 +153488,19 @@ function getToolcacheDestinationInfo(maybeBundleVersion, maybeCliVersion, logger } return void 0; } -function getCanonicalToolcacheVersion(cliVersion2, bundleVersion2, logger) { +function getCanonicalToolcacheVersion(cliVersion2, bundleVersion2, logger2) { if (!cliVersion2?.match(/^[0-9]+\.[0-9]+\.[0-9]+$/)) { - return convertToSemVer(bundleVersion2, logger); + return convertToSemVer(bundleVersion2, logger2); } return cliVersion2; } -async function setupCodeQLBundle(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger) { - if (!await isBinaryAccessible("tar", logger)) { +async function setupCodeQLBundle(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger2) { + if (!await isBinaryAccessible("tar", logger2)) { throw new ConfigurationError( "Could not find tar in PATH, so unable to extract CodeQL bundle." ); } - const zstdAvailability = await isZstdAvailable(logger); + const zstdAvailability = await isZstdAvailable(logger2); const source = await getCodeQLSource( toolsInput, defaultCliVersion, @@ -153507,7 +153510,7 @@ async function setupCodeQLBundle(toolsInput, apiDetails, tempDir, variant, defau variant, zstdAvailability.available, features, - logger + logger2 ); let codeqlFolder; let toolsVersion = source.toolsVersion; @@ -153520,14 +153523,14 @@ async function setupCodeQLBundle(toolsInput, apiDetails, tempDir, variant, defau getTempExtractionDir(tempDir), source.compressionMethod, zstdAvailability.version, - logger + logger2 ); toolsSource = "LOCAL" /* Local */; break; } case "toolcache": codeqlFolder = source.codeqlFolder; - logger.debug(`CodeQL found in cache ${codeqlFolder}`); + logger2.debug(`CodeQL found in cache ${codeqlFolder}`); toolsSource = "TOOLCACHE" /* Toolcache */; break; case "download": { @@ -153539,7 +153542,7 @@ async function setupCodeQLBundle(toolsInput, apiDetails, tempDir, variant, defau apiDetails, zstdAvailability.version, tempDir, - logger + logger2 ); toolsVersion = result.toolsVersion; codeqlFolder = result.codeqlFolder; @@ -153567,8 +153570,8 @@ async function useZstdBundle(cliVersion2, tarSupportsZstd) { function getTempExtractionDir(tempDir) { return path13.join(tempDir, v4_default()); } -async function getNightlyToolsUrl(logger) { - const zstdAvailability = await isZstdAvailable(logger); +async function getNightlyToolsUrl(logger2) { + const zstdAvailability = await isZstdAvailable(logger2); const compressionMethod = await useZstdBundle( CODEQL_VERSION_ZSTD_BUNDLE, zstdAvailability.available @@ -153592,16 +153595,16 @@ async function getNightlyToolsUrl(logger) { ); } } -function getLatestToolcacheVersion(logger) { +function getLatestToolcacheVersion(logger2) { const allVersions = toolcache3.findAllVersions("CodeQL").sort((a, b) => semver9.compare(b, a)); - logger.debug( + logger2.debug( `Found the following versions of the CodeQL tools in the toolcache: ${JSON.stringify( allVersions )}.` ); if (allVersions.length > 0) { const latestToolcacheVersion = allVersions[0]; - logger.info( + logger2.info( `CLI version ${latestToolcacheVersion} is the latest version in the toolcache.` ); return latestToolcacheVersion; @@ -153624,9 +153627,9 @@ async function shouldEnableIndirectTracing(codeql, config) { } return asyncSome(config.languages, (l) => codeql.isTracedLanguage(l)); } -async function endTracingForCluster(codeql, config, logger) { +async function endTracingForCluster(codeql, config, logger2) { if (!await shouldEnableIndirectTracing(codeql, config)) return; - logger.info( + logger2.info( "Unsetting build tracing environment variables. Subsequent steps of this job will not be traced." ); const envVariablesFile = path14.resolve( @@ -153700,7 +153703,7 @@ var CODEQL_NEXT_MINIMUM_VERSION = "2.19.4"; var GHES_VERSION_MOST_RECENTLY_DEPRECATED = "3.15"; var GHES_MOST_RECENT_DEPRECATION_DATE = "2026-04-09"; var EXTRACTION_DEBUG_MODE_VERBOSITY = "progress++"; -async function setupCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger, checkVersion) { +async function setupCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger2, checkVersion) { try { const { codeqlFolder, @@ -153717,9 +153720,9 @@ async function setupCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliV rawLanguages, useOverlayAwareDefaultCliVersion, features, - logger + logger2 ); - logger.debug( + logger2.debug( `Bundle download status report: ${JSON.stringify( toolsDownloadStatusReport )}` @@ -153797,7 +153800,7 @@ async function getCodeQLForCmd(cmd, checkVersion) { async isScannedLanguage(language) { return !await this.isTracedLanguage(language); }, - async databaseInitCluster(config, sourceRoot, processName, qlconfigFile, logger) { + async databaseInitCluster(config, sourceRoot, processName, qlconfigFile, logger2) { const extraArgs = config.languages.map( (language) => `--language=${language}` ); @@ -153808,7 +153811,7 @@ async function getCodeQLForCmd(cmd, checkVersion) { } const codeScanningConfigFile = await writeCodeScanningConfigFile( config, - logger + logger2 ); const externalRepositoryToken = getOptionalInput( "external-repository-token" @@ -153828,7 +153831,7 @@ async function getCodeQLForCmd(cmd, checkVersion) { const overlayChangesFile = await writeOverlayChangesFile( config, sourceRoot, - logger + logger2 ); extraArgs.push(`--overlay-changes=${overlayChangesFile}`); } else if (overlayDatabaseMode === "overlay-base" /* OverlayBase */) { @@ -154220,18 +154223,18 @@ async function runCliJson(cmd, args = [], opts = {}) { throw Error(`Invalid JSON output from \`${args.join(" ")}\`: ${output}`); } } -async function writeCodeScanningConfigFile(config, logger) { +async function writeCodeScanningConfigFile(config, logger2) { const codeScanningConfigFile = getGeneratedCodeScanningConfigPath(config); const augmentedConfig = appendExtraQueryExclusions( config.extraQueryExclusions, config.computedConfig ); - logger.info( + logger2.info( `Writing augmented user configuration file to ${codeScanningConfigFile}` ); - logger.startGroup("Augmented user configuration file contents"); - logger.info(dump(augmentedConfig)); - logger.endGroup(); + logger2.startGroup("Augmented user configuration file contents"); + logger2.info(dump(augmentedConfig)); + logger2.endGroup(); fs16.writeFileSync(codeScanningConfigFile, dump(augmentedConfig)); return codeScanningConfigFile; } @@ -154274,9 +154277,9 @@ async function getJobRunUuidSarifOptions() { } // src/autobuild.ts -async function determineAutobuildLanguages(codeql, config, logger) { +async function determineAutobuildLanguages(codeql, config, logger2) { if (config.buildMode === "none" /* None */ || config.buildMode === "manual" /* Manual */) { - logger.info( + logger2.info( `Using build mode "${config.buildMode}", nothing to autobuild. See ${"https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages#codeql-build-modes" /* CODEQL_BUILD_MODES */} for more information.` ); return void 0; @@ -154286,7 +154289,7 @@ async function determineAutobuildLanguages(codeql, config, logger) { async (language) => await codeql.isTracedLanguage(language) ); if (autobuildLanguages.length === 0) { - logger.info( + logger2.info( "None of the languages in this project require extra build steps" ); return void 0; @@ -154301,9 +154304,9 @@ async function determineAutobuildLanguages(codeql, config, logger) { if (autobuildLanguages.length !== autobuildLanguagesWithoutGo.length) { languages.push("go" /* go */); } - logger.debug(`Will autobuild ${languages.join(" and ")}.`); + logger2.debug(`Will autobuild ${languages.join(" and ")}.`); if (autobuildLanguagesWithoutGo.length > 1) { - logger.warning( + logger2.warning( `We will only automatically build ${languages.join( " and " )} code. If you wish to scan ${autobuildLanguagesWithoutGo.slice(1).join( @@ -154313,7 +154316,7 @@ async function determineAutobuildLanguages(codeql, config, logger) { } return languages; } -async function setupCppAutobuild(codeql, logger) { +async function setupCppAutobuild(codeql, logger2) { const envVar = featureConfig["cpp_dependency_installation_enabled" /* CppDependencyInstallation */].envVar; const featureName = "C++ automatic installation of dependencies"; const gitHubVersion = await getGitHubVersion(); @@ -154322,30 +154325,30 @@ async function setupCppAutobuild(codeql, logger) { gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); if (await features.getValue("cpp_dependency_installation_enabled" /* CppDependencyInstallation */, codeql)) { if (process.env["RUNNER_ENVIRONMENT"] === "self-hosted" && process.env[envVar] !== "true") { - logger.info( + logger2.info( `Disabling ${featureName} as we are on a self-hosted runner.${getWorkflowEventName() !== "dynamic" ? ` To override this, set the ${envVar} environment variable to 'true' in your workflow. See ${"https://docs.github.com/en/actions/learn-github-actions/variables#defining-environment-variables-for-a-single-workflow" /* DEFINE_ENV_VARIABLES */} for more information.` : ""}` ); core11.exportVariable(envVar, "false"); } else { - logger.info( + logger2.info( `Enabling ${featureName}. This can be disabled by setting the ${envVar} environment variable to 'false'. See ${"https://docs.github.com/en/actions/learn-github-actions/variables#defining-environment-variables-for-a-single-workflow" /* DEFINE_ENV_VARIABLES */} for more information.` ); core11.exportVariable(envVar, "true"); } } else { - logger.info(`Disabling ${featureName}.`); + logger2.info(`Disabling ${featureName}.`); core11.exportVariable(envVar, "false"); } } -async function runAutobuild(config, language, logger) { - logger.startGroup(`Attempting to automatically build ${language} code`); +async function runAutobuild(config, language, logger2) { + logger2.startGroup(`Attempting to automatically build ${language} code`); const codeQL = await getCodeQL(config.codeQLCmd); if (language === "cpp" /* cpp */) { - await setupCppAutobuild(codeQL, logger); + await setupCppAutobuild(codeQL, logger2); } if (config.buildMode) { await codeQL.extractUsingBuildMode(config, language); @@ -154355,7 +154358,7 @@ async function runAutobuild(config, language, logger) { if (language === "go" /* go */) { core11.exportVariable("CODEQL_ACTION_DID_AUTOBUILD_GOLANG" /* DID_AUTOBUILD_GOLANG */, "true"); } - logger.endGroup(); + logger2.endGroup(); } // src/dependency-caching.ts @@ -154446,22 +154449,22 @@ var defaultCacheConfigs = { async function makeGlobber(patterns) { return glob.create(patterns.join("\n")); } -async function checkHashPatterns(codeql, features, language, cacheConfig, checkType, logger) { +async function checkHashPatterns(codeql, features, language, cacheConfig, checkType, logger2) { const patterns = await cacheConfig.getHashPatterns(codeql, features); if (patterns === void 0) { - logger.info( + logger2.info( `Skipping ${checkType} of dependency cache for ${language} as we cannot calculate a hash for the cache key.` ); } return patterns; } -async function downloadDependencyCaches(codeql, features, languages, logger) { +async function downloadDependencyCaches(codeql, features, languages, logger2) { const status = []; const restoredKeys = []; for (const language of languages) { const cacheConfig = defaultCacheConfigs[language]; if (cacheConfig === void 0) { - logger.info( + logger2.info( `Skipping download of dependency cache for ${language} as we have no caching configuration for it.` ); continue; @@ -154472,7 +154475,7 @@ async function downloadDependencyCaches(codeql, features, languages, logger) { language, cacheConfig, "download", - logger + logger2 ); if (patterns === void 0) { status.push({ language, hit_kind: "no-hash" /* NoHash */ }); @@ -154482,7 +154485,7 @@ async function downloadDependencyCaches(codeql, features, languages, logger) { const restoreKeys = [ await cachePrefix2(codeql, features, language) ]; - logger.info( + logger2.info( `Downloading cache for ${language} with key ${primaryKey} and restore keys ${restoreKeys.join( ", " )}` @@ -154495,7 +154498,7 @@ async function downloadDependencyCaches(codeql, features, languages, logger) { ); const download_duration_ms = Math.round(performance.now() - start); if (hitKey !== void 0) { - logger.info(`Cache hit on key ${hitKey} for ${language}.`); + logger2.info(`Cache hit on key ${hitKey} for ${language}.`); let hit_kind = "partial" /* Partial */; if (hitKey === primaryKey) { hit_kind = "exact" /* Exact */; @@ -154508,17 +154511,17 @@ async function downloadDependencyCaches(codeql, features, languages, logger) { restoredKeys.push(hitKey); } else { status.push({ language, hit_kind: "miss" /* Miss */ }); - logger.info(`No suitable cache found for ${language}.`); + logger2.info(`No suitable cache found for ${language}.`); } } return { statusReport: status, restoredKeys }; } -async function uploadDependencyCaches(codeql, features, config, logger) { +async function uploadDependencyCaches(codeql, features, config, logger2) { const status = []; for (const language of config.languages) { const cacheConfig = defaultCacheConfigs[language]; if (cacheConfig === void 0) { - logger.info( + logger2.info( `Skipping upload of dependency cache for ${language} as we have no caching configuration for it.` ); continue; @@ -154529,7 +154532,7 @@ async function uploadDependencyCaches(codeql, features, config, logger) { language, cacheConfig, "upload", - logger + logger2 ); if (patterns === void 0) { status.push({ language, result: "no-hash" /* NoHash */ }); @@ -154542,17 +154545,17 @@ async function uploadDependencyCaches(codeql, features, config, logger) { } const size = await getTotalCacheSize( await cacheConfig.getDependencyPaths(codeql, features), - logger, + logger2, true ); if (size === 0) { status.push({ language, result: "empty" /* Empty */ }); - logger.info( + logger2.info( `Skipping upload of dependency cache for ${language} since it is empty.` ); continue; } - logger.info( + logger2.info( `Uploading cache of size ${size} for ${language} with key ${key}...` ); try { @@ -154570,10 +154573,10 @@ async function uploadDependencyCaches(codeql, features, config, logger) { }); } catch (error3) { if (error3 instanceof actionsCache4.ReserveCacheError) { - logger.info( + logger2.info( `Not uploading cache for ${language}, because ${key} is already in use.` ); - logger.debug(error3.message); + logger2.debug(error3.message); status.push({ language, result: "duplicate" /* Duplicate */ }); } else { throw error3; @@ -154612,7 +154615,7 @@ async function cachePrefix2(codeql, features, language) { const featurePrefix = await getFeaturePrefix(codeql, features, language); return `${prefix}-${featurePrefix}${CODEQL_DEPENDENCY_CACHE_VERSION}-${runnerOs}-${language}-`; } -async function getDependencyCacheUsage(logger) { +async function getDependencyCacheUsage(logger2) { try { const caches = await listActionsCaches(CODEQL_DEPENDENCY_CACHE_PREFIX); const totalSize = caches.reduce( @@ -154621,7 +154624,7 @@ async function getDependencyCacheUsage(logger) { ); return { count: caches.length, size_bytes: totalSize }; } catch (err) { - logger.warning( + logger2.warning( `Unable to retrieve information about dependency cache usage: ${getErrorMessage(err)}` ); } @@ -154644,32 +154647,32 @@ var CodeQLAnalysisError = class extends Error { message; error; }; -async function setupPythonExtractor(logger) { +async function setupPythonExtractor(logger2) { const codeqlPython = process.env["CODEQL_PYTHON"]; if (codeqlPython === void 0 || codeqlPython.length === 0) { return; } - logger.warning( + logger2.warning( "The CODEQL_PYTHON environment variable is no longer supported. Please remove it from your workflow. This environment variable was originally used to specify a Python executable that included the dependencies of your Python code, however Python analysis no longer uses these dependencies.\nIf you used CODEQL_PYTHON to force the version of Python to analyze as, please use CODEQL_EXTRACTOR_PYTHON_ANALYSIS_VERSION instead, such as 'CODEQL_EXTRACTOR_PYTHON_ANALYSIS_VERSION=2.7' or 'CODEQL_EXTRACTOR_PYTHON_ANALYSIS_VERSION=3.11'." ); return; } -async function runExtraction(codeql, features, config, logger) { +async function runExtraction(codeql, features, config, logger2) { for (const language of config.languages) { - if (dbIsFinalized(config, language, logger)) { - logger.debug( + if (dbIsFinalized(config, language, logger2)) { + logger2.debug( `Database for ${language} has already been finalized, skipping extraction.` ); continue; } if (await shouldExtractLanguage(codeql, config, language)) { - logger.startGroup(`Extracting ${language}`); + logger2.startGroup(`Extracting ${language}`); if (language === "python" /* python */) { - await setupPythonExtractor(logger); + await setupPythonExtractor(logger2); } if (config.buildMode) { if (language === "cpp" /* cpp */ && config.buildMode === "autobuild" /* Autobuild */) { - await setupCppAutobuild(codeql, logger); + await setupCppAutobuild(codeql, logger2); } if (language === "java" /* java */ && config.buildMode === "none" /* None */) { process.env["CODEQL_EXTRACTOR_JAVA_OPTION_BUILDLESS_DEPENDENCY_DIR"] = getJavaTempDependencyDir(); @@ -154681,14 +154684,14 @@ async function runExtraction(codeql, features, config, logger) { } else { await codeql.extractScannedLanguage(config, language); } - logger.endGroup(); + logger2.endGroup(); } } } async function shouldExtractLanguage(codeql, config, language) { return config.buildMode === "none" /* None */ || config.buildMode === "autobuild" /* Autobuild */ && process.env["CODEQL_ACTION_AUTOBUILD_DID_COMPLETE_SUCCESSFULLY" /* AUTOBUILD_DID_COMPLETE_SUCCESSFULLY */] !== "true" || !config.buildMode && await codeql.isScannedLanguage(language); } -function dbIsFinalized(config, language, logger) { +function dbIsFinalized(config, language, logger2) { const dbPath = getCodeQLDatabasePath(config, language); try { const dbInfo = load( @@ -154696,31 +154699,31 @@ function dbIsFinalized(config, language, logger) { ); return !("inProgress" in dbInfo); } catch { - logger.warning( + logger2.warning( `Could not check whether database for ${language} was finalized. Assuming it is not.` ); return false; } } -async function finalizeDatabaseCreation(codeql, features, config, threadsFlag, memoryFlag, logger) { +async function finalizeDatabaseCreation(codeql, features, config, threadsFlag, memoryFlag, logger2) { const extractionStart = import_perf_hooks3.performance.now(); - await runExtraction(codeql, features, config, logger); + await runExtraction(codeql, features, config, logger2); const extractionTime = import_perf_hooks3.performance.now() - extractionStart; const trapImportStart = import_perf_hooks3.performance.now(); for (const language of config.languages) { - if (dbIsFinalized(config, language, logger)) { - logger.info( + if (dbIsFinalized(config, language, logger2)) { + logger2.info( `There is already a finalized database for ${language} at the location where the CodeQL Action places databases, so we did not create one.` ); } else { - logger.startGroup(`Finalizing ${language}`); + logger2.startGroup(`Finalizing ${language}`); await codeql.finalizeDatabase( getCodeQLDatabasePath(config, language), threadsFlag, memoryFlag, config.debugMode ); - logger.endGroup(); + logger2.endGroup(); } } const trapImportTime = import_perf_hooks3.performance.now() - trapImportStart; @@ -154729,24 +154732,24 @@ async function finalizeDatabaseCreation(codeql, features, config, threadsFlag, m trap_import_duration_ms: Math.round(trapImportTime) }; } -async function setupDiffInformedQueryRun(logger) { +async function setupDiffInformedQueryRun(logger2) { return await withGroupAsync( "Generating diff range extension pack", async () => { - const diffRanges = readDiffRangesJsonFile(logger); + const diffRanges = readDiffRangesJsonFile(logger2); if (diffRanges === void 0) { - logger.info( + logger2.info( "No precomputed diff ranges found; skipping diff-informed analysis stage." ); return void 0; } const checkoutPath = getRequiredInput("checkout_path"); const packDir = writeDiffRangeDataExtensionPack( - logger, + logger2, diffRanges, checkoutPath ); - logger.info( + logger2.info( `Successfully created diff range extension pack at ${packDir}.` ); return packDir; @@ -154772,7 +154775,7 @@ extensions: } return header + data; } -function writeDiffRangeDataExtensionPack(logger, ranges, checkoutPath) { +function writeDiffRangeDataExtensionPack(logger2, ranges, checkoutPath) { if (ranges.length === 0) { ranges = [{ path: "", startLine: 0, endLine: 0 }]; } @@ -154796,7 +154799,7 @@ dataExtensions: ); const extensionFilePath = path16.join(diffRangeDir, "pr-diff-range.yml"); fs17.writeFileSync(extensionFilePath, extensionContents); - logger.debug( + logger2.debug( `Wrote pr-diff-range extension pack to ${extensionFilePath}: ${extensionContents}` ); @@ -154818,7 +154821,7 @@ function resolveQuerySuiteAlias(language, maybeSuite) { function addSarifExtension(analysis, base) { return `${base}${analysis.sarifExtension}`; } -async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir, automationDetailsId, codeql, config, logger, features) { +async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir, automationDetailsId, codeql, config, logger2, features) { const statusReport = {}; const queryFlags = [memoryFlag, threadsFlag]; const incrementalMode = []; @@ -154849,11 +154852,11 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir } } } - logger.startGroup(`Running queries for ${language}`); + logger2.startGroup(`Running queries for ${language}`); const startTimeRunQueries = (/* @__PURE__ */ new Date()).getTime(); const databasePath = getCodeQLDatabasePath(config, language); await codeql.databaseRunQueries(databasePath, queryFlags, queries); - logger.debug(`Finished running queries for ${language}.`); + logger2.debug(`Finished running queries for ${language}.`); statusReport[`analyze_builtin_queries_${language}_duration_ms`] = (/* @__PURE__ */ new Date()).getTime() - startTimeRunQueries; const startTimeInterpretResults = /* @__PURE__ */ new Date(); const { summary: analysisSummary, sarifFile } = await runInterpretResultsFor( @@ -154876,15 +154879,15 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir } const endTimeInterpretResults = /* @__PURE__ */ new Date(); statusReport[`interpret_results_${language}_duration_ms`] = endTimeInterpretResults.getTime() - startTimeInterpretResults.getTime(); - logger.endGroup(); + logger2.endGroup(); if (analysisSummary.trim()) { - logger.info(analysisSummary); + logger2.info(analysisSummary); } if (qualityAnalysisSummary?.trim()) { - logger.info(qualityAnalysisSummary); + logger2.info(qualityAnalysisSummary); } if (!config.enableFileCoverageInformation) { - logger.info( + logger2.info( "To speed up pull request analysis, file coverage information is only enabled when analyzing the default branch and protected branches." ); } @@ -154916,8 +154919,8 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir } return statusReport; async function runInterpretResultsFor(analysis, language, queries, enableDebugLogging) { - logger.info(`Interpreting ${analysis.name} results for ${language}`); - const category = analysis.fixCategory(logger, automationDetailsId); + logger2.info(`Interpreting ${analysis.name} results for ${language}`); + const category = analysis.fixCategory(logger2, automationDetailsId); const sarifFile = path16.join( sarifFolder, addSarifExtension(analysis, language) @@ -154963,7 +154966,7 @@ async function runQueries(sarifFolder, memoryFlag, threadsFlag, diffRangePackDir return perQueryAlertCounts; } } -async function runFinalize(features, outputDir, threadsFlag, memoryFlag, codeql, config, logger) { +async function runFinalize(features, outputDir, threadsFlag, memoryFlag, codeql, config, logger2) { try { await fs17.promises.rm(outputDir, { force: true, recursive: true }); } catch (error3) { @@ -154978,19 +154981,19 @@ async function runFinalize(features, outputDir, threadsFlag, memoryFlag, codeql, config, threadsFlag, memoryFlag, - logger + logger2 ); if (process.env["CODEQL_ACTION_AUTOBUILD_DID_COMPLETE_SUCCESSFULLY" /* AUTOBUILD_DID_COMPLETE_SUCCESSFULLY */] !== "true") { - await endTracingForCluster(codeql, config, logger); + await endTracingForCluster(codeql, config, logger2); } return timings; } -async function warnIfGoInstalledAfterInit(config, logger) { +async function warnIfGoInstalledAfterInit(config, logger2) { const goInitPath = process.env["CODEQL_ACTION_GO_BINARY" /* GO_BINARY_LOCATION */]; if (process.env["CODEQL_ACTION_DID_AUTOBUILD_GOLANG" /* DID_AUTOBUILD_GOLANG */] !== "true" && goInitPath !== void 0) { const goBinaryPath = await io5.which("go", true); if (goInitPath !== goBinaryPath) { - logger.warning( + logger2.warning( `Expected \`which go\` to return ${goInitPath}, but got ${goBinaryPath}: please ensure that the correct version of Go is installed before the \`codeql-action/init\` Action is used.` ); addDiagnostic( @@ -155016,27 +155019,27 @@ async function warnIfGoInstalledAfterInit(config, logger) { // src/database-upload.ts var fs18 = __toESM(require("fs")); -async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetails, features, logger) { +async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetails, features, logger2) { if (getRequiredInput("upload-database") !== "true") { - logger.debug("Database upload disabled in workflow. Skipping upload."); + logger2.debug("Database upload disabled in workflow. Skipping upload."); return []; } if (!config.analysisKinds.includes("code-scanning" /* CodeScanning */)) { - logger.debug( + logger2.debug( `Not uploading database because 'analysis-kinds: ${"code-scanning" /* CodeScanning */}' is not enabled.` ); return []; } if (isInTestMode()) { - logger.debug("In test mode. Skipping database upload."); + logger2.debug("In test mode. Skipping database upload."); return []; } if (config.gitHubVersion.type !== "GitHub.com" /* DOTCOM */ && config.gitHubVersion.type !== "GitHub Enterprise Cloud with data residency" /* GHEC_DR */) { - logger.debug("Not running against github.com or GHEC-DR. Skipping upload."); + logger2.debug("Not running against github.com or GHEC-DR. Skipping upload."); return []; } if (!await isAnalyzingDefaultBranch()) { - logger.debug("Not analyzing default branch. Skipping upload."); + logger2.debug("Not analyzing default branch. Skipping upload."); return []; } const shouldUploadOverlayBase = config.overlayDatabaseMode === "overlay-base" /* OverlayBase */ && await features.getValue("upload_overlay_db_to_api" /* UploadOverlayDbToApi */, codeql); @@ -155074,13 +155077,13 @@ async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetai if (!isRetryable) { throw e; } else if (attempt === maxAttempts) { - logger.error( + logger2.error( `Maximum retry attempts exhausted (${attempt}), aborting database upload` ); throw e; } const backoffMs = 15e3 * Math.pow(2, attempt - 1); - logger.debug( + logger2.debug( `Database upload attempt ${attempt} of ${maxAttempts} failed for ${language}: ${getErrorMessage(e)}. Retrying in ${backoffMs / 1e3}s...` ); await new Promise((resolve13) => setTimeout(resolve13, backoffMs)); @@ -155092,9 +155095,9 @@ async function cleanupAndUploadDatabases(repositoryNwo, codeql, config, apiDetai is_overlay_base: shouldUploadOverlayBase, upload_duration_ms: uploadDurationMs }); - logger.debug(`Successfully uploaded database for ${language}`); + logger2.debug(`Successfully uploaded database for ${language}`); } catch (e) { - logger.warning( + logger2.warning( `Failed to upload database for ${language}: ${getErrorMessage(e)}` ); reports.push({ @@ -155197,7 +155200,7 @@ function setJobStatusIfUnsuccessful(actionStatus) { ); } } -async function createStatusReportBase(actionName, status, actionStartedAt, config, diskInfo, logger, cause, exception) { +async function createStatusReportBase(actionName, status, actionStartedAt, config, diskInfo, logger2, cause, exception) { try { const commitOid = getOptionalInput("sha") || process.env["GITHUB_SHA"] || ""; const ref = await getRef(); @@ -155251,7 +155254,7 @@ async function createStatusReportBase(actionName, status, actionStartedAt, confi try { statusReport.actions_event_name = getWorkflowEventName(); } catch (e) { - logger.warning( + logger2.warning( `Could not determine the workflow event name: ${getErrorMessage(e)}.` ); } @@ -155290,7 +155293,7 @@ async function createStatusReportBase(actionName, status, actionStartedAt, confi } return statusReport; } catch (e) { - logger.warning( + logger2.warning( `Failed to gather information for telemetry: ${getErrorMessage(e)}. Will skip sending status report.` ); if (isInTestMode()) { @@ -155400,7 +155403,7 @@ async function createInitWithConfigStatusReport(config, initStatusReport, config ) }; } -async function sendUnhandledErrorStatusReport(actionName, actionStartedAt, error3, logger) { +async function sendUnhandledErrorStatusReport(actionName, actionStartedAt, error3, logger2) { try { const statusReport = await createStatusReportBase( actionName, @@ -155408,7 +155411,7 @@ async function sendUnhandledErrorStatusReport(actionName, actionStartedAt, error actionStartedAt, void 0, void 0, - logger, + logger2, `Unhandled CodeQL Action error: ${getErrorMessage(error3)}`, error3 instanceof Error ? error3.stack : void 0 ); @@ -155416,7 +155419,7 @@ async function sendUnhandledErrorStatusReport(actionName, actionStartedAt, error await sendStatusReport(statusReport); } } catch (e) { - logger.warning( + logger2.warning( `Failed to send the unhandled error status report: ${getErrorMessage(e)}.` ); if (isInTestMode()) { @@ -156457,7 +156460,7 @@ async function hash(callback, filepath) { updateHash(0); } } -function locationUpdateCallback(result, location, logger) { +function locationUpdateCallback(result, location, logger2) { let locationStartLine = location.physicalLocation?.region?.startLine; if (locationStartLine === void 0) { locationStartLine = 1; @@ -156473,29 +156476,29 @@ function locationUpdateCallback(result, location, logger) { if (!existingFingerprint) { result.partialFingerprints.primaryLocationLineHash = hashValue; } else if (existingFingerprint !== hashValue) { - logger.warning( + logger2.warning( `Calculated fingerprint of ${hashValue} for file ${location.physicalLocation.artifactLocation.uri} line ${lineNumber}, but found existing inconsistent fingerprint value ${existingFingerprint}` ); } }; } -function resolveUriToFile(location, artifacts, sourceRoot, logger) { +function resolveUriToFile(location, artifacts, sourceRoot, logger2) { if (!location.uri && location.index !== void 0) { if (typeof location.index !== "number" || location.index < 0 || location.index >= artifacts.length || !isObject(artifacts[location.index].location)) { - logger.debug(`Ignoring location as index "${location.index}" is invalid`); + logger2.debug(`Ignoring location as index "${location.index}" is invalid`); return void 0; } location = artifacts[location.index].location; } if (typeof location.uri !== "string") { - logger.debug(`Ignoring location as URI "${location.uri}" is invalid`); + logger2.debug(`Ignoring location as URI "${location.uri}" is invalid`); return void 0; } let uri; try { uri = decodeURIComponent(location.uri); } catch { - logger.debug(`Ignoring location as URI "${location.uri}" is invalid`); + logger2.debug(`Ignoring location as URI "${location.uri}" is invalid`); return void 0; } const fileUriPrefix = "file://"; @@ -156503,14 +156506,14 @@ function resolveUriToFile(location, artifacts, sourceRoot, logger) { uri = uri.substring(fileUriPrefix.length); } if (uri.indexOf("://") !== -1) { - logger.debug( + logger2.debug( `Ignoring location URI "${uri}" as the scheme is not recognised` ); return void 0; } const srcRootPrefix = `${sourceRoot}/`; if (uri.startsWith("/") && !uri.startsWith(srcRootPrefix)) { - logger.debug( + logger2.debug( `Ignoring location URI "${uri}" as it is outside of the src root` ); return void 0; @@ -156519,17 +156522,17 @@ function resolveUriToFile(location, artifacts, sourceRoot, logger) { uri = srcRootPrefix + uri; } if (!fs19.existsSync(uri)) { - logger.debug(`Unable to compute fingerprint for non-existent file: ${uri}`); + logger2.debug(`Unable to compute fingerprint for non-existent file: ${uri}`); return void 0; } if (fs19.statSync(uri).isDirectory()) { - logger.debug(`Unable to compute fingerprint for directory: ${uri}`); + logger2.debug(`Unable to compute fingerprint for directory: ${uri}`); return void 0; } return uri; } -async function addFingerprints(sarifLog, sourceRoot, logger) { - logger.info( +async function addFingerprints(sarifLog, sourceRoot, logger2) { + logger2.info( `Adding fingerprints to SARIF file. See ${"https://docs.github.com/en/code-security/reference/code-scanning/sarif-support-for-code-scanning#data-for-preventing-duplicated-alerts" /* TRACK_CODE_SCANNING_ALERTS_ACROSS_RUNS */} for more information.` ); const callbacksByFile = {}; @@ -156538,7 +156541,7 @@ async function addFingerprints(sarifLog, sourceRoot, logger) { for (const result of run9.results || []) { const primaryLocation = (result.locations || [])[0]; if (!primaryLocation?.physicalLocation?.artifactLocation) { - logger.debug( + logger2.debug( `Unable to compute fingerprint for invalid location: ${JSON.stringify( primaryLocation )}` @@ -156552,7 +156555,7 @@ async function addFingerprints(sarifLog, sourceRoot, logger) { primaryLocation.physicalLocation.artifactLocation, artifacts, sourceRoot, - logger + logger2 ); if (!filepath) { continue; @@ -156561,7 +156564,7 @@ async function addFingerprints(sarifLog, sourceRoot, logger) { callbacksByFile[filepath] = []; } callbacksByFile[filepath].push( - locationUpdateCallback(result, primaryLocation, logger) + locationUpdateCallback(result, primaryLocation, logger2) ); } } @@ -156583,8 +156586,8 @@ var core13 = __toESM(require_core()); var toolrunner4 = __toESM(require_toolrunner()); var github2 = __toESM(require_github()); var io6 = __toESM(require_io()); -async function initCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger) { - logger.startGroup("Setup CodeQL tools"); +async function initCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliVersion, rawLanguages, useOverlayAwareDefaultCliVersion, features, logger2) { + logger2.startGroup("Setup CodeQL tools"); const { codeql, toolsDownloadStatusReport, @@ -156600,11 +156603,11 @@ async function initCodeQL(toolsInput, apiDetails, tempDir, variant, defaultCliVe rawLanguages, useOverlayAwareDefaultCliVersion, features, - logger, + logger2, true ); await codeql.printVersion(); - logger.endGroup(); + logger2.endGroup(); return { codeql, toolsDownloadStatusReport, @@ -156618,7 +156621,7 @@ async function initConfig2(features, inputs) { return await initConfig(features, inputs); }); } -async function runDatabaseInitCluster(databaseInitEnvironment, codeql, config, sourceRoot, processName, qlconfigFile, logger) { +async function runDatabaseInitCluster(databaseInitEnvironment, codeql, config, sourceRoot, processName, qlconfigFile, logger2) { fs20.mkdirSync(config.dbLocation, { recursive: true }); await wrapEnvironment( databaseInitEnvironment, @@ -156627,14 +156630,14 @@ async function runDatabaseInitCluster(databaseInitEnvironment, codeql, config, s sourceRoot, processName, qlconfigFile, - logger + logger2 ) ); } -async function checkPacksForOverlayCompatibility(codeql, config, logger) { +async function checkPacksForOverlayCompatibility(codeql, config, logger2) { const codeQlOverlayVersion = (await codeql.getVersion()).overlayVersion; if (codeQlOverlayVersion === void 0) { - logger.warning("The CodeQL CLI does not support overlay analysis."); + logger2.warning("The CodeQL CLI does not support overlay analysis."); return false; } for (const language of config.languages) { @@ -156644,7 +156647,7 @@ async function checkPacksForOverlayCompatibility(codeql, config, logger) { (packDir) => !checkPackForOverlayCompatibility( packDir, codeQlOverlayVersion, - logger + logger2 ) )) { return false; @@ -156652,7 +156655,7 @@ async function checkPacksForOverlayCompatibility(codeql, config, logger) { } return true; } -function checkPackForOverlayCompatibility(packDir, codeQlOverlayVersion, logger) { +function checkPackForOverlayCompatibility(packDir, codeQlOverlayVersion, logger2) { try { let qlpackPath = path18.join(packDir, "qlpack.yml"); if (!fs20.existsSync(qlpackPath)) { @@ -156666,7 +156669,7 @@ function checkPackForOverlayCompatibility(packDir, codeQlOverlayVersion, logger) } const packInfoPath = path18.join(packDir, ".packinfo"); if (!fs20.existsSync(packInfoPath)) { - logger.warning( + logger2.warning( `The query pack at ${packDir} does not have a .packinfo file, so it cannot support overlay analysis. Recompiling the query pack with the latest CodeQL CLI should solve this problem.` ); return false; @@ -156676,19 +156679,19 @@ function checkPackForOverlayCompatibility(packDir, codeQlOverlayVersion, logger) ); const packOverlayVersion = packInfoFileContents.overlayVersion; if (typeof packOverlayVersion !== "number") { - logger.warning( + logger2.warning( `The .packinfo file for the query pack at ${packDir} does not have the overlayVersion field, which indicates that the pack is not compatible with overlay analysis.` ); return false; } if (packOverlayVersion !== codeQlOverlayVersion) { - logger.warning( + logger2.warning( `The query pack at ${packDir} was compiled with overlay version ${packOverlayVersion}, but the CodeQL CLI supports overlay version ${codeQlOverlayVersion}. The query pack needs to be recompiled to support overlay analysis.` ); return false; } } catch (e) { - logger.warning( + logger2.warning( `Error while checking pack at ${packDir} for overlay compatibility: ${getErrorMessage(e)}` ); return false; @@ -156707,10 +156710,10 @@ async function checkInstallPython311(languages, codeql) { ]).exec(); } } -function cleanupDatabaseClusterDirectory(config, logger, options = {}, rmSync5 = fs20.rmSync) { +function cleanupDatabaseClusterDirectory(config, logger2, options = {}, rmSync5 = fs20.rmSync) { if (fs20.existsSync(config.dbLocation) && (fs20.statSync(config.dbLocation).isFile() || fs20.readdirSync(config.dbLocation).length > 0)) { if (!options.disableExistingDirectoryWarning) { - logger.warning( + logger2.warning( `The database cluster directory ${config.dbLocation} must be empty. Attempting to clean it up.` ); } @@ -156720,7 +156723,7 @@ function cleanupDatabaseClusterDirectory(config, logger, options = {}, rmSync5 = maxRetries: 3, recursive: true }); - logger.info( + logger2.info( `Cleaned up database cluster directory ${config.dbLocation}.` ); } catch (e) { @@ -156781,7 +156784,7 @@ async function getFileCoverageInformationEnabled(debugMode, codeql, features, re showDeprecationWarning: false }; } -function logFileCoverageOnPrsDeprecationWarning(logger) { +function logFileCoverageOnPrsDeprecationWarning(logger2) { if (process.env["CODEQL_ACTION_DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION" /* DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION */]) { return; } @@ -156808,7 +156811,7 @@ To opt out of this change, switch to an advanced setup workflow and ${envVarOptO To opt out of this change, ${envVarOptOut}`; } - logger.warning(message); + logger2.warning(message); core13.exportVariable("CODEQL_ACTION_DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION" /* DID_LOG_FILE_COVERAGE_ON_PRS_DEPRECATION */, "true"); } @@ -156830,12 +156833,12 @@ function getToolNames(sarifFile) { function readSarifFile(sarifFilePath) { return JSON.parse(fs21.readFileSync(sarifFilePath, "utf8")); } -function combineSarifFiles(sarifFiles, logger) { - logger.info(`Loading SARIF file(s)`); +function combineSarifFiles(sarifFiles, logger2) { + logger2.info(`Loading SARIF file(s)`); const runs = []; let version = void 0; for (const sarifFile of sarifFiles) { - logger.debug(`Loading SARIF file: ${sarifFile}`); + logger2.debug(`Loading SARIF file: ${sarifFile}`); const sarifLog = readSarifFile(sarifFile); if (version === void 0) { version = sarifLog.version; @@ -156909,32 +156912,32 @@ async function shouldDisableCombineSarifFiles(sarifObjects, githubVersion) { } return true; } -async function combineSarifFilesUsingCLI(sarifFiles, gitHubVersion, features, logger) { - logger.info("Combining SARIF files using the CodeQL CLI"); +async function combineSarifFilesUsingCLI(sarifFiles, gitHubVersion, features, logger2) { + logger2.info("Combining SARIF files using the CodeQL CLI"); const sarifObjects = sarifFiles.map(readSarifFile); const deprecationWarningMessage = gitHubVersion.type === "GitHub Enterprise Server" /* GHES */ ? "and will be removed in GitHub Enterprise Server 3.18" : "and will be removed in July 2025"; const deprecationMoreInformationMessage = "For more information, see https://github.blog/changelog/2024-05-06-code-scanning-will-stop-combining-runs-from-a-single-upload"; if (!areAllRunsProducedByCodeQL(sarifObjects)) { await throwIfCombineSarifFilesDisabled(sarifObjects, gitHubVersion); - logger.debug( + logger2.debug( "Not all SARIF files were produced by CodeQL. Merging files in the action." ); if (await shouldShowCombineSarifFilesDeprecationWarning(sarifObjects)) { - logger.warning( + logger2.warning( `Uploading multiple SARIF runs with the same category is deprecated ${deprecationWarningMessage}. Please update your workflow to upload a single run per category. ${deprecationMoreInformationMessage}` ); core14.exportVariable("CODEQL_MERGE_SARIF_DEPRECATION_WARNING", "true"); } - return combineSarifFiles(sarifFiles, logger); + return combineSarifFiles(sarifFiles, logger2); } let codeQL; let tempDir = getTemporaryDirectory(); - const config = await getConfig(tempDir, logger); + const config = await getConfig(tempDir, logger2); if (config !== void 0) { codeQL = await getCodeQL(config.codeQLCmd); tempDir = config.tempDir; } else { - logger.info( + logger2.info( "Initializing CodeQL since the 'init' Action was not called before this step." ); const apiDetails = { @@ -156958,7 +156961,7 @@ async function combineSarifFilesUsingCLI(sarifFiles, gitHubVersion, features, lo false, // useOverlayAwareDefaultCliVersion: upload-lib does not run analysis features, - logger + logger2 ); codeQL = initCodeQLResult.codeql; } @@ -156995,17 +156998,17 @@ function getAutomationID2(category, analysis_key, environment) { } return computeAutomationID(analysis_key, environment); } -async function uploadPayload(payload, repositoryNwo, logger, analysis) { - logger.info("Uploading results"); +async function uploadPayload(payload, repositoryNwo, logger2, analysis) { + logger2.info("Uploading results"); if (shouldSkipSarifUpload()) { const payloadSaveFile = path19.join( getTemporaryDirectory(), `payload-${analysis.kind}.json` ); - logger.info( + logger2.info( `SARIF upload disabled by an environment variable. Saving to ${payloadSaveFile}` ); - logger.info(`Payload: ${JSON.stringify(payload, null, 2)}`); + logger2.info(`Payload: ${JSON.stringify(payload, null, 2)}`); fs22.writeFileSync(payloadSaveFile, JSON.stringify(payload, null, 2)); return "dummy-sarif-id"; } @@ -157016,8 +157019,8 @@ async function uploadPayload(payload, repositoryNwo, logger, analysis) { repo: repositoryNwo.repo, data: payload }); - logger.debug(`response status: ${response.status}`); - logger.info("Successfully uploaded results"); + logger2.debug(`response status: ${response.status}`); + logger2.info("Successfully uploaded results"); return response.data.id; } catch (e) { const httpError = asHTTPError(e); @@ -157069,7 +157072,7 @@ function getSarifFilePaths(sarifPath, isSarif) { } return sarifFiles; } -async function getGroupedSarifFilePaths(logger, sarifPath) { +async function getGroupedSarifFilePaths(logger2, sarifPath) { const stats = fs22.statSync(sarifPath, { throwIfNoEntry: false }); if (stats === void 0) { throw new ConfigurationError(`Path does not exist: ${sarifPath}`); @@ -157080,7 +157083,7 @@ async function getGroupedSarifFilePaths(logger, sarifPath) { sarifPath, (name) => path19.extname(name) === ".sarif" ); - logger.debug( + logger2.debug( `Found the following .sarif files in ${sarifPath}: ${unassignedSarifFiles.join(", ")}` ); for (const analysisConfig of SarifScanOrder) { @@ -157088,7 +157091,7 @@ async function getGroupedSarifFilePaths(logger, sarifPath) { analysisConfig.sarifPredicate ); if (filesForCurrentAnalysis.length > 0) { - logger.debug( + logger2.debug( `The following SARIF files are for ${analysisConfig.name}: ${filesForCurrentAnalysis.join(", ")}` ); unassignedSarifFiles = unassignedSarifFiles.filter( @@ -157096,18 +157099,18 @@ async function getGroupedSarifFilePaths(logger, sarifPath) { ); results[analysisConfig.kind] = filesForCurrentAnalysis; } else { - logger.debug(`Found no SARIF files for ${analysisConfig.name}`); + logger2.debug(`Found no SARIF files for ${analysisConfig.name}`); } } if (unassignedSarifFiles.length !== 0) { - logger.warning( + logger2.warning( `Found files in ${sarifPath} which do not belong to any analysis: ${unassignedSarifFiles.join(", ")}` ); } } else { for (const analysisConfig of SarifScanOrder) { if (analysisConfig.kind === "code-scanning" /* CodeScanning */ || analysisConfig.sarifPredicate(sarifPath)) { - logger.debug( + logger2.debug( `Using '${sarifPath}' as a SARIF file for ${analysisConfig.name}.` ); results[analysisConfig.kind] = [sarifPath]; @@ -157142,15 +157145,15 @@ function readSarifFileOrThrow(sarifFilePath) { ); } } -function validateSarifFileSchema(sarifLog, sarifFilePath, logger) { +function validateSarifFileSchema(sarifLog, sarifFilePath, logger2) { if (areAllRunsProducedByCodeQL([sarifLog]) && // We want to validate CodeQL SARIF in testing environments. !getTestingEnvironment()) { - logger.debug( + logger2.debug( `Skipping SARIF schema validation for ${sarifFilePath} as all runs are produced by CodeQL.` ); return true; } - logger.info(`Validating ${sarifFilePath}`); + logger2.info(`Validating ${sarifFilePath}`); const schema = require_sarif_schema_2_1_0(); const result = new jsonschema2.Validator().validate(sarifLog, schema); const warningAttributes = ["uri-reference", "uri"]; @@ -157161,15 +157164,15 @@ function validateSarifFileSchema(sarifLog, sarifFilePath, logger) { (err) => err.name === "format" && typeof err.argument === "string" && warningAttributes.includes(err.argument) ); for (const warning14 of warnings) { - logger.info( + logger2.info( `Warning: '${warning14.instance}' is not a valid URI in '${warning14.property}'.` ); } if (errors.length > 0) { for (const error3 of errors) { - logger.startGroup(`Error details: ${error3.stack}`); - logger.info(JSON.stringify(error3, null, 2)); - logger.endGroup(); + logger2.startGroup(`Error details: ${error3.stack}`); + logger2.info(JSON.stringify(error3, null, 2)); + logger2.endGroup(); } const sarifErrors = errors.map((e) => `- ${e.stack}`); throw new InvalidSarifUploadError( @@ -157213,30 +157216,30 @@ function buildPayload(commitOid, ref, analysisKey, analysisName, zippedSarif, wo } return payloadObj; } -async function postProcessSarifFiles(logger, features, checkoutPath, sarifPaths, category, analysis) { - logger.info(`Post-processing sarif files: ${JSON.stringify(sarifPaths)}`); +async function postProcessSarifFiles(logger2, features, checkoutPath, sarifPaths, category, analysis) { + logger2.info(`Post-processing sarif files: ${JSON.stringify(sarifPaths)}`); const gitHubVersion = await getGitHubVersion(); let sarifLog; - category = analysis.fixCategory(logger, category); + category = analysis.fixCategory(logger2, category); if (sarifPaths.length > 1) { for (const sarifPath of sarifPaths) { const parsedSarif = readSarifFileOrThrow(sarifPath); - validateSarifFileSchema(parsedSarif, sarifPath, logger); + validateSarifFileSchema(parsedSarif, sarifPath, logger2); } sarifLog = await combineSarifFilesUsingCLI( sarifPaths, gitHubVersion, features, - logger + logger2 ); } else { const sarifPath = sarifPaths[0]; sarifLog = readSarifFileOrThrow(sarifPath); - validateSarifFileSchema(sarifLog, sarifPath, logger); + validateSarifFileSchema(sarifLog, sarifPath, logger2); await throwIfCombineSarifFilesDisabled([sarifLog], gitHubVersion); } - sarifLog = filterAlertsByDiffRange(logger, sarifLog); - sarifLog = await addFingerprints(sarifLog, checkoutPath, logger); + sarifLog = filterAlertsByDiffRange(logger2, sarifLog); + sarifLog = await addFingerprints(sarifLog, checkoutPath, logger2); const analysisKey = await getAnalysisKey(); const environment = getRequiredInput("matrix"); sarifLog = populateRunAutomationDetails( @@ -157247,20 +157250,20 @@ async function postProcessSarifFiles(logger, features, checkoutPath, sarifPaths, ); return { sarif: sarifLog, analysisKey, environment }; } -async function writePostProcessedFiles(logger, pathInput, uploadTarget, postProcessingResults) { +async function writePostProcessedFiles(logger2, pathInput, uploadTarget, postProcessingResults) { const outputPath = pathInput || getOptionalEnvVar("CODEQL_ACTION_SARIF_DUMP_DIR" /* SARIF_DUMP_DIR */); if (outputPath !== void 0) { dumpSarifFile( JSON.stringify(postProcessingResults.sarif), outputPath, - logger, + logger2, uploadTarget ); } else { - logger.debug(`Not writing post-processed SARIF files.`); + logger2.debug(`Not writing post-processed SARIF files.`); } } -async function uploadFiles(inputSarifPath, checkoutPath, category, features, logger, uploadTarget) { +async function uploadFiles(inputSarifPath, checkoutPath, category, features, logger2, uploadTarget) { const sarifPaths = getSarifFilePaths( inputSarifPath, uploadTarget.sarifPredicate @@ -157270,13 +157273,13 @@ async function uploadFiles(inputSarifPath, checkoutPath, category, features, log checkoutPath, category, features, - logger, + logger2, uploadTarget ); } -async function uploadSpecifiedFiles(sarifPaths, checkoutPath, category, features, logger, uploadTarget) { +async function uploadSpecifiedFiles(sarifPaths, checkoutPath, category, features, logger2, uploadTarget) { const processingResults = await postProcessSarifFiles( - logger, + logger2, features, checkoutPath, sarifPaths, @@ -157284,21 +157287,21 @@ async function uploadSpecifiedFiles(sarifPaths, checkoutPath, category, features uploadTarget ); return uploadPostProcessedFiles( - logger, + logger2, checkoutPath, uploadTarget, processingResults ); } -async function uploadPostProcessedFiles(logger, checkoutPath, uploadTarget, postProcessingResults) { - logger.startGroup(`Uploading ${uploadTarget.name} results`); +async function uploadPostProcessedFiles(logger2, checkoutPath, uploadTarget, postProcessingResults) { + logger2.startGroup(`Uploading ${uploadTarget.name} results`); const sarifLog = postProcessingResults.sarif; const toolNames = getToolNames(sarifLog); - logger.debug(`Validating that each SARIF run has a unique category`); + logger2.debug(`Validating that each SARIF run has a unique category`); validateUniqueCategory(sarifLog, uploadTarget.sentinelPrefix); - logger.debug(`Serializing SARIF for upload`); + logger2.debug(`Serializing SARIF for upload`); const sarifPayload = JSON.stringify(sarifLog); - logger.debug(`Compressing serialized SARIF`); + logger2.debug(`Compressing serialized SARIF`); const zippedSarif = import_zlib.default.gzipSync(sarifPayload).toString("base64"); const checkoutURI = url.pathToFileURL(checkoutPath).href; const payload = uploadTarget.transformPayload( @@ -157317,18 +157320,18 @@ async function uploadPostProcessedFiles(logger, checkoutPath, uploadTarget, post ) ); const rawUploadSizeBytes = sarifPayload.length; - logger.debug(`Raw upload size: ${rawUploadSizeBytes} bytes`); + logger2.debug(`Raw upload size: ${rawUploadSizeBytes} bytes`); const zippedUploadSizeBytes = zippedSarif.length; - logger.debug(`Base64 zipped upload size: ${zippedUploadSizeBytes} bytes`); + logger2.debug(`Base64 zipped upload size: ${zippedUploadSizeBytes} bytes`); const numResultInSarif = countResultsInSarif(sarifPayload); - logger.debug(`Number of results in upload: ${numResultInSarif}`); + logger2.debug(`Number of results in upload: ${numResultInSarif}`); const sarifID = await uploadPayload( payload, getRepositoryNwo(), - logger, + logger2, uploadTarget ); - logger.endGroup(); + logger2.endGroup(); return { statusReport: { raw_upload_size_bytes: rawUploadSizeBytes, @@ -157338,7 +157341,7 @@ async function uploadPostProcessedFiles(logger, checkoutPath, uploadTarget, post sarifID }; } -function dumpSarifFile(sarifPayload, outputDir, logger, uploadTarget) { +function dumpSarifFile(sarifPayload, outputDir, logger2, uploadTarget) { if (!fs22.existsSync(outputDir)) { fs22.mkdirSync(outputDir, { recursive: true }); } else if (!fs22.lstatSync(outputDir).isDirectory()) { @@ -157350,16 +157353,16 @@ function dumpSarifFile(sarifPayload, outputDir, logger, uploadTarget) { outputDir, `upload${uploadTarget.sarifExtension}` ); - logger.info(`Writing processed SARIF file to ${outputFile}`); + logger2.info(`Writing processed SARIF file to ${outputFile}`); fs22.writeFileSync(outputFile, sarifPayload); } var STATUS_CHECK_INITIAL_BACKOFF_MILLISECONDS = 5 * 1e3; var STATUS_CHECK_BACKOFF_MULTIPLIER = 2; var STATUS_CHECK_MAX_TRIES = 5; -async function waitForProcessing(repositoryNwo, sarifID, logger, options = { +async function waitForProcessing(repositoryNwo, sarifID, logger2, options = { isUnsuccessfulExecution: false }) { - logger.startGroup("Waiting for processing to finish"); + logger2.startGroup("Waiting for processing to finish"); try { const client = getApiClient(); let statusCheckBackoff = STATUS_CHECK_INITIAL_BACKOFF_MILLISECONDS; @@ -157378,20 +157381,20 @@ async function waitForProcessing(repositoryNwo, sarifID, logger, options = { } ); } catch (e) { - logger.warning( + logger2.warning( `An error occurred checking the status of the delivery. ${e} It should still be processed in the background, but errors that occur during processing may not be reported.` ); break; } const status = response.data.processing_status; - logger.info(`Analysis upload status is ${status}.`); + logger2.info(`Analysis upload status is ${status}.`); if (status === "pending") { - logger.debug("Analysis processing is still pending..."); + logger2.debug("Analysis processing is still pending..."); } else if (options.isUnsuccessfulExecution) { handleProcessingResultForUnsuccessfulExecution( response, status, - logger + logger2 ); break; } else if (status === "complete") { @@ -157405,7 +157408,7 @@ ${response.data.errors}`; assertNever(status); } if (statusCheckCount === STATUS_CHECK_MAX_TRIES) { - logger.warning( + logger2.warning( "Timed out waiting for analysis to finish processing. Continuing." ); break; @@ -157415,7 +157418,7 @@ ${response.data.errors}`; } } } finally { - logger.endGroup(); + logger2.endGroup(); } } function shouldConsiderConfigurationError(processingErrors) { @@ -157435,18 +157438,18 @@ function shouldConsiderInvalidRequest(processingErrors) { ) ); } -function handleProcessingResultForUnsuccessfulExecution(response, status, logger) { +function handleProcessingResultForUnsuccessfulExecution(response, status, logger2) { if (status === "failed" && Array.isArray(response.data.errors) && response.data.errors.length === 1 && // eslint-disable-next-line @typescript-eslint/no-unsafe-call response.data.errors[0].toString().startsWith("unsuccessful execution")) { - logger.info( + logger2.info( 'Successfully uploaded a SARIF file for the unsuccessful execution. Received expected "unsuccessful execution" processing error, and no other errors.' ); } else if (status === "failed") { - logger.warning( + logger2.warning( `Failed to upload a SARIF file for the unsuccessful execution. Code scanning status information for the repository may be out of date as a result. Processing errors: ${response.data.errors}` ); } else if (status === "complete") { - logger.debug( + logger2.debug( 'Uploaded a SARIF file for the unsuccessful execution, but did not receive the expected "unsuccessful execution" processing error. This is a known transient issue with the code scanning API, and does not cause out of date code scanning status information.' ); } else { @@ -157474,8 +157477,8 @@ function validateUniqueCategory(sarifLog, sentinelPrefix) { function sanitize(str) { return (str ?? "_").replace(/[^a-zA-Z0-9_]/g, "_").toLocaleUpperCase(); } -function filterAlertsByDiffRange(logger, sarifLog) { - const diffRanges = readDiffRangesJsonFile(logger); +function filterAlertsByDiffRange(logger2, sarifLog) { + const diffRanges = readDiffRangesJsonFile(logger2); if (!diffRanges?.length) { return sarifLog; } @@ -157506,9 +157509,9 @@ function filterAlertsByDiffRange(logger, sarifLog) { } // src/upload-sarif.ts -async function postProcessAndUploadSarif(logger, features, uploadKind, checkoutPath, sarifPath, category, postProcessedOutputPath) { +async function postProcessAndUploadSarif(logger2, features, uploadKind, checkoutPath, sarifPath, category, postProcessedOutputPath) { const sarifGroups = await getGroupedSarifFilePaths( - logger, + logger2, sarifPath ); const uploadResults = {}; @@ -157517,7 +157520,7 @@ async function postProcessAndUploadSarif(logger, features, uploadKind, checkoutP )) { const analysisConfig = getAnalysisConfig(analysisKind); const postProcessingResults = await postProcessSarifFiles( - logger, + logger2, features, checkoutPath, sarifFiles, @@ -157525,14 +157528,14 @@ async function postProcessAndUploadSarif(logger, features, uploadKind, checkoutP analysisConfig ); await writePostProcessedFiles( - logger, + logger2, postProcessedOutputPath, analysisConfig, postProcessingResults ); if (uploadKind === "always") { uploadResults[analysisKind] = await uploadPostProcessedFiles( - logger, + logger2, checkoutPath, analysisConfig, postProcessingResults @@ -157543,15 +157546,15 @@ async function postProcessAndUploadSarif(logger, features, uploadKind, checkoutP } // src/analyze-action.ts -async function sendStatusReport2(startedAt, config, stats, error3, trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, trapCacheCleanup, dependencyCacheResults, databaseUploadResults, logger) { +async function sendStatusReport2(startedAt, config, stats, error3, trapCacheUploadTime, dbCreationTimings, didUploadTrapCaches, trapCacheCleanup, dependencyCacheResults, databaseUploadResults, logger2) { const status = getActionsStatus(error3, stats?.analyze_failure_language); const statusReportBase = await createStatusReportBase( "finish" /* Analyze */, status, startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3?.message, error3?.stack ); @@ -157569,7 +157572,7 @@ async function sendStatusReport2(startedAt, config, stats, error3, trapCacheUplo ...report, trap_cache_upload_duration_ms: Math.round(trapCacheUploadTime || 0), trap_cache_upload_size_bytes: Math.round( - await getTotalCacheSize(Object.values(config.trapCaches), logger) + await getTotalCacheSize(Object.values(config.trapCaches), logger2) ) }; await sendStatusReport(trapCacheUploadStatusReport); @@ -157602,41 +157605,41 @@ function doesGoExtractionOutputExist(config) { ].some((ext) => fileName.endsWith(ext)) ); } -async function runAutobuildIfLegacyGoWorkflow(config, logger) { +async function runAutobuildIfLegacyGoWorkflow(config, logger2) { if (!config.languages.includes("go" /* go */)) { return; } if (config.buildMode) { - logger.debug( + logger2.debug( "Skipping legacy Go autobuild since a build mode has been specified." ); return; } if (process.env["CODEQL_ACTION_DID_AUTOBUILD_GOLANG" /* DID_AUTOBUILD_GOLANG */] === "true") { - logger.debug("Won't run Go autobuild since it has already been run."); + logger2.debug("Won't run Go autobuild since it has already been run."); return; } - if (dbIsFinalized(config, "go" /* go */, logger)) { - logger.debug( + if (dbIsFinalized(config, "go" /* go */, logger2)) { + logger2.debug( "Won't run Go autobuild since there is already a finalized database for Go." ); return; } if (doesGoExtractionOutputExist(config)) { - logger.debug( + logger2.debug( "Won't run Go autobuild since at least one file of Go code has already been extracted." ); if ("CODEQL_EXTRACTOR_GO_BUILD_TRACING" in process.env) { - logger.warning( + logger2.warning( `The CODEQL_EXTRACTOR_GO_BUILD_TRACING environment variable has no effect on workflows with manual build steps, so we recommend that you remove it from your workflow.` ); } return; } - logger.debug( + logger2.debug( "Running Go autobuild because extraction output (TRAP files) for Go code has not been found." ); - await runAutobuild(config, "go" /* go */, logger); + await runAutobuild(config, "go" /* go */, logger2); } async function run(startedAt) { let uploadResults = void 0; @@ -157648,7 +157651,7 @@ async function run(startedAt) { let didUploadTrapCaches = false; let dependencyCacheResults; let databaseUploadResults = []; - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { initializeEnvironment(getActionVersion()); persistInputs(); @@ -157657,13 +157660,13 @@ async function run(startedAt) { "starting", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); } - config = await getConfig(getTemporaryDirectory(), logger); + config = await getConfig(getTemporaryDirectory(), logger2); if (config === void 0) { throw new ConfigurationError( "Config file could not be found at expected location. Has the 'init' action been called?" @@ -157681,7 +157684,7 @@ async function run(startedAt) { delete process.env.CODEQL_PROXY_CA_CERTIFICATE; } if (getOptionalInput("cleanup-level")) { - logger.info( + logger2.info( "The 'cleanup-level' input is ignored since the CodeQL Action now automatically manages database cleanup. This input can safely be removed from your workflow." ); } @@ -157690,7 +157693,7 @@ async function run(startedAt) { core15.exportVariable("CODEQL_ACTION_SARIF_RESULTS_OUTPUT_DIR" /* SARIF_RESULTS_OUTPUT_DIR */, outputDir); const threads = getThreadsFlag( getOptionalInput("threads") || process.env["CODEQL_THREADS"], - logger + logger2 ); const repositoryNwo = getRepositoryNwo(); const gitHubVersion = await getGitHubVersion(); @@ -157699,15 +157702,15 @@ async function run(startedAt) { gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); const memory = getMemoryFlag( getOptionalInput("ram") || process.env["CODEQL_RAM"], - logger + logger2 ); - const diffRangePackDir = await setupDiffInformedQueryRun(logger); - await warnIfGoInstalledAfterInit(config, logger); - await runAutobuildIfLegacyGoWorkflow(config, logger); + const diffRangePackDir = await setupDiffInformedQueryRun(logger2); + await warnIfGoInstalledAfterInit(config, logger2); + await runAutobuildIfLegacyGoWorkflow(config, logger2); dbCreationTimings = await runFinalize( features, outputDir, @@ -157715,11 +157718,11 @@ async function run(startedAt) { memory, codeql, config, - logger + logger2 ); if (getRequiredInput("skip-queries") !== "true") { if (getOptionalInput("add-snippets") !== void 0) { - logger.warning( + logger2.warning( "The `add-snippets` input has been removed and no longer has any effect." ); } @@ -157731,7 +157734,7 @@ async function run(startedAt) { getOptionalInput("category"), codeql, config, - logger, + logger2, features ); } @@ -157748,7 +157751,7 @@ async function run(startedAt) { const checkoutPath = getRequiredInput("checkout_path"); const category = getOptionalInput("category"); uploadResults = await postProcessAndUploadSarif( - logger, + logger2, features, uploadKind, checkoutPath, @@ -157769,35 +157772,35 @@ async function run(startedAt) { ); } } else { - logger.info("Not uploading results"); + logger2.info("Not uploading results"); } - await cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger); + await cleanupAndUploadOverlayBaseDatabaseToCache(codeql, config, logger2); databaseUploadResults = await cleanupAndUploadDatabases( repositoryNwo, codeql, config, apiDetails, features, - logger + logger2 ); const trapCacheUploadStartTime = import_perf_hooks4.performance.now(); - didUploadTrapCaches = await uploadTrapCaches(codeql, config, logger); + didUploadTrapCaches = await uploadTrapCaches(codeql, config, logger2); trapCacheUploadTime = import_perf_hooks4.performance.now() - trapCacheUploadStartTime; trapCacheCleanupTelemetry = await cleanupTrapCaches( config, features, - logger + logger2 ); if (shouldStoreCache(config.dependencyCachingEnabled)) { dependencyCacheResults = await uploadDependencyCaches( codeql, features, config, - logger + logger2 ); } if (isInTestMode()) { - logger.debug("In test mode. Waiting for processing is disabled."); + logger2.debug("In test mode. Waiting for processing is disabled."); } else if (uploadResults?.["code-scanning" /* CodeScanning */] !== void 0 && getRequiredInput("wait-for-processing") === "true") { await waitForProcessing( getRepositoryNwo(), @@ -157827,7 +157830,7 @@ async function run(startedAt) { trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, - logger + logger2 ); return; } @@ -157846,7 +157849,7 @@ async function run(startedAt) { trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, - logger + logger2 ); } else if (runStats !== void 0) { await sendStatusReport2( @@ -157860,7 +157863,7 @@ async function run(startedAt) { trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, - logger + logger2 ); } else { await sendStatusReport2( @@ -157874,13 +157877,13 @@ async function run(startedAt) { trapCacheCleanupTelemetry, dependencyCacheResults, databaseUploadResults, - logger + logger2 ); } } async function runWrapper() { const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { await run(startedAt); } catch (error3) { @@ -157889,7 +157892,7 @@ async function runWrapper() { "finish" /* Analyze */, startedAt, error3, - logger + logger2 ); } await checkForTimeout(); @@ -157952,7 +157955,7 @@ function isAuthToken(value, patterns = GITHUB_TOKEN_PATTERNS) { } return void 0; } -function scanFileForTokens(filePath, relativePath, logger) { +function scanFileForTokens(filePath, relativePath, logger2) { const findings = []; try { const content = fs24.readFileSync(filePath, "utf8"); @@ -157962,18 +157965,18 @@ function scanFileForTokens(filePath, relativePath, logger) { for (let i = 0; i < matches.length; i++) { findings.push({ tokenType: type, filePath: relativePath }); } - logger.debug(`Found ${matches.length} ${type}(s) in ${relativePath}`); + logger2.debug(`Found ${matches.length} ${type}(s) in ${relativePath}`); } } return findings; } catch (e) { - logger.debug( + logger2.debug( `Could not scan file ${filePath} for tokens: ${getErrorMessage(e)}` ); return []; } } -async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, logger, depth = 0) { +async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, logger2, depth = 0) { const MAX_DEPTH = 10; if (depth > MAX_DEPTH) { throw new Error( @@ -157993,12 +157996,12 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log ); const fileName = path21.basename(archivePath).toLowerCase(); if (fileName.endsWith(".tar.gz") || fileName.endsWith(".tgz")) { - logger.debug(`Extracting tar.gz file: ${archivePath}`); + logger2.debug(`Extracting tar.gz file: ${archivePath}`); await exec.exec("tar", ["-xzf", archivePath, "-C", tempExtractDir], { silent: true }); } else if (fileName.endsWith(".tar.zst")) { - logger.debug(`Extracting tar.zst file: ${archivePath}`); + logger2.debug(`Extracting tar.zst file: ${archivePath}`); await exec.exec( "tar", ["--zstd", "-xf", archivePath, "-C", tempExtractDir], @@ -158007,7 +158010,7 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log } ); } else if (fileName.endsWith(".zst")) { - logger.debug(`Extracting zst file: ${archivePath}`); + logger2.debug(`Extracting zst file: ${archivePath}`); const outputFile = path21.join( tempExtractDir, path21.basename(archivePath, ".zst") @@ -158016,7 +158019,7 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log silent: true }); } else if (fileName.endsWith(".gz")) { - logger.debug(`Extracting gz file: ${archivePath}`); + logger2.debug(`Extracting gz file: ${archivePath}`); const outputFile = path21.join( tempExtractDir, path21.basename(archivePath, ".gz") @@ -158026,7 +158029,7 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log silent: true }); } else if (fileName.endsWith(".zip")) { - logger.debug(`Extracting zip file: ${archivePath}`); + logger2.debug(`Extracting zip file: ${archivePath}`); await exec.exec( "unzip", ["-q", "-o", archivePath, "-d", tempExtractDir], @@ -158038,20 +158041,20 @@ async function scanArchiveFile(archivePath, relativeArchivePath, extractDir, log const scanResult = await scanDirectory( tempExtractDir, relativeArchivePath, - logger, + logger2, depth + 1 ); result.scannedFiles += scanResult.scannedFiles; result.findings.push(...scanResult.findings); fs24.rmSync(tempExtractDir, { recursive: true, force: true }); } catch (e) { - logger.debug( + logger2.debug( `Could not extract or scan archive file ${archivePath}: ${getErrorMessage(e)}` ); } return result; } -async function scanFile(fullPath, relativePath, extractDir, logger, depth = 0) { +async function scanFile(fullPath, relativePath, extractDir, logger2, depth = 0) { const result = { scannedFiles: 1, findings: [] @@ -158063,17 +158066,17 @@ async function scanFile(fullPath, relativePath, extractDir, logger, depth = 0) { fullPath, relativePath, extractDir, - logger, + logger2, depth ); result.scannedFiles += archiveResult.scannedFiles; result.findings.push(...archiveResult.findings); } - const fileFindings = scanFileForTokens(fullPath, relativePath, logger); + const fileFindings = scanFileForTokens(fullPath, relativePath, logger2); result.findings.push(...fileFindings); return result; } -async function scanDirectory(dirPath, baseRelativePath, logger, depth = 0) { +async function scanDirectory(dirPath, baseRelativePath, logger2, depth = 0) { const result = { scannedFiles: 0, findings: [] @@ -158086,7 +158089,7 @@ async function scanDirectory(dirPath, baseRelativePath, logger, depth = 0) { const subResult = await scanDirectory( fullPath, relativePath, - logger, + logger2, depth ); result.scannedFiles += subResult.scannedFiles; @@ -158096,7 +158099,7 @@ async function scanDirectory(dirPath, baseRelativePath, logger, depth = 0) { fullPath, relativePath, path21.dirname(fullPath), - logger, + logger2, depth ); result.scannedFiles += fileResult.scannedFiles; @@ -158105,8 +158108,8 @@ async function scanDirectory(dirPath, baseRelativePath, logger, depth = 0) { } return result; } -async function scanArtifactsForTokens(filesToScan, logger) { - logger.info( +async function scanArtifactsForTokens(filesToScan, logger2) { + logger2.info( "Starting best-effort check for potential GitHub tokens in debug artifacts (for testing purposes only)..." ); const result = { @@ -158119,7 +158122,7 @@ async function scanArtifactsForTokens(filesToScan, logger) { const stats = fs24.statSync(filePath); const fileName = path21.basename(filePath); if (stats.isDirectory()) { - const dirResult = await scanDirectory(filePath, fileName, logger); + const dirResult = await scanDirectory(filePath, fileName, logger2); result.scannedFiles += dirResult.scannedFiles; result.findings.push(...dirResult.findings); } else if (stats.isFile()) { @@ -158127,7 +158130,7 @@ async function scanArtifactsForTokens(filesToScan, logger) { filePath, fileName, tempScanDir, - logger + logger2 ); result.scannedFiles += fileResult.scannedFiles; result.findings.push(...fileResult.findings); @@ -158145,7 +158148,7 @@ async function scanArtifactsForTokens(filesToScan, logger) { const tokenTypesSummary = Array.from(tokenTypesCounts.entries()).map(([type, count]) => `${count} ${type}${count > 1 ? "s" : ""}`).join(", "); const baseSummary = `scanned ${result.scannedFiles} files, found ${result.findings.length} potential token(s) in ${filesWithTokens.size} file(s)`; const summaryWithTypes = tokenTypesSummary ? `${baseSummary} (${tokenTypesSummary})` : baseSummary; - logger.info(`Artifact check complete: ${summaryWithTypes}`); + logger2.info(`Artifact check complete: ${summaryWithTypes}`); if (result.findings.length > 0) { const fileList = Array.from(filesWithTokens).join(", "); throw new Error( @@ -158156,7 +158159,7 @@ async function scanArtifactsForTokens(filesToScan, logger) { try { fs24.rmSync(tempScanDir, { recursive: true, force: true }); } catch (e) { - logger.debug( + logger2.debug( `Could not clean up temporary scan directory: ${getErrorMessage(e)}` ); } @@ -158167,11 +158170,11 @@ async function scanArtifactsForTokens(filesToScan, logger) { function sanitizeArtifactName(name) { return name.replace(/[^a-zA-Z0-9_-]+/g, ""); } -async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion) { +async function uploadCombinedSarifArtifacts(logger2, gitHubVariant, codeQlVersion) { const tempDir = getTemporaryDirectory(); if (process.env["CODEQL_ACTION_DEBUG_COMBINED_SARIF"] === "true") { await withGroup("Uploading combined SARIF debug artifact", async () => { - logger.info( + logger2.info( "Uploading available combined SARIF files as Actions debugging artifact..." ); const baseTempDir = path22.resolve(tempDir, "combined-sarif"); @@ -158187,7 +158190,7 @@ async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion } try { await uploadDebugArtifacts( - logger, + logger2, toUpload, baseTempDir, "combined-sarif-artifacts", @@ -158195,7 +158198,7 @@ async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion codeQlVersion ); } catch (e) { - logger.warning( + logger2.warning( `Failed to upload combined SARIF files as Actions debugging artifact. Reason: ${getErrorMessage( e )}` @@ -158204,7 +158207,7 @@ async function uploadCombinedSarifArtifacts(logger, gitHubVariant, codeQlVersion }); } } -function tryPrepareSarifDebugArtifact(config, language, logger) { +function tryPrepareSarifDebugArtifact(config, language, logger2) { try { const analyzeActionOutputDir = process.env["CODEQL_ACTION_SARIF_RESULTS_OUTPUT_DIR" /* SARIF_RESULTS_OUTPUT_DIR */]; if (analyzeActionOutputDir !== void 0 && fs25.existsSync(analyzeActionOutputDir) && fs25.lstatSync(analyzeActionOutputDir).isDirectory()) { @@ -158222,7 +158225,7 @@ function tryPrepareSarifDebugArtifact(config, language, logger) { } } } catch (e) { - logger.warning( + logger2.warning( `Failed to find SARIF results path for ${language}. Reason: ${getErrorMessage( e )}` @@ -158230,20 +158233,20 @@ function tryPrepareSarifDebugArtifact(config, language, logger) { } return void 0; } -async function tryBundleDatabase(codeql, config, language, logger) { +async function tryBundleDatabase(codeql, config, language, logger2) { try { - if (dbIsFinalized(config, language, logger)) { + if (dbIsFinalized(config, language, logger2)) { try { return await createDatabaseBundleCli(codeql, config, language); } catch (e) { - logger.warning( + logger2.warning( `Failed to bundle database for ${language} using the CLI. Falling back to a partial bundle. Reason: ${getErrorMessage(e)}` ); } } return await createPartialDatabaseBundle(config, language); } catch (e) { - logger.warning( + logger2.warning( `Failed to bundle database for ${language}. Reason: ${getErrorMessage( e )}` @@ -158251,52 +158254,52 @@ async function tryBundleDatabase(codeql, config, language, logger) { return void 0; } } -async function tryUploadAllAvailableDebugArtifacts(codeql, config, logger, codeQlVersion) { +async function tryUploadAllAvailableDebugArtifacts(codeql, config, logger2, codeQlVersion) { const filesToUpload = []; try { for (const language of config.languages) { await withGroup(`Uploading debug artifacts for ${language}`, async () => { - logger.info("Preparing SARIF result debug artifact..."); + logger2.info("Preparing SARIF result debug artifact..."); const sarifResultDebugArtifact = tryPrepareSarifDebugArtifact( config, language, - logger + logger2 ); if (sarifResultDebugArtifact) { filesToUpload.push(sarifResultDebugArtifact); - logger.info("SARIF result debug artifact ready for upload."); + logger2.info("SARIF result debug artifact ready for upload."); } - logger.info("Preparing database logs debug artifact..."); + logger2.info("Preparing database logs debug artifact..."); const databaseDirectory = getCodeQLDatabasePath(config, language); const logsDirectory = path22.resolve(databaseDirectory, "log"); if (doesDirectoryExist(logsDirectory)) { filesToUpload.push(...listFolder(logsDirectory)); - logger.info("Database logs debug artifact ready for upload."); + logger2.info("Database logs debug artifact ready for upload."); } - logger.info("Preparing database cluster logs debug artifact..."); + logger2.info("Preparing database cluster logs debug artifact..."); const multiLanguageTracingLogsDirectory = path22.resolve( config.dbLocation, "log" ); if (doesDirectoryExist(multiLanguageTracingLogsDirectory)) { filesToUpload.push(...listFolder(multiLanguageTracingLogsDirectory)); - logger.info("Database cluster logs debug artifact ready for upload."); + logger2.info("Database cluster logs debug artifact ready for upload."); } - logger.info("Preparing database bundle debug artifact..."); + logger2.info("Preparing database bundle debug artifact..."); const databaseBundle = await tryBundleDatabase( codeql, config, language, - logger + logger2 ); if (databaseBundle) { filesToUpload.push(databaseBundle); - logger.info("Database bundle debug artifact ready for upload."); + logger2.info("Database bundle debug artifact ready for upload."); } }); } } catch (e) { - logger.warning( + logger2.warning( `Failed to prepare debug artifacts. Reason: ${getErrorMessage(e)}` ); return; @@ -158305,7 +158308,7 @@ async function tryUploadAllAvailableDebugArtifacts(codeql, config, logger, codeQ await withGroup( "Uploading debug artifacts", async () => uploadDebugArtifacts( - logger, + logger2, filesToUpload, config.dbLocation, config.debugArtifactName, @@ -158314,7 +158317,7 @@ async function tryUploadAllAvailableDebugArtifacts(codeql, config, logger, codeQ ) ); } catch (e) { - logger.warning( + logger2.warning( `Failed to upload debug artifacts. Reason: ${getErrorMessage(e)}` ); } @@ -158338,7 +158341,7 @@ function getArtifactSuffix(matrix) { } return suffix; } -async function uploadDebugArtifacts(logger, toUpload, rootDir, artifactName, ghVariant, codeQlVersion) { +async function uploadDebugArtifacts(logger2, toUpload, rootDir, artifactName, ghVariant, codeQlVersion) { const uploadSupported = isSafeArtifactUpload(codeQlVersion); if (!uploadSupported) { core16.info( @@ -158346,18 +158349,18 @@ async function uploadDebugArtifacts(logger, toUpload, rootDir, artifactName, ghV ); return "upload-not-supported"; } - return uploadArtifacts(logger, toUpload, rootDir, artifactName, ghVariant); + return uploadArtifacts(logger2, toUpload, rootDir, artifactName, ghVariant); } -async function uploadArtifacts(logger, toUpload, rootDir, artifactName, ghVariant) { +async function uploadArtifacts(logger2, toUpload, rootDir, artifactName, ghVariant) { if (toUpload.length === 0) { return "no-artifacts-to-upload"; } if (isInTestMode()) { - await scanArtifactsForTokens(toUpload, logger); + await scanArtifactsForTokens(toUpload, logger2); core16.exportVariable("CODEQL_ACTION_ARTIFACT_SCAN_FINISHED", "true"); } const suffix = getArtifactSuffix(getOptionalInput("matrix")); - const artifactUploader = await getArtifactUploaderClient(logger, ghVariant); + const artifactUploader = await getArtifactUploaderClient(logger2, ghVariant); try { await artifactUploader.uploadArtifact( sanitizeArtifactName(`${artifactName}${suffix}`), @@ -158374,14 +158377,14 @@ async function uploadArtifacts(logger, toUpload, rootDir, artifactName, ghVarian return "upload-failed"; } } -async function getArtifactUploaderClient(logger, ghVariant) { +async function getArtifactUploaderClient(logger2, ghVariant) { if (ghVariant === "GitHub Enterprise Server" /* GHES */) { - logger.info( + logger2.info( "Debug artifacts can be consumed with `actions/download-artifact@v3` because the `v4` version is not yet compatible on GHES." ); return artifactLegacy.create(); } else { - logger.info( + logger2.info( "Debug artifacts can be consumed with `actions/download-artifact@v4`." ); return new artifact.DefaultArtifactClient(); @@ -158429,19 +158432,19 @@ async function createDatabaseBundleCli(codeql, config, language) { async function runWrapper2() { try { restoreInputs(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); if (process.env["CODEQL_ACTION_INIT_HAS_RUN" /* INIT_ACTION_HAS_RUN */] === "true") { const config = await getConfig( getTemporaryDirectory(), - logger + logger2 ); if (config !== void 0) { const codeql = await getCodeQL(config.codeQLCmd); const version = await codeql.getVersion(); await uploadCombinedSarifArtifacts( - logger, + logger2, config.gitHubVersion.type, version.version ); @@ -158456,7 +158459,7 @@ async function runWrapper2() { try { fs26.rmSync(tempDependencyDir, { recursive: true }); } catch (error3) { - logger.info( + logger2.info( `Failed to remove temporary dependencies directory: ${getErrorMessage(error3)}` ); } @@ -158471,7 +158474,7 @@ async function runWrapper2() { // src/autobuild-action.ts var core18 = __toESM(require_core()); -async function sendCompletedStatusReport(config, logger, startedAt, allLanguages, failingLanguage, cause) { +async function sendCompletedStatusReport(config, logger2, startedAt, allLanguages, failingLanguage, cause) { initializeEnvironment(getActionVersion()); const status = getActionsStatus(cause, failingLanguage); const statusReportBase = await createStatusReportBase( @@ -158479,8 +158482,8 @@ async function sendCompletedStatusReport(config, logger, startedAt, allLanguages status, startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, cause?.message, cause?.stack ); @@ -158494,7 +158497,7 @@ async function sendCompletedStatusReport(config, logger, startedAt, allLanguages } } async function run2(startedAt) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); let config; let currentLanguage; let languages; @@ -158504,37 +158507,37 @@ async function run2(startedAt) { "starting", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); } const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); checkActionVersion(getActionVersion(), gitHubVersion); - config = await getConfig(getTemporaryDirectory(), logger); + config = await getConfig(getTemporaryDirectory(), logger2); if (config === void 0) { throw new ConfigurationError( "Config file could not be found at expected location. Has the 'init' action been called?" ); } const codeql = await getCodeQL(config.codeQLCmd); - languages = await determineAutobuildLanguages(codeql, config, logger); + languages = await determineAutobuildLanguages(codeql, config, logger2); if (languages !== void 0) { const workingDirectory = getOptionalInput("working-directory"); if (workingDirectory) { - logger.info( + logger2.info( `Changing autobuilder working directory to ${workingDirectory}` ); process.chdir(workingDirectory); } for (const language of languages) { currentLanguage = language; - await runAutobuild(config, language, logger); + await runAutobuild(config, language, logger2); } } - await endTracingForCluster(codeql, config, logger); + await endTracingForCluster(codeql, config, logger2); } catch (unwrappedError) { const error3 = wrapError(unwrappedError); core18.setFailed( @@ -158542,7 +158545,7 @@ async function run2(startedAt) { ); await sendCompletedStatusReport( config, - logger, + logger2, startedAt, languages ?? [], currentLanguage, @@ -158551,11 +158554,11 @@ async function run2(startedAt) { return; } core18.exportVariable("CODEQL_ACTION_AUTOBUILD_DID_COMPLETE_SUCCESSFULLY" /* AUTOBUILD_DID_COMPLETE_SUCCESSFULLY */, "true"); - await sendCompletedStatusReport(config, logger, startedAt, languages ?? []); + await sendCompletedStatusReport(config, logger2, startedAt, languages ?? []); } async function runWrapper3() { const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { await run2(startedAt); } catch (error3) { @@ -158564,7 +158567,7 @@ async function runWrapper3() { "autobuild" /* Autobuild */, startedAt, error3, - logger + logger2 ); } } @@ -158578,15 +158581,15 @@ var io7 = __toESM(require_io()); var semver10 = __toESM(require_semver2()); // src/config/file.ts -function getConfigFileInput(logger, actions, repositoryProperties) { +function getConfigFileInput(logger2, actions, repositoryProperties) { const input = actions.getOptionalInput("config-file"); if (input !== void 0) { - logger.info(`Using configuration file input from workflow: ${input}`); + logger2.info(`Using configuration file input from workflow: ${input}`); return input; } const propertyValue = repositoryProperties["github-codeql-config-file" /* CONFIG_FILE */]; if (propertyValue !== void 0 && propertyValue.trim().length > 0) { - logger.info( + logger2.info( `Using configuration file input from repository property: ${propertyValue}` ); return propertyValue; @@ -158701,10 +158704,10 @@ function hasWorkflowTrigger(triggerName, doc) { } return Object.prototype.hasOwnProperty.call(doc.on, triggerName); } -async function validateWorkflow(codeql, logger) { +async function validateWorkflow(codeql, logger2) { let workflow; try { - workflow = await getWorkflow(logger); + workflow = await getWorkflow(logger2); } catch (e) { return `error: getWorkflow() failed: ${String(e)}`; } @@ -158736,27 +158739,27 @@ function formatWorkflowCause(errors) { } return errors.map((e) => e.code).join(","); } -async function getWorkflow(logger) { +async function getWorkflow(logger2) { const maybeWorkflow = process.env["CODE_SCANNING_WORKFLOW_FILE"]; if (maybeWorkflow) { - logger.debug( + logger2.debug( "Using the workflow specified by the CODE_SCANNING_WORKFLOW_FILE environment variable." ); return load( import_zlib2.default.gunzipSync(Buffer.from(maybeWorkflow, "base64")).toString() ); } - const workflowPath = await getWorkflowAbsolutePath(logger); + const workflowPath = await getWorkflowAbsolutePath(logger2); return load(fs27.readFileSync(workflowPath, "utf-8")); } -async function getWorkflowAbsolutePath(logger) { +async function getWorkflowAbsolutePath(logger2) { const relativePath = await getWorkflowRelativePath(); const absolutePath = path23.join( getRequiredEnvParam("GITHUB_WORKSPACE"), relativePath ); if (fs27.existsSync(absolutePath)) { - logger.debug( + logger2.debug( `Derived the following absolute path for the currently executing workflow: ${absolutePath}.` ); return absolutePath; @@ -158848,17 +158851,17 @@ function getCheckoutPathInputOrThrow(workflow, jobName, matrixVars) { matrixVars ) || getRequiredEnvParam("GITHUB_WORKSPACE"); } -async function checkWorkflow(logger, codeql) { +async function checkWorkflow(logger2, codeql) { if (!isDynamicWorkflow() && process.env["CODEQL_ACTION_SKIP_WORKFLOW_VALIDATION" /* SKIP_WORKFLOW_VALIDATION */] !== "true") { core19.startGroup("Validating workflow"); const validateWorkflowResult = await internal2.validateWorkflow( codeql, - logger + logger2 ); if (validateWorkflowResult === void 0) { - logger.info("Detected no issues with the code scanning workflow."); + logger2.info("Detected no issues with the code scanning workflow."); } else { - logger.debug( + logger2.debug( `Unable to validate code scanning workflow: ${validateWorkflowResult}` ); } @@ -158871,27 +158874,27 @@ var internal2 = { // src/init-action.ts var CODEQL_VERSION_JAR_MINIMIZATION = "2.23.0"; -async function sendStartingStatusReport(startedAt, config, logger) { +async function sendStartingStatusReport(startedAt, config, logger2) { const statusReportBase = await createStatusReportBase( "init" /* Init */, "starting", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); } } -async function sendCompletedStatusReport2(startedAt, config, configFile, toolsDownloadStatusReport, toolsFeatureFlagsValid, toolsSource, toolsVersion, overlayBaseDatabaseStats, dependencyCachingResults, logger, error3) { +async function sendCompletedStatusReport2(startedAt, config, configFile, toolsDownloadStatusReport, toolsFeatureFlagsValid, toolsSource, toolsVersion, overlayBaseDatabaseStats, dependencyCachingResults, logger2, error3) { const statusReportBase = await createStatusReportBase( "init" /* Init */, getActionsStatus(error3), startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3?.message, error3?.stack ); @@ -158919,7 +158922,7 @@ async function sendCompletedStatusReport2(startedAt, config, configFile, toolsDo initStatusReport, configFile, Math.round( - await getTotalCacheSize(Object.values(config.trapCaches), logger) + await getTotalCacheSize(Object.values(config.trapCaches), logger2) ), overlayBaseDatabaseStats, dependencyCachingResults @@ -158933,7 +158936,7 @@ async function sendCompletedStatusReport2(startedAt, config, configFile, toolsDo } } async function run3(startedAt) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); const actionsEnv = getActionsEnv(); let apiDetails; let config; @@ -158956,38 +158959,38 @@ async function run3(startedAt) { apiURL: getRequiredEnvParam("GITHUB_API_URL") }; const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); checkActionVersion(getActionVersion(), gitHubVersion); const repositoryNwo = getRepositoryNwo(); features = initFeatures( gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); const repositoryPropertiesResult = await loadRepositoryProperties( repositoryNwo, - logger + logger2 ); const repositoryProperties = repositoryPropertiesResult.orElse({}); const jobRunUuid = v4_default(); - logger.info(`Job run UUID is ${jobRunUuid}.`); + logger2.info(`Job run UUID is ${jobRunUuid}.`); core20.exportVariable("JOB_RUN_UUID" /* JOB_RUN_UUID */, jobRunUuid); core20.exportVariable("CODEQL_ACTION_INIT_HAS_RUN" /* INIT_ACTION_HAS_RUN */, "true"); - configFile = getConfigFileInput(logger, actionsEnv, repositoryProperties); + configFile = getConfigFileInput(logger2, actionsEnv, repositoryProperties); sourceRoot = path24.resolve( getRequiredEnvParam("GITHUB_WORKSPACE"), getOptionalInput("source-root") || "" ); let analysisKinds; try { - analysisKinds = await getAnalysisKinds(logger, features); + analysisKinds = await getAnalysisKinds(logger2, features); } catch (err) { - logger.debug( + logger2.debug( `Failed to parse analysis kinds for 'starting' status report: ${getErrorMessage(err)}` ); } - await sendStartingStatusReport(startedAt, { analysisKinds }, logger); + await sendStartingStatusReport(startedAt, { analysisKinds }, logger2); if (process.env["CODEQL_ACTION_SETUP_CODEQL_HAS_RUN" /* SETUP_CODEQL_ACTION_HAS_RUN */] === "true") { throw new ConfigurationError( `The 'init' action should not be run in the same workflow as 'setup-codeql'.` @@ -159008,14 +159011,14 @@ async function run3(startedAt) { rawLanguages, useOverlayAwareDefaultCliVersion, features, - logger + logger2 ); codeql = initCodeQLResult.codeql; toolsDownloadStatusReport = initCodeQLResult.toolsDownloadStatusReport; toolsVersion = initCodeQLResult.toolsVersion; toolsSource = initCodeQLResult.toolsSource; zstdAvailability = initCodeQLResult.zstdAvailability; - await checkWorkflow(logger, codeql); + await checkWorkflow(logger2, codeql); if ( // Only enable the experimental features env variable for Rust analysis if the user has explicitly // requested rust - don't enable it via language autodetection. @@ -159031,10 +159034,10 @@ async function run3(startedAt) { } if (semver10.lt(actualVer, publicPreview)) { core20.exportVariable("CODEQL_ENABLE_EXPERIMENTAL_FEATURES" /* EXPERIMENTAL_FEATURES */, "true"); - logger.info("Experimental Rust analysis enabled"); + logger2.info("Experimental Rust analysis enabled"); } } - analysisKinds = await getAnalysisKinds(logger, features); + analysisKinds = await getAnalysisKinds(logger2, features); const debugMode = getOptionalInput("debug") === "true" || core20.isDebug(); const fileCoverageResult = await getFileCoverageInformationEnabled( debugMode, @@ -159070,7 +159073,7 @@ async function run3(startedAt) { features, repositoryProperties, enableFileCoverageInformation: fileCoverageResult.enabled, - logger + logger: logger2 }); if (config.languages.includes("swift" /* swift */) && process.platform !== "darwin") { throw new ConfigurationError( @@ -159100,7 +159103,7 @@ async function run3(startedAt) { ); } if (fileCoverageResult.showDeprecationWarning) { - logFileCoverageOnPrsDeprecationWarning(logger); + logFileCoverageOnPrsDeprecationWarning(logger2); } await checkInstallPython311(config.languages, codeql); } catch (unwrappedError) { @@ -159111,8 +159114,8 @@ async function run3(startedAt) { error3 instanceof ConfigurationError ? "user-error" : "aborted", startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3.message, error3.stack ); @@ -159131,11 +159134,11 @@ async function run3(startedAt) { overlayBaseDatabaseStats = await downloadOverlayBaseDatabaseFromCache( codeql, config, - logger + logger2 ); if (!overlayBaseDatabaseStats) { config.overlayDatabaseMode = "none" /* None */; - logger.info( + logger2.info( `No overlay-base database found in cache, reverting overlay database mode to ${"none" /* None */}.` ); } @@ -159143,7 +159146,7 @@ async function run3(startedAt) { ); } if (config.overlayDatabaseMode !== "overlay" /* Overlay */) { - cleanupDatabaseClusterDirectory(config, logger); + cleanupDatabaseClusterDirectory(config, logger2); } if (zstdAvailability) { await recordZstdAvailability(config, zstdAvailability); @@ -159173,7 +159176,7 @@ async function run3(startedAt) { "indirectTracingSupportsStaticBinaries" /* IndirectTracingSupportsStaticBinaries */ )) { try { - logger.debug(`Applying static binary workaround for Go`); + logger2.debug(`Applying static binary workaround for Go`); const tempBinPath = path24.resolve( getTemporaryDirectory(), "codeql-action-go-tracing", @@ -159191,7 +159194,7 @@ exec ${goBinaryPath} "$@"` fs28.chmodSync(goWrapperPath, "755"); core20.exportVariable("CODEQL_ACTION_GO_BINARY" /* GO_BINARY_LOCATION */, goWrapperPath); } catch (e) { - logger.warning( + logger2.warning( `Analyzing Go on Linux, but failed to install wrapper script. Tracing custom builds may fail: ${e}` ); } @@ -159199,7 +159202,7 @@ exec ${goBinaryPath} "$@"` core20.exportVariable("CODEQL_ACTION_GO_BINARY" /* GO_BINARY_LOCATION */, goBinaryPath); } } catch (e) { - logger.warning( + logger2.warning( `Failed to determine the location of the Go binary: ${e}` ); if (e instanceof FileCmdNotFoundError) { @@ -159225,11 +159228,11 @@ exec ${goBinaryPath} "$@"` } core20.exportVariable( "CODEQL_RAM", - process.env["CODEQL_RAM"] || getCodeQLMemoryLimit(getOptionalInput("ram"), logger).toString() + process.env["CODEQL_RAM"] || getCodeQLMemoryLimit(getOptionalInput("ram"), logger2).toString() ); core20.exportVariable( "CODEQL_THREADS", - process.env["CODEQL_THREADS"] || getThreadsFlagValue(getOptionalInput("threads"), logger).toString() + process.env["CODEQL_THREADS"] || getThreadsFlagValue(getOptionalInput("threads"), logger2).toString() ); if (await features.getValue("disable_kotlin_analysis_enabled" /* DisableKotlinAnalysisEnabled */)) { core20.exportVariable("CODEQL_EXTRACTOR_JAVA_AGENT_DISABLE_KOTLIN", "true"); @@ -159246,23 +159249,23 @@ exec ${goBinaryPath} "$@"` codeql, features, config.languages, - logger + logger2 ); dependencyCachingStatus = dependencyCachingResult.statusReport; config.dependencyCachingRestoredKeys = dependencyCachingResult.restoredKeys; } if (getOptionalInput("setup-python-dependencies") !== void 0) { - logger.warning( + logger2.warning( "The setup-python-dependencies input is deprecated and no longer has any effect. We recommend removing any references from your workflows. See https://github.blog/changelog/2024-01-23-codeql-2-16-python-dependency-installation-disabled-new-queries-and-bug-fixes/ for more information." ); } if (process.env["CODEQL_ACTION_DISABLE_PYTHON_DEPENDENCY_INSTALLATION"] !== void 0) { - logger.warning( + logger2.warning( "The CODEQL_ACTION_DISABLE_PYTHON_DEPENDENCY_INSTALLATION environment variable is deprecated and no longer has any effect. We recommend removing any references from your workflows. See https://github.blog/changelog/2024-01-23-codeql-2-16-python-dependency-installation-disabled-new-queries-and-bug-fixes/ for more information." ); } if (process.env["CODEQL_EXTRACTOR_JAVA_OPTION_MINIMIZE_DEPENDENCY_JARS" /* JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS */]) { - logger.debug( + logger2.debug( `${"CODEQL_EXTRACTOR_JAVA_OPTION_MINIMIZE_DEPENDENCY_JARS" /* JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS */} is already set to '${process.env["CODEQL_EXTRACTOR_JAVA_OPTION_MINIMIZE_DEPENDENCY_JARS" /* JAVA_EXTRACTOR_MINIMIZE_DEPENDENCY_JARS */]}', so the Action will not override it.` ); } else if (await codeQlVersionAtLeast(codeql, CODEQL_VERSION_JAR_MINIMIZATION) && config.dependencyCachingEnabled && config.buildMode === "none" /* None */ && config.languages.includes("java" /* java */)) { @@ -159274,7 +159277,7 @@ exec ${goBinaryPath} "$@"` const { registriesAuthTokens, qlconfigFile } = await generateRegistries( getOptionalInput("registries"), config.tempDir, - logger + logger2 ); const databaseInitEnvironment = { GITHUB_TOKEN: apiDetails.auth, @@ -159287,14 +159290,14 @@ exec ${goBinaryPath} "$@"` sourceRoot, "Runner.Worker.exe", qlconfigFile, - logger + logger2 ); - if (config.overlayDatabaseMode !== "none" /* None */ && !await checkPacksForOverlayCompatibility(codeql, config, logger)) { - logger.info( + if (config.overlayDatabaseMode !== "none" /* None */ && !await checkPacksForOverlayCompatibility(codeql, config, logger2)) { + logger2.info( "Reverting overlay database mode to None due to incompatible packs." ); config.overlayDatabaseMode = "none" /* None */; - cleanupDatabaseClusterDirectory(config, logger, { + cleanupDatabaseClusterDirectory(config, logger2, { disableExistingDirectoryWarning: true }); await runDatabaseInitCluster( @@ -159304,7 +159307,7 @@ exec ${goBinaryPath} "$@"` sourceRoot, "Runner.Worker.exe", qlconfigFile, - logger + logger2 ); } const tracerConfig = await getCombinedTracerConfig(codeql, config); @@ -159321,7 +159324,7 @@ exec ${goBinaryPath} "$@"` ); } flushDiagnostics(config); - await saveConfig(config, logger); + await saveConfig(config, logger2); core20.setOutput("codeql-path", config.codeQLCmd); core20.setOutput("codeql-version", (await codeql.getVersion()).version); } catch (unwrappedError) { @@ -159338,7 +159341,7 @@ exec ${goBinaryPath} "$@"` toolsVersion, overlayBaseDatabaseStats, dependencyCachingStatus, - logger, + logger2, error3 ); return; @@ -159355,24 +159358,24 @@ exec ${goBinaryPath} "$@"` toolsVersion, overlayBaseDatabaseStats, dependencyCachingStatus, - logger + logger2 ); } -async function loadRepositoryProperties(repositoryNwo, logger) { +async function loadRepositoryProperties(repositoryNwo, logger2) { const repositoryOwnerType = github3.context.payload.repository?.owner.type; - logger.debug( + logger2.debug( `Repository owner type is '${repositoryOwnerType ?? "unknown"}'.` ); if (repositoryOwnerType === "User") { - logger.debug( + logger2.debug( "Skipping loading repository properties because the repository is owned by a user and therefore cannot have repository properties." ); return new Success({}); } try { - return new Success(await loadPropertiesFromApi(logger, repositoryNwo)); + return new Success(await loadPropertiesFromApi(logger2, repositoryNwo)); } catch (error3) { - logger.warning( + logger2.warning( `Failed to load repository properties: ${getErrorMessage(error3)}` ); return new Failure(error3); @@ -159390,7 +159393,7 @@ async function recordZstdAvailability(config, zstdAvailability) { } async function runWrapper4() { const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { await run3(startedAt); } catch (error3) { @@ -159399,7 +159402,7 @@ async function runWrapper4() { "init" /* Init */, startedAt, error3, - logger + logger2 ); } await checkForTimeout(); @@ -159419,7 +159422,7 @@ function createFailedUploadFailedSarifResult(error3) { upload_failed_run_stack_trace: wrappedError.stack }; } -async function prepareFailedSarif(logger, features, config) { +async function prepareFailedSarif(logger2, features, config) { if (!config.codeQLCmd) { return new Failure({ upload_failed_run_skipped_because: "CodeQL command not found" @@ -159450,7 +159453,7 @@ async function prepareFailedSarif(logger, features, config) { ); return new Success(result); } else { - const workflow = await getWorkflow(logger); + const workflow = await getWorkflow(logger2); const shouldUpload = getUploadInputOrThrow(workflow, jobName, matrix); if (!["always", "failure-only"].includes( getUploadValue(shouldUpload) @@ -159483,40 +159486,40 @@ async function generateFailedSarif(features, config, category, checkoutPath, sar } return { sarifFile, category, checkoutPath }; } -async function maybeUploadFailedSarif(config, repositoryNwo, features, logger) { - const failedSarifResult = await prepareFailedSarif(logger, features, config); +async function maybeUploadFailedSarif(config, repositoryNwo, features, logger2) { + const failedSarifResult = await prepareFailedSarif(logger2, features, config); if (failedSarifResult.isFailure()) { return failedSarifResult.value; } const failedSarif = failedSarifResult.value; - logger.info(`Uploading failed SARIF file ${failedSarif.sarifFile}`); + logger2.info(`Uploading failed SARIF file ${failedSarif.sarifFile}`); const uploadResult = await uploadFiles( failedSarif.sarifFile, failedSarif.checkoutPath, failedSarif.category, features, - logger, + logger2, CodeScanning ); await waitForProcessing( repositoryNwo, uploadResult.sarifID, - logger, + logger2, { isUnsuccessfulExecution: true } ); return uploadResult ? { ...uploadResult.statusReport, sarifID: uploadResult.sarifID } : {}; } -async function maybeUploadFailedSarifArtifact(config, features, logger) { - const failedSarifResult = await prepareFailedSarif(logger, features, config); +async function maybeUploadFailedSarifArtifact(config, features, logger2) { + const failedSarifResult = await prepareFailedSarif(logger2, features, config); if (failedSarifResult.isFailure()) { return failedSarifResult.value; } const failedSarif = failedSarifResult.value; - logger.info( + logger2.info( `Uploading failed SARIF file ${failedSarif.sarifFile} as artifact` ); const gitHubVersion = await getGitHubVersion(); - const client = await getArtifactUploaderClient(logger, gitHubVersion.type); + const client = await getArtifactUploaderClient(logger2, gitHubVersion.type); const suffix = getArtifactSuffix(getOptionalInput("matrix")); const name = sanitizeArtifactName(`sarif-artifact-${suffix}`); await client.uploadArtifact( @@ -159526,7 +159529,7 @@ async function maybeUploadFailedSarifArtifact(config, features, logger) { ); return { sarifID: name }; } -async function tryUploadSarifIfRunFailed(config, repositoryNwo, features, logger) { +async function tryUploadSarifIfRunFailed(config, repositoryNwo, features, logger2) { if (process.env["CODEQL_ACTION_ANALYZE_DID_COMPLETE_SUCCESSFULLY" /* ANALYZE_DID_COMPLETE_SUCCESSFULLY */] === "true") { return { upload_failed_run_skipped_because: "Analyze Action completed successfully" @@ -159538,32 +159541,32 @@ async function tryUploadSarifIfRunFailed(config, repositoryNwo, features, logger config, repositoryNwo, features, - logger + logger2 ); } else if (isRiskAssessmentEnabled(config)) { - return await maybeUploadFailedSarifArtifact(config, features, logger); + return await maybeUploadFailedSarifArtifact(config, features, logger2); } else { return { upload_failed_run_skipped_because: "No analysis kind that supports failed SARIF uploads is enabled." }; } } catch (e) { - logger.debug( + logger2.debug( `Failed to upload a SARIF file for this failed CodeQL code scanning run. ${e}` ); return createFailedUploadFailedSarifResult(e); } } -async function uploadFailureInfo(uploadAllAvailableDebugArtifacts, printDebugLogs2, codeql, config, repositoryNwo, features, logger) { - await recordOverlayStatus(codeql, config, features, logger); +async function uploadFailureInfo(uploadAllAvailableDebugArtifacts, printDebugLogs2, codeql, config, repositoryNwo, features, logger2) { + await recordOverlayStatus(codeql, config, features, logger2); const uploadFailedSarifResult = await tryUploadSarifIfRunFailed( config, repositoryNwo, features, - logger + logger2 ); if (uploadFailedSarifResult.upload_failed_run_skipped_because) { - logger.debug( + logger2.debug( `Won't upload a failed SARIF file for this CodeQL analysis because: ${uploadFailedSarifResult.upload_failed_run_skipped_because}.` ); } @@ -159575,22 +159578,22 @@ async function uploadFailureInfo(uploadAllAvailableDebugArtifacts, printDebugLog } if (process.env["CODEQL_ACTION_EXPECT_UPLOAD_FAILED_SARIF"] === "true") { if (!github4.context.payload.pull_request?.head.repo.fork) { - await removeUploadedSarif(uploadFailedSarifResult, logger); + await removeUploadedSarif(uploadFailedSarifResult, logger2); } else { - logger.info( + logger2.info( "Skipping deletion of failed SARIF because the workflow was triggered from a fork of codeql-action and doesn't have the appropriate permissions for deletion." ); } } if (config.debugMode) { - logger.info( + logger2.info( "Debug mode is on. Uploading available database bundles and logs as Actions debugging artifacts..." ); const version = await codeql.getVersion(); await uploadAllAvailableDebugArtifacts( codeql, config, - logger, + logger2, version.version ); await printDebugLogs2(config); @@ -159602,22 +159605,22 @@ async function uploadFailureInfo(uploadAllAvailableDebugArtifacts, printDebugLog force: true, maxRetries: 3 }); - logger.info( + logger2.info( `Cleaned up database cluster directory ${config.dbLocation}.` ); } catch (e) { - logger.warning( + logger2.warning( `Failed to clean up database cluster directory ${config.dbLocation}. Details: ${e}` ); } } else { - logger.debug( + logger2.debug( "Skipping cleanup of database cluster directory since we are running on a GitHub-hosted runner which will be automatically cleaned up." ); } return uploadFailedSarifResult; } -async function recordOverlayStatus(codeql, config, features, logger) { +async function recordOverlayStatus(codeql, config, features, logger2) { if (config.overlayDatabaseMode !== "overlay-base" /* OverlayBase */ || process.env["CODEQL_ACTION_ANALYZE_DID_COMPLETE_SUCCESSFULLY" /* ANALYZE_DID_COMPLETE_SUCCESSFULLY */] === "true" || !await features.getValue("overlay_analysis_status_save" /* OverlayAnalysisStatusSave */)) { return; } @@ -159630,9 +159633,9 @@ async function recordOverlayStatus(codeql, config, features, logger) { }, checkRunId !== void 0 && checkRunId >= 0 ? checkRunId : void 0 ); - const diskUsage = await checkDiskUsage(logger); + const diskUsage = await checkDiskUsage(logger2); if (diskUsage === void 0) { - logger.warning( + logger2.warning( "Unable to save overlay status to the Actions cache because the available disk space could not be determined." ); return; @@ -159642,24 +159645,24 @@ async function recordOverlayStatus(codeql, config, features, logger) { config.languages, diskUsage, overlayStatus, - logger + logger2 ); const blurb = "This job attempted to run with improved incremental analysis but it did not complete successfully. One possible reason for this is disk space constraints, since improved incremental analysis can require a significant amount of disk space for some repositories."; if (saved) { - logger.error( + logger2.error( `${blurb} This failure has been recorded in the Actions cache, so the next CodeQL analysis will run without improved incremental analysis. If you want to enable improved incremental analysis, try increasing the disk space available to the runner. If that doesn't help, contact GitHub Support for further assistance.` ); } else { - logger.error( + logger2.error( `${blurb} The attempt to save this failure status to the Actions cache failed. The Action will attempt to run with improved incremental analysis again.` ); } } -async function removeUploadedSarif(uploadFailedSarifResult, logger) { +async function removeUploadedSarif(uploadFailedSarifResult, logger2) { const sarifID = uploadFailedSarifResult.sarifID; if (sarifID) { - logger.startGroup("Deleting failed SARIF upload"); - logger.info( + logger2.startGroup("Deleting failed SARIF upload"); + logger2.info( `In test mode, therefore deleting the failed analysis to avoid impacting tool status for the Action repository. SARIF ID to delete: ${sarifID}.` ); const client = getApiClient(); @@ -159676,7 +159679,7 @@ async function removeUploadedSarif(uploadFailedSarifResult, logger) { ); if (analysisInfo.data.length === 1) { const analysis = analysisInfo.data[0]; - logger.info(`Analysis ID to delete: ${analysis.id}.`); + logger2.info(`Analysis ID to delete: ${analysis.id}.`); try { await client.request( "DELETE /repos/:owner/:repo/code-scanning/analyses/:analysis_id?confirm_delete", @@ -159686,7 +159689,7 @@ async function removeUploadedSarif(uploadFailedSarifResult, logger) { analysis_id: analysis.id } ); - logger.info(`Analysis deleted.`); + logger2.info(`Analysis deleted.`); } catch (e) { const origMessage = getErrorMessage(e); const newMessage = origMessage.includes( @@ -159706,10 +159709,10 @@ async function removeUploadedSarif(uploadFailedSarifResult, logger) { )}` ); } finally { - logger.endGroup(); + logger2.endGroup(); } } else { - logger.warning( + logger2.warning( "Could not delete the uploaded SARIF analysis because a SARIF ID wasn't provided by the API when uploading the SARIF file." ); } @@ -159717,24 +159720,24 @@ async function removeUploadedSarif(uploadFailedSarifResult, logger) { // src/init-action-post.ts async function run4(startedAt) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); let config; let uploadFailedSarifResult; let dependencyCachingUsage; try { restoreInputs(); const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); const repositoryNwo = getRepositoryNwo(); const features = initFeatures( gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); - config = await getConfig(getTemporaryDirectory(), logger); + config = await getConfig(getTemporaryDirectory(), logger2); if (config === void 0) { - logger.warning( + logger2.warning( "Debugging artifacts are unavailable since the 'init' Action failed before it could produce any." ); } else { @@ -159746,10 +159749,10 @@ async function run4(startedAt) { config, repositoryNwo, features, - logger + logger2 ); if (await isAnalyzingDefaultBranch() && config.dependencyCachingEnabled !== "none" /* None */) { - dependencyCachingUsage = await getDependencyCacheUsage(logger); + dependencyCachingUsage = await getDependencyCacheUsage(logger2); } } } catch (unwrappedError) { @@ -159760,8 +159763,8 @@ async function run4(startedAt) { getActionsStatus(error3), startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3.message, error3.stack ); @@ -159771,14 +159774,14 @@ async function run4(startedAt) { return; } const jobStatus = getFinalJobStatus(config); - logger.info(`CodeQL job status was ${getJobStatusDisplayName(jobStatus)}.`); + logger2.info(`CodeQL job status was ${getJobStatusDisplayName(jobStatus)}.`); const statusReportBase = await createStatusReportBase( "init-post" /* InitPost */, "success", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { const statusReport = { @@ -159787,9 +159790,9 @@ async function run4(startedAt) { job_status: jobStatus, dependency_caching_usage: dependencyCachingUsage }; - logger.info("Sending status report for init-post step."); + logger2.info("Sending status report for init-post step."); await sendStatusReport(statusReport); - logger.info("Status report sent for init-post step."); + logger2.info("Status report sent for init-post step."); } } function getFinalJobStatus(config) { @@ -159821,7 +159824,7 @@ function getJobStatusFromEnvironment() { } async function runWrapper5() { const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { await run4(startedAt); } catch (error3) { @@ -159830,7 +159833,7 @@ async function runWrapper5() { "init-post" /* InitPost */, startedAt, error3, - logger + logger2 ); } } @@ -159839,21 +159842,21 @@ async function runWrapper5() { var core22 = __toESM(require_core()); // src/resolve-environment.ts -async function runResolveBuildEnvironment(cmd, logger, workingDir, language) { - logger.startGroup(`Attempting to resolve build environment for ${language}`); +async function runResolveBuildEnvironment(cmd, logger2, workingDir, language) { + logger2.startGroup(`Attempting to resolve build environment for ${language}`); const codeql = await getCodeQL(cmd); if (workingDir !== void 0) { - logger.info(`Using ${workingDir} as the working directory.`); + logger2.info(`Using ${workingDir} as the working directory.`); } const result = await codeql.resolveBuildEnvironment(workingDir, language); - logger.endGroup(); + logger2.endGroup(); return result; } // src/resolve-environment-action.ts var ENVIRONMENT_OUTPUT_NAME = "environment"; async function run5(startedAt) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); let config; try { const statusReportBase2 = await createStatusReportBase( @@ -159861,16 +159864,16 @@ async function run5(startedAt) { "starting", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase2 !== void 0) { await sendStatusReport(statusReportBase2); } const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); checkActionVersion(getActionVersion(), gitHubVersion); - config = await getConfig(getTemporaryDirectory(), logger); + config = await getConfig(getTemporaryDirectory(), logger2); if (config === void 0) { throw new ConfigurationError( "Config file could not be found at expected location. Has the 'init' action been called?" @@ -159879,7 +159882,7 @@ async function run5(startedAt) { const workingDirectory = getOptionalInput("working-directory"); const result = await runResolveBuildEnvironment( config.codeQLCmd, - logger, + logger2, workingDirectory, getRequiredInput("language") ); @@ -159888,7 +159891,7 @@ async function run5(startedAt) { const error3 = wrapError(unwrappedError); if (error3 instanceof CliError) { core22.setOutput(ENVIRONMENT_OUTPUT_NAME, {}); - logger.warning( + logger2.warning( `Failed to resolve a build environment suitable for automatically building your code. ${error3.message}` ); } else { @@ -159900,8 +159903,8 @@ async function run5(startedAt) { getActionsStatus(error3), startedAt, config, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3.message, error3.stack ); @@ -159916,8 +159919,8 @@ async function run5(startedAt) { "success", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); @@ -159925,7 +159928,7 @@ async function run5(startedAt) { } async function runWrapper6() { const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { await run5(startedAt); } catch (error3) { @@ -159938,7 +159941,7 @@ async function runWrapper6() { "resolve-environment" /* ResolveEnvironment */, startedAt, error3, - logger + logger2 ); } await checkForTimeout(); @@ -159946,14 +159949,14 @@ async function runWrapper6() { // src/setup-codeql-action.ts var core23 = __toESM(require_core()); -async function sendCompletedStatusReport3(startedAt, toolsDownloadStatusReport, toolsFeatureFlagsValid, toolsSource, toolsVersion, logger, error3) { +async function sendCompletedStatusReport3(startedAt, toolsDownloadStatusReport, toolsFeatureFlagsValid, toolsSource, toolsVersion, logger2, error3) { const statusReportBase = await createStatusReportBase( "setup-codeql" /* SetupCodeQL */, getActionsStatus(error3), startedAt, void 0, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3?.message, error3?.stack ); @@ -159977,7 +159980,7 @@ async function sendCompletedStatusReport3(startedAt, toolsDownloadStatusReport, await sendStatusReport({ ...initStatusReport, ...initToolsDownloadFields }); } async function run6(startedAt) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); let codeql; let toolsDownloadStatusReport; let toolsFeatureFlagsValid; @@ -159992,25 +159995,25 @@ async function run6(startedAt) { apiURL: getRequiredEnvParam("GITHUB_API_URL") }; const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); checkActionVersion(getActionVersion(), gitHubVersion); const repositoryNwo = getRepositoryNwo(); const features = initFeatures( gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); const jobRunUuid = v4_default(); - logger.info(`Job run UUID is ${jobRunUuid}.`); + logger2.info(`Job run UUID is ${jobRunUuid}.`); core23.exportVariable("JOB_RUN_UUID" /* JOB_RUN_UUID */, jobRunUuid); const statusReportBase = await createStatusReportBase( "setup-codeql" /* SetupCodeQL */, "starting", startedAt, void 0, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { await sendStatusReport(statusReportBase); @@ -160020,7 +160023,7 @@ async function run6(startedAt) { const rawLanguages = getRawLanguagesNoAutodetect( getOptionalInput("languages") ); - const analysisKinds = await getAnalysisKinds(logger, features); + const analysisKinds = await getAnalysisKinds(logger2, features); const initCodeQLResult = await initCodeQL( getOptionalInput("tools"), apiDetails, @@ -160030,7 +160033,7 @@ async function run6(startedAt) { rawLanguages, analysisKinds.length === 1 && analysisKinds[0] === "code-scanning" /* CodeScanning */, features, - logger + logger2 ); codeql = initCodeQLResult.codeql; toolsDownloadStatusReport = initCodeQLResult.toolsDownloadStatusReport; @@ -160047,8 +160050,8 @@ async function run6(startedAt) { error3 instanceof ConfigurationError ? "user-error" : "failure", startedAt, void 0, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, error3.message, error3.stack ); @@ -160063,12 +160066,12 @@ async function run6(startedAt) { toolsFeatureFlagsValid, toolsSource, toolsVersion, - logger + logger2 ); } async function runWrapper7() { const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { await run6(startedAt); } catch (error3) { @@ -160077,7 +160080,7 @@ async function runWrapper7() { "setup-codeql" /* SetupCodeQL */, startedAt, error3, - logger + logger2 ); } await checkForTimeout(); @@ -160287,14 +160290,14 @@ var StartProxyError = class extends Error { this.errorType = errorType; } }; -async function sendSuccessStatusReport(startedAt, config, registry_types, logger) { +async function sendSuccessStatusReport(startedAt, config, registry_types, logger2) { const statusReportBase = await createStatusReportBase( "start-proxy" /* StartProxy */, "success", startedAt, config, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { const statusReport = { @@ -160310,7 +160313,7 @@ function getSafeErrorMessage(error3) { } return `Error from start-proxy Action omitted (${error3.constructor.name}).`; } -async function sendFailedStatusReport(logger, startedAt, language, unwrappedError) { +async function sendFailedStatusReport(logger2, startedAt, language, unwrappedError) { const error3 = wrapError(unwrappedError); core25.setFailed(`start-proxy action failed: ${error3.message}`); const statusReportMessage = getSafeErrorMessage(error3); @@ -160321,8 +160324,8 @@ async function sendFailedStatusReport(logger, startedAt, language, unwrappedErro { languages: language === void 0 ? void 0 : [language] }, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, statusReportMessage ); if (errorStatusReportBase !== void 0) { @@ -160367,24 +160370,24 @@ function getRegistryAddress(registry) { ); } } -function getCredentials(logger, registrySecrets, registriesCredentials, language) { +function getCredentials(logger2, registrySecrets, registriesCredentials, language) { const registryTypeForLanguage = language ? LANGUAGE_TO_REGISTRY_TYPE[language] : void 0; let credentialsStr; if (registriesCredentials !== void 0) { - logger.info(`Using registries_credentials input.`); + logger2.info(`Using registries_credentials input.`); credentialsStr = Buffer.from(registriesCredentials, "base64").toString(); } else if (registrySecrets !== void 0) { - logger.info(`Using registry_secrets input.`); + logger2.info(`Using registry_secrets input.`); credentialsStr = registrySecrets; } else { - logger.info(`No credentials defined.`); + logger2.info(`No credentials defined.`); return []; } let parsed; try { parsed = parseString(credentialsStr); } catch { - logger.error("Failed to parse the credentials data."); + logger2.error("Failed to parse the credentials data."); throw new ConfigurationError("Invalid credentials format."); } if (!isArray(parsed)) { @@ -160420,7 +160423,7 @@ function getCredentials(logger, registrySecrets, registriesCredentials, language const passwordIsPAT = hasUsernameAndPassword(authConfig) && isDefined2(authConfig.password) && isPAT(authConfig.password); const tokenIsPAT = hasToken(authConfig) && isDefined2(authConfig.token) && isPAT(authConfig.token); if (noUsername && (passwordIsPAT || tokenIsPAT)) { - logger.warning( + logger2.warning( `A ${e.type} private registry is configured for ${e.host || e.url} using a GitHub Personal Access Token (PAT), but no username was provided. This may not work correctly. When configuring a private registry using a PAT, select "Username and password" and enter the username of the user who generated the PAT.` ); } @@ -160460,7 +160463,7 @@ async function getCliVersionFromFeatures(features) { const gitHubVersion = await getGitHubVersion(); return await features.getEnabledDefaultCliVersions(gitHubVersion.type); } -async function getDownloadUrl(logger, features) { +async function getDownloadUrl(logger2, features) { const proxyPackage = getProxyPackage(); try { const useFeaturesToDetermineCLI = await features.getValue( @@ -160473,7 +160476,7 @@ async function getDownloadUrl(logger, features) { const cliRelease = await getReleaseByVersion(versionInfo.tagName); for (const asset of cliRelease.data.assets) { if (asset.name === proxyPackage) { - logger.info( + logger2.info( `Found '${proxyPackage}' in release '${versionInfo.tagName}' at '${asset.url}'` ); return { @@ -160486,11 +160489,11 @@ async function getDownloadUrl(logger, features) { } } } catch (ex) { - logger.warning( + logger2.warning( `Failed to retrieve information about the linked release: ${getErrorMessage(ex)}` ); } - logger.info( + logger2.info( `Did not find '${proxyPackage}' in the linked release, falling back to hard-coded version.` ); return { @@ -160498,7 +160501,7 @@ async function getDownloadUrl(logger, features) { version: UPDATEJOB_PROXY_VERSION }; } -async function downloadProxy(logger, url2, authorization) { +async function downloadProxy(logger2, url2, authorization) { try { return toolcache4.downloadTool( url2, @@ -160510,27 +160513,27 @@ async function downloadProxy(logger, url2, authorization) { } ); } catch (error3) { - logger.error( + logger2.error( `Failed to download proxy archive from ${url2}: ${getErrorMessage(error3)}` ); throw new StartProxyError(0 /* DownloadFailed */); } } -async function extractProxy(logger, archive) { +async function extractProxy(logger2, archive) { try { return await toolcache4.extractTar(archive); } catch (error3) { - logger.error( + logger2.error( `Failed to extract proxy archive from ${archive}: ${getErrorMessage(error3)}` ); throw new StartProxyError(1 /* ExtractionFailed */); } } -async function cacheProxy(logger, source, filename, version) { +async function cacheProxy(logger2, source, filename, version) { try { return await toolcache4.cacheDir(source, filename, version); } catch (error3) { - logger.error( + logger2.error( `Failed to add proxy archive from ${source} to toolcache: ${getErrorMessage(error3)}` ); throw new StartProxyError(2 /* CacheFailed */); @@ -160539,21 +160542,21 @@ async function cacheProxy(logger, source, filename, version) { function getProxyFilename() { return process.platform === "win32" ? `${UPDATEJOB_PROXY}.exe` : UPDATEJOB_PROXY; } -async function getProxyBinaryPath(logger, features) { +async function getProxyBinaryPath(logger2, features) { const proxyFileName = getProxyFilename(); - const proxyInfo = await getDownloadUrl(logger, features); + const proxyInfo = await getDownloadUrl(logger2, features); let proxyBin = toolcache4.find(proxyFileName, proxyInfo.version); if (!proxyBin) { const apiDetails = getApiDetails(); const authorization = getAuthorizationHeaderFor( - logger, + logger2, apiDetails, proxyInfo.url ); - const temp = await downloadProxy(logger, proxyInfo.url, authorization); - const extracted = await extractProxy(logger, temp); + const temp = await downloadProxy(logger2, proxyInfo.url, authorization); + const extracted = await extractProxy(logger2, temp); proxyBin = await cacheProxy( - logger, + logger2, extracted, proxyFileName, proxyInfo.version @@ -160628,20 +160631,20 @@ var fs30 = __toESM(require("fs")); var path27 = __toESM(require("path")); var toolrunner5 = __toESM(require_toolrunner()); var io8 = __toESM(require_io()); -function checkEnvVar(logger, name) { +function checkEnvVar(logger2, name) { const value = process.env[name]; if (isDefined2(value)) { const url2 = URL.parse(value); if (isDefined2(url2)) { url2.username = ""; url2.password = ""; - logger.info(`Environment variable '${name}' is set to '${url2}'.`); + logger2.info(`Environment variable '${name}' is set to '${url2}'.`); } else { - logger.info(`Environment variable '${name}' is set to '${value}'.`); + logger2.info(`Environment variable '${name}' is set to '${value}'.`); } return true; } else { - logger.debug(`Environment variable '${name}' is not set.`); + logger2.debug(`Environment variable '${name}' is not set.`); return false; } } @@ -160669,9 +160672,9 @@ var JAVA_PROXY_ENV_VARS = [ "JDK_JAVA_OPTIONS" /* JDK_JAVA_OPTIONS */, "_JAVA_OPTIONS" /* _JAVA_OPTIONS */ ]; -function checkJavaEnvVars(logger) { +function checkJavaEnvVars(logger2) { for (const envVar of JAVA_PROXY_ENV_VARS) { - checkEnvVar(logger, envVar); + checkEnvVar(logger2, envVar); } } function discoverActionsJdks() { @@ -160687,7 +160690,7 @@ function discoverActionsJdks() { } return paths; } -function checkJdkSettings(logger, jdkHome) { +function checkJdkSettings(logger2, jdkHome) { const filesToCheck = [ // JDK 9+ path27.join("conf", "net.properties"), @@ -160698,24 +160701,24 @@ function checkJdkSettings(logger, jdkHome) { const file = path27.join(jdkHome, fileToCheck); try { if (fs30.existsSync(file)) { - logger.debug(`Found '${file}'.`); + logger2.debug(`Found '${file}'.`); const lines = String(fs30.readFileSync(file)).split("\n"); for (const line of lines) { for (const property of javaProperties) { if (line.startsWith(`${property}=`)) { - logger.info(`Found '${line.trimEnd()}' in '${file}'.`); + logger2.info(`Found '${line.trimEnd()}' in '${file}'.`); } } } } else { - logger.debug(`'${file}' does not exist.`); + logger2.debug(`'${file}' does not exist.`); } } catch (err) { - logger.debug(`Failed to read '${file}': ${getErrorMessage(err)}`); + logger2.debug(`Failed to read '${file}': ${getErrorMessage(err)}`); } } } -async function showJavaSettings(logger) { +async function showJavaSettings(logger2) { try { const java = await io8.which("java", true); let output = ""; @@ -160734,11 +160737,11 @@ async function showJavaSettings(logger) { } } ).exec(); - logger.startGroup("Java settings"); - logger.info(output); - logger.endGroup(); + logger2.startGroup("Java settings"); + logger2.info(output); + logger2.endGroup(); } catch (err) { - logger.debug(`Failed to query java settings: ${getErrorMessage(err)}`); + logger2.debug(`Failed to query java settings: ${getErrorMessage(err)}`); } } var ProxyEnvVars = /* @__PURE__ */ ((ProxyEnvVars2) => { @@ -160747,20 +160750,20 @@ var ProxyEnvVars = /* @__PURE__ */ ((ProxyEnvVars2) => { ProxyEnvVars2["ALL_PROXY"] = "ALL_PROXY"; return ProxyEnvVars2; })(ProxyEnvVars || {}); -function checkProxyEnvVars(logger) { +function checkProxyEnvVars(logger2) { for (const envVar of Object.values(ProxyEnvVars)) { - checkEnvVar(logger, envVar); - checkEnvVar(logger, envVar.toLowerCase()); + checkEnvVar(logger2, envVar); + checkEnvVar(logger2, envVar.toLowerCase()); } } -async function checkProxyEnvironment(logger, language) { - checkProxyEnvVars(logger); +async function checkProxyEnvironment(logger2, language) { + checkProxyEnvVars(logger2); if (language === void 0 || language === "java" /* java */) { - checkJavaEnvVars(logger); - await showJavaSettings(logger); + checkJavaEnvVars(logger2); + await showJavaSettings(logger2); const jdks = discoverActionsJdks(); for (const jdk of jdks) { - checkJdkSettings(logger, jdk); + checkJdkSettings(logger2, jdk); } } } @@ -160825,11 +160828,11 @@ var NetworkReachabilityBackend = class { }); } }; -async function checkConnections(logger, proxy, backend) { +async function checkConnections(logger2, proxy, backend) { const result = /* @__PURE__ */ new Set(); if (proxy.registries.length === 0) return result; - logger.startGroup("Testing connections via the proxy"); - logger.info( + logger2.startGroup("Testing connections via the proxy"); + logger2.info( `The connection tests performed here are best-effort only and failures here may not affect the subsequent analysis. See ${"https://docs.github.com/en/code-security/reference/code-scanning/code-scanning-logs#diagnostic-information-for-private-package-registries" /* PRIVATE_REGISTRY_LOGS */} for more information.` ); try { @@ -160841,40 +160844,40 @@ async function checkConnections(logger, proxy, backend) { const address = getAddressString(registry); const url2 = URL.parse(address); if (url2 === null) { - logger.info( + logger2.info( `Skipping check for ${address} since it is not a valid URL.` ); continue; } const testUrl = makeTestUrl(config, url2); try { - logger.debug(`Testing connection to ${url2}...`); + logger2.debug(`Testing connection to ${url2}...`); const statusCode = await backend.checkConnection(testUrl); - logger.info(`Successfully tested connection to ${url2} (${statusCode})`); + logger2.info(`Successfully tested connection to ${url2} (${statusCode})`); result.add(registry); } catch (e) { if (e instanceof ReachabilityError && e.statusCode !== void 0) { - logger.info(`Connection test to ${url2} failed. (${e.statusCode})`); + logger2.info(`Connection test to ${url2} failed. (${e.statusCode})`); } else { - logger.warning( + logger2.warning( `Connection test to ${url2} failed: ${getErrorMessage(e)}` ); } } } - logger.debug(`Finished testing connections to private registries.`); + logger2.debug(`Finished testing connections to private registries.`); } catch (e) { - logger.warning( + logger2.warning( `Failed to test connections to private registries: ${getErrorMessage(e)}` ); } - logger.endGroup(); + logger2.endGroup(); return result; } // src/start-proxy-action.ts async function run7(startedAt) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); let features; let language; try { @@ -160888,29 +160891,29 @@ async function run7(startedAt) { gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); const languageInput = getOptionalInput("language"); language = languageInput ? parseBuiltInLanguage(languageInput) : void 0; const credentials = getCredentials( - logger, + logger2, getOptionalInput("registry_secrets"), getOptionalInput("registries_credentials"), language ); if (credentials.length === 0) { - logger.info("No credentials found, skipping proxy setup."); + logger2.info("No credentials found, skipping proxy setup."); return; } - logger.info( + logger2.info( `Credentials loaded for the following registries: ${credentials.map((c) => credentialToStr(c)).join("\n")}` ); if (core26.isDebug() || isInTestMode()) { try { - await checkProxyEnvironment(logger, language); + await checkProxyEnvironment(logger2, language); } catch (err) { - logger.debug( + logger2.debug( `Unable to inspect runner environment: ${getErrorMessage(err)}` ); } @@ -160920,29 +160923,29 @@ async function run7(startedAt) { all_credentials: credentials, ca }; - const proxyBin = await getProxyBinaryPath(logger, features); + const proxyBin = await getProxyBinaryPath(logger2, features); const proxyInfo = await startProxy( proxyBin, proxyConfig, proxyLogFilePath, - logger + logger2 ); - await checkConnections(logger, proxyInfo); + await checkConnections(logger2, proxyInfo); await sendSuccessStatusReport( startedAt, { languages: language === void 0 ? void 0 : [language] }, proxyConfig.all_credentials.map((c) => c.type), - logger + logger2 ); } catch (unwrappedError) { - await sendFailedStatusReport(logger, startedAt, language, unwrappedError); + await sendFailedStatusReport(logger2, startedAt, language, unwrappedError); } } async function runWrapper8() { const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { await run7(startedAt); } catch (error3) { @@ -160951,11 +160954,11 @@ async function runWrapper8() { "start-proxy" /* StartProxy */, startedAt, getSafeErrorMessage(wrapError(error3)), - logger + logger2 ); } } -async function startProxy(binPath, config, logFilePath, logger) { +async function startProxy(binPath, config, logFilePath, logger2) { const host = "127.0.0.1"; let port = 49152; let subprocess = void 0; @@ -160990,7 +160993,7 @@ async function startProxy(binPath, config, logFilePath, logger) { if (subprocessError) { throw subprocessError; } - logger.info(`Proxy started on ${host}:${port}`); + logger2.info(`Proxy started on ${host}:${port}`); core26.setOutput("proxy_host", host); core26.setOutput("proxy_port", port.toString()); core26.setOutput("proxy_ca_certificate", config.ca.cert); @@ -161006,7 +161009,7 @@ async function startProxy(binPath, config, logFilePath, logger) { // src/start-proxy-action-post.ts var core27 = __toESM(require_core()); async function runWrapper9() { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { restoreInputs(); const pid = core27.getState("proxy-process-pid"); @@ -161015,23 +161018,23 @@ async function runWrapper9() { } const config = await getConfig( getTemporaryDirectory(), - logger + logger2 ); if (config?.debugMode || core27.isDebug()) { const logFilePath = core27.getState("proxy-log-file"); - logger.info( + logger2.info( "Debug mode is on. Uploading proxy log as Actions debugging artifact..." ); if (config?.gitHubVersion.type === void 0) { - logger.warning( + logger2.warning( `Did not upload debug artifacts because cannot determine the GitHub variant running.` ); return; } const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); await uploadArtifacts( - logger, + logger2, [logFilePath], getTemporaryDirectory(), "proxy-log-file", @@ -161039,7 +161042,7 @@ async function runWrapper9() { ); } } catch (error3) { - logger.warning( + logger2.warning( `start-proxy post-action step failed: ${getErrorMessage(error3)}` ); } @@ -161047,14 +161050,14 @@ async function runWrapper9() { // src/upload-sarif-action.ts var core28 = __toESM(require_core()); -async function sendSuccessStatusReport2(startedAt, uploadStats, logger) { +async function sendSuccessStatusReport2(startedAt, uploadStats, logger2) { const statusReportBase = await createStatusReportBase( "upload-sarif" /* UploadSarif */, "success", startedAt, void 0, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (statusReportBase !== void 0) { const statusReport = { @@ -161065,7 +161068,7 @@ async function sendSuccessStatusReport2(startedAt, uploadStats, logger) { } } async function run8(startedAt) { - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { initializeEnvironment(getActionVersion()); const gitHubVersion = await getGitHubVersion(); @@ -161076,15 +161079,15 @@ async function run8(startedAt) { gitHubVersion, repositoryNwo, getTemporaryDirectory(), - logger + logger2 ); const startingStatusReportBase = await createStatusReportBase( "upload-sarif" /* UploadSarif */, "starting", startedAt, void 0, - await checkDiskUsage(logger), - logger + await checkDiskUsage(logger2), + logger2 ); if (startingStatusReportBase !== void 0) { await sendStatusReport(startingStatusReportBase); @@ -161093,7 +161096,7 @@ async function run8(startedAt) { const checkoutPath = getRequiredInput("checkout_path"); const category = getOptionalInput("category"); const uploadResults = await postProcessAndUploadSarif( - logger, + logger2, features, "always", checkoutPath, @@ -161119,14 +161122,14 @@ async function run8(startedAt) { await waitForProcessing( getRepositoryNwo(), codeScanningResult.sarifID, - logger + logger2 ); } } await sendSuccessStatusReport2( startedAt, codeScanningResult?.statusReport || {}, - logger + logger2 ); } catch (unwrappedError) { const error3 = isThirdPartyAnalysis("upload-sarif" /* UploadSarif */) && unwrappedError instanceof InvalidSarifUploadError ? new ConfigurationError(unwrappedError.message) : wrapError(unwrappedError); @@ -161137,8 +161140,8 @@ async function run8(startedAt) { getActionsStatus(error3), startedAt, void 0, - await checkDiskUsage(logger), - logger, + await checkDiskUsage(logger2), + logger2, message, error3.stack ); @@ -161150,7 +161153,7 @@ async function run8(startedAt) { } async function runWrapper10() { const startedAt = /* @__PURE__ */ new Date(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); try { await run8(startedAt); } catch (error3) { @@ -161161,7 +161164,7 @@ async function runWrapper10() { "upload-sarif" /* UploadSarif */, startedAt, error3, - logger + logger2 ); } } @@ -161171,9 +161174,9 @@ var core29 = __toESM(require_core()); async function runWrapper11() { try { restoreInputs(); - const logger = getActionsLogger(); + const logger2 = getActionsLogger(); const gitHubVersion = await getGitHubVersion(); - checkGitHubVersionInRange(gitHubVersion, logger); + checkGitHubVersionInRange(gitHubVersion, logger2); if (process.env["CODEQL_ACTION_INIT_HAS_RUN" /* INIT_ACTION_HAS_RUN */] !== "true") { if (gitHubVersion.type === void 0) { core29.warning( @@ -161184,7 +161187,7 @@ async function runWrapper11() { await withGroup( "Uploading combined SARIF debug artifact", () => uploadCombinedSarifArtifacts( - logger, + logger2, gitHubVersion.type, // The codeqlVersion is not applicable for uploading non-codeql sarif. // We can assume all versions are safe to upload. diff --git a/src/cache.ts b/src/cache.ts index ca766bf746..f9f3afb6ea 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -3,6 +3,7 @@ import * as path from "path"; import { getTemporaryDirectory } from "./actions-util"; import * as json from "./json"; +import { getActionsLogger } from "./logging"; /** * The name of the temporary file that backs the on-disk cache of @@ -37,6 +38,7 @@ interface CommandCacheEntry { * (tier 3). */ const inMemoryCache = new Map(); +const logger = getActionsLogger(); function getCommandCacheFilePath(): string { return path.join(getTemporaryDirectory(), COMMAND_CACHE_FILENAME); @@ -56,8 +58,8 @@ function readCommandCacheFile(): Record { if (json.isObject(parsed)) { return parsed; } - } catch { - // Fall through and treat a malformed file as empty. + } catch (e) { + logger.warning(`Failed to read or parse command cache file: ${e}`); } return {}; } @@ -69,8 +71,8 @@ function readCommandCacheFile(): Record { function writeCommandCacheFile(data: Record): void { try { fs.writeFileSync(getCommandCacheFilePath(), JSON.stringify(data)); - } catch { - // Best-effort; ignore write failures. + } catch (e) { + logger.warning(`Failed to write command cache file: ${e}`); } } From 805b59092e7efaab37053dc1898e5fb1a435636f Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 19 Jun 2026 16:29:52 -0500 Subject: [PATCH 17/26] Remove duplicate key check in cacheCommandOutput and related tests This key-check is unnecessary because this function is only ever called if the key does NOT exist in the cache already. In that case, why check again? --- lib/entry-points.js | 5 ----- src/cache.test.ts | 16 ---------------- src/cache.ts | 9 --------- 3 files changed, 30 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 965223138b..07b48863f6 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -149942,11 +149942,6 @@ function writeCommandCacheFile(data) { } } function cacheCommandOutput(key, cmd, output) { - if (inMemoryCache.has(key)) { - throw new Error( - `cacheCommandOutput() should be called only once per key, but was called more than once for '${key}'.` - ); - } const entry = { cmd, output }; inMemoryCache.set(key, entry); const data = readCommandCacheFile(); diff --git a/src/cache.test.ts b/src/cache.test.ts index 6f9757e030..c76e4719fa 100644 --- a/src/cache.test.ts +++ b/src/cache.test.ts @@ -216,19 +216,3 @@ test.serial( }); }, ); - -test.serial( - "cacheCommandOutput throws if called twice for the same key", - async (t) => { - await withCacheDir(() => { - cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", { - value: 1, - }); - t.throws(() => - cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", { - value: 2, - }), - ); - }); - }, -); diff --git a/src/cache.ts b/src/cache.ts index f9f3afb6ea..660a0eb9c1 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -79,21 +79,12 @@ function writeCommandCacheFile(data: Record): void { /** * Stores the output of a command under `key`, writing it to both the in-memory * memo (tier 1) and the temporary file (tier 2). - * - * Should only be called once per key within a single process; doing otherwise - * indicates a logic error, since a value that has already been cached should be - * served from the memo rather than recomputed. */ export function cacheCommandOutput( key: CommandCacheKey, cmd: string, output: unknown, ): void { - if (inMemoryCache.has(key)) { - throw new Error( - `cacheCommandOutput() should be called only once per key, but was called more than once for '${key}'.`, - ); - } const entry: CommandCacheEntry = { cmd, output }; inMemoryCache.set(key, entry); From 895ffe7eb5dc00f0e37304117af54df325cf26ee Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 19 Jun 2026 17:45:48 -0500 Subject: [PATCH 18/26] Front-load caching and rear-load saving to disk This implementation saves CPU and I/O by not trying to write to the file on every set-cache. --- lib/entry-points.js | 13 ++++++++----- src/cache.test.ts | 42 ++++++++++++++++-------------------------- src/cache.ts | 16 +++++++--------- src/init-action.ts | 9 +++++++++ 4 files changed, 40 insertions(+), 40 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 07b48863f6..e3ad622953 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -149934,9 +149934,12 @@ function readCommandCacheFile() { } return {}; } -function writeCommandCacheFile(data) { +function writeCommandCacheFile() { try { - fs6.writeFileSync(getCommandCacheFilePath(), JSON.stringify(data)); + fs6.writeFileSync( + getCommandCacheFilePath(), + JSON.stringify(Object.fromEntries(inMemoryCache)) + ); } catch (e) { logger.warning(`Failed to write command cache file: ${e}`); } @@ -149944,9 +149947,6 @@ function writeCommandCacheFile(data) { function cacheCommandOutput(key, cmd, output) { const entry = { cmd, output }; inMemoryCache.set(key, entry); - const data = readCommandCacheFile(); - data[key] = entry; - writeCommandCacheFile(data); } function getCachedCommandOutput(key, cmd, validate) { const memoized = inMemoryCache.get(key); @@ -159013,6 +159013,8 @@ async function run3(startedAt) { toolsVersion = initCodeQLResult.toolsVersion; toolsSource = initCodeQLResult.toolsSource; zstdAvailability = initCodeQLResult.zstdAvailability; + await codeql.getVersion(); + await codeql.resolveLanguages(); await checkWorkflow(logger2, codeql); if ( // Only enable the experimental features env variable for Rust analysis if the user has explicitly @@ -159322,6 +159324,7 @@ exec ${goBinaryPath} "$@"` await saveConfig(config, logger2); core20.setOutput("codeql-path", config.codeQLCmd); core20.setOutput("codeql-version", (await codeql.getVersion()).version); + writeCommandCacheFile(); } catch (unwrappedError) { const error3 = wrapError(unwrappedError); core20.setFailed(error3.message); diff --git a/src/cache.test.ts b/src/cache.test.ts index c76e4719fa..71a07b4c4a 100644 --- a/src/cache.test.ts +++ b/src/cache.test.ts @@ -170,32 +170,19 @@ test.serial( }, ); -test.serial( - "cacheCommandOutput persists the output to both the memo and the file", - async (t) => { - await withCacheDir((cacheFilePath) => { - cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", { - hello: "world", - }); - - // Tier 2: the temporary file contains the entry. - const onDisk = JSON.parse( - fs.readFileSync(cacheFilePath, "utf8"), - ) as Record; - t.deepEqual(onDisk[CommandCacheKey.Version], { - cmd: "/path/to/codeql", - output: { hello: "world" }, - }); - - // Tier 1: the value is served from the memo even after the file is gone. - fs.rmSync(cacheFilePath); - t.deepEqual( - getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), - { hello: "world" }, - ); +test.serial("cacheCommandOutput persists the output to the memo", async (t) => { + await withCacheDir(() => { + cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", { + hello: "world", }); - }, -); + + // Tier 1: the value is immediately available from the memo. + t.deepEqual( + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), + { hello: "world" }, + ); + }); +}); test.serial( "getCachedCommandOutput prefers the in-memory memo over the file", @@ -207,7 +194,10 @@ test.serial( // Overwrite the file with a different value; the memo (tier 1) should win. writeCacheFile(cacheFilePath, { - [CommandCacheKey.Version]: { cmd: "/path/to/codeql", output: { value: 2 } }, + [CommandCacheKey.Version]: { + cmd: "/path/to/codeql", + output: { value: 2 }, + }, }); t.deepEqual( getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), diff --git a/src/cache.ts b/src/cache.ts index 660a0eb9c1..32ec7f9868 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -65,20 +65,22 @@ function readCommandCacheFile(): Record { } /** - * Persists the cache to the temporary file. Best-effort: a failure to write + * Persists the in-memory cache to the temporary file. Best-effort: a failure to write * just means a later step re-runs the CLI. */ -function writeCommandCacheFile(data: Record): void { +export function writeCommandCacheFile(): void { try { - fs.writeFileSync(getCommandCacheFilePath(), JSON.stringify(data)); + fs.writeFileSync( + getCommandCacheFilePath(), + JSON.stringify(Object.fromEntries(inMemoryCache)), + ); } catch (e) { logger.warning(`Failed to write command cache file: ${e}`); } } /** - * Stores the output of a command under `key`, writing it to both the in-memory - * memo (tier 1) and the temporary file (tier 2). + * Stores the output of a CLI command under `key` in a module-global object. */ export function cacheCommandOutput( key: CommandCacheKey, @@ -87,10 +89,6 @@ export function cacheCommandOutput( ): void { const entry: CommandCacheEntry = { cmd, output }; inMemoryCache.set(key, entry); - - const data = readCommandCacheFile(); - data[key] = entry; - writeCommandCacheFile(data); } /** diff --git a/src/init-action.ts b/src/init-action.ts index 9c9b45556b..dbcb2f0540 100644 --- a/src/init-action.ts +++ b/src/init-action.ts @@ -19,6 +19,7 @@ import { } from "./actions-util"; import { AnalysisKind, getAnalysisKinds } from "./analyses"; import { getGitHubVersion, GitHubApiCombinedDetails } from "./api-client"; +import { writeCommandCacheFile } from "./cache"; import { getDependencyCachingEnabled, getTotalCacheSize, @@ -323,6 +324,11 @@ async function run(startedAt: Date) { toolsSource = initCodeQLResult.toolsSource; zstdAvailability = initCodeQLResult.zstdAvailability; + // Populate the in-memory command cache with CLI version and languages. + // These results will be persisted to disk at the end of the init action. + await codeql.getVersion(); + await codeql.resolveLanguages(); + // Check the workflow for problems. If there are any problems, they are reported // to the workflow log. No exceptions are thrown. await checkWorkflow(logger, codeql); @@ -766,6 +772,9 @@ async function run(startedAt: Date) { core.setOutput("codeql-path", config.codeQLCmd); core.setOutput("codeql-version", (await codeql.getVersion()).version); + + // Persist the command cache to disk at the end of a successful init. + writeCommandCacheFile(); } catch (unwrappedError) { const error = wrapError(unwrappedError); core.setFailed(error.message); From 649bababe740aae717fbfd30fc0b4af8f7676a17 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 19 Jun 2026 17:49:45 -0500 Subject: [PATCH 19/26] Refactor cache storage to use cacheCommandOutput for consistency --- lib/entry-points.js | 2 +- src/cache.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index e3ad622953..aff18c1a4e 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -149957,7 +149957,7 @@ function getCachedCommandOutput(key, cmd, validate) { if (!isObject(entry) || !isString(entry.cmd) || cmd !== void 0 && entry.cmd !== cmd || validate !== void 0 && !validate(entry.output)) { return void 0; } - inMemoryCache.set(key, { cmd: entry.cmd, output: entry.output }); + cacheCommandOutput(key, entry.cmd, entry.output); return entry.output; } diff --git a/src/cache.ts b/src/cache.ts index 32ec7f9868..df8b69d8be 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -125,7 +125,7 @@ export function getCachedCommandOutput( } // Memoize so subsequent lookups in this process hit tier 1. - inMemoryCache.set(key, { cmd: entry.cmd, output: entry.output }); + cacheCommandOutput(key, entry.cmd, entry.output); return entry.output as T; } From b3c7aa7372bb8c2a98069821038d3ed34bd4d90f Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 19 Jun 2026 18:04:52 -0500 Subject: [PATCH 20/26] Add warning log for invalid data in command cache retrieval --- lib/entry-points.js | 1 + src/cache.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/lib/entry-points.js b/lib/entry-points.js index aff18c1a4e..348e213bd9 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -149955,6 +149955,7 @@ function getCachedCommandOutput(key, cmd, validate) { } const entry = readCommandCacheFile()[key]; if (!isObject(entry) || !isString(entry.cmd) || cmd !== void 0 && entry.cmd !== cmd || validate !== void 0 && !validate(entry.output)) { + logger.warning("Received invalid data from the command-cache file."); return void 0; } cacheCommandOutput(key, entry.cmd, entry.output); diff --git a/src/cache.ts b/src/cache.ts index df8b69d8be..7ec0d68516 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -121,6 +121,7 @@ export function getCachedCommandOutput( (cmd !== undefined && entry.cmd !== cmd) || (validate !== undefined && !validate(entry.output)) ) { + logger.warning("Received invalid data from the command-cache file."); return undefined; } From 41965b0e7be3045e3ddf8d5c7c30fe3f19a1480b Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Mon, 29 Jun 2026 22:16:21 -0500 Subject: [PATCH 21/26] Move `cache.ts` to `cli/output-cache.ts` This change should hopefully make the purpose of this module clear. --- src/{cache.test.ts => cli/output-cache.test.ts} | 7 ++++--- src/{cache.ts => cli/output-cache.ts} | 6 +++--- src/codeql.ts | 2 +- src/init-action.ts | 2 +- src/status-report.ts | 2 +- src/testing-utils.ts | 2 +- 6 files changed, 11 insertions(+), 10 deletions(-) rename src/{cache.test.ts => cli/output-cache.test.ts} (97%) rename src/{cache.ts => cli/output-cache.ts} (96%) diff --git a/src/cache.test.ts b/src/cli/output-cache.test.ts similarity index 97% rename from src/cache.test.ts rename to src/cli/output-cache.test.ts index 71a07b4c4a..2f15c1e65b 100644 --- a/src/cache.test.ts +++ b/src/cli/output-cache.test.ts @@ -4,14 +4,15 @@ import path from "path"; import test from "ava"; +import { isVersionInfo } from "../codeql"; +import { setupTests } from "../testing-utils"; + import { cacheCommandOutput, getCachedCommandOutput, resetCachedCommandOutputs, CommandCacheKey, -} from "./cache"; -import { isVersionInfo } from "./codeql"; -import { setupTests } from "./testing-utils"; +} from "./output-cache"; setupTests(test); diff --git a/src/cache.ts b/src/cli/output-cache.ts similarity index 96% rename from src/cache.ts rename to src/cli/output-cache.ts index 7ec0d68516..5af8a69c19 100644 --- a/src/cache.ts +++ b/src/cli/output-cache.ts @@ -1,9 +1,9 @@ import * as fs from "fs"; import * as path from "path"; -import { getTemporaryDirectory } from "./actions-util"; -import * as json from "./json"; -import { getActionsLogger } from "./logging"; +import { getTemporaryDirectory } from "../actions-util"; +import * as json from "../json"; +import { getActionsLogger } from "../logging"; /** * The name of the temporary file that backs the on-disk cache of diff --git a/src/codeql.ts b/src/codeql.ts index 0a00cda610..f05147c68b 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -16,7 +16,7 @@ import { cacheCommandOutput, getCachedCommandOutput, CommandCacheKey, -} from "./cache"; +} from "./cli/output-cache"; import { CliError, wrapCliConfigurationError } from "./cli-errors"; import { appendExtraQueryExclusions, type Config } from "./config-utils"; import { DocUrl } from "./doc-url"; diff --git a/src/init-action.ts b/src/init-action.ts index dbcb2f0540..a37da327d1 100644 --- a/src/init-action.ts +++ b/src/init-action.ts @@ -19,12 +19,12 @@ import { } from "./actions-util"; import { AnalysisKind, getAnalysisKinds } from "./analyses"; import { getGitHubVersion, GitHubApiCombinedDetails } from "./api-client"; -import { writeCommandCacheFile } from "./cache"; import { getDependencyCachingEnabled, getTotalCacheSize, shouldRestoreCache, } from "./caching-utils"; +import { writeCommandCacheFile } from "./cli/output-cache"; import { CodeQL } from "./codeql"; import { getConfigFileInput } from "./config/file"; import * as configUtils from "./config-utils"; diff --git a/src/status-report.ts b/src/status-report.ts index e6a489c5cc..2d79b53073 100644 --- a/src/status-report.ts +++ b/src/status-report.ts @@ -12,7 +12,7 @@ import { isSelfHostedRunner, } from "./actions-util"; import { getAnalysisKey, getApiClient } from "./api-client"; -import { getCachedCommandOutput, CommandCacheKey } from "./cache"; +import { getCachedCommandOutput, CommandCacheKey } from "./cli/output-cache"; import { isVersionInfo } from "./codeql"; import { parseRegistriesWithoutCredentials, type Config } from "./config-utils"; import { DependencyCacheRestoreStatusReport } from "./dependency-caching"; diff --git a/src/testing-utils.ts b/src/testing-utils.ts index b62242b267..d47f3be746 100644 --- a/src/testing-utils.ts +++ b/src/testing-utils.ts @@ -14,8 +14,8 @@ import { ActionsEnv, getActionVersion } from "./actions-util"; import { AnalysisKind } from "./analyses"; import * as apiClient from "./api-client"; import { GitHubApiDetails } from "./api-client"; -import { resetCachedCommandOutputs } from "./cache"; import { CachingKind } from "./caching-utils"; +import { resetCachedCommandOutputs } from "./cli/output-cache"; import * as codeql from "./codeql"; import { Config } from "./config-utils"; import * as defaults from "./defaults.json"; From c2f43799c5aca5fdaebaed44e5f4ef63d80a6987 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Mon, 29 Jun 2026 23:25:50 -0500 Subject: [PATCH 22/26] Refactor `CommandCacheKey` as a string union --- src/cli/output-cache.test.ts | 31 +++++++++++++++---------------- src/cli/output-cache.ts | 9 +-------- src/codeql.ts | 27 ++++++++++++++++++--------- src/status-report.ts | 4 ++-- 4 files changed, 36 insertions(+), 35 deletions(-) diff --git a/src/cli/output-cache.test.ts b/src/cli/output-cache.test.ts index 2f15c1e65b..2504f484fe 100644 --- a/src/cli/output-cache.test.ts +++ b/src/cli/output-cache.test.ts @@ -11,7 +11,6 @@ import { cacheCommandOutput, getCachedCommandOutput, resetCachedCommandOutputs, - CommandCacheKey, } from "./output-cache"; setupTests(test); @@ -52,14 +51,14 @@ test.serial( async (t) => { await withCacheDir((cacheFilePath) => { writeCacheFile(cacheFilePath, { - [CommandCacheKey.Version]: { + version: { cmd: "/path/to/codeql", output: { version: "2.20.0" }, }, }); t.deepEqual( getCachedCommandOutput( - CommandCacheKey.Version, + "version", "/path/to/codeql", isVersionInfo, ), @@ -74,14 +73,14 @@ test.serial( async (t) => { await withCacheDir((cacheFilePath) => { writeCacheFile(cacheFilePath, { - [CommandCacheKey.Version]: { + version: { cmd: "/path/to/other-codeql", output: { version: "2.20.0" }, }, }); t.is( getCachedCommandOutput( - CommandCacheKey.Version, + "version", "/path/to/codeql", isVersionInfo, ), @@ -98,7 +97,7 @@ test.serial( fs.writeFileSync(cacheFilePath, "not valid json"); t.is( getCachedCommandOutput( - CommandCacheKey.Version, + "version", "/path/to/codeql", isVersionInfo, ), @@ -114,7 +113,7 @@ test.serial( await withCacheDir(() => { t.is( getCachedCommandOutput( - CommandCacheKey.Version, + "version", "/path/to/codeql", isVersionInfo, ), @@ -136,11 +135,11 @@ test.serial( ]) { resetCachedCommandOutputs(); writeCacheFile(cacheFilePath, { - [CommandCacheKey.Version]: { cmd: "/path/to/codeql", output }, + version: { cmd: "/path/to/codeql", output }, }); t.is( getCachedCommandOutput( - CommandCacheKey.Version, + "version", "/path/to/codeql", isVersionInfo, ), @@ -157,11 +156,11 @@ test.serial( async (t) => { await withCacheDir((cacheFilePath) => { writeCacheFile(cacheFilePath, { - [CommandCacheKey.Version]: { output: { version: "2.20.0" } }, + version: { output: { version: "2.20.0" } }, }); t.is( getCachedCommandOutput( - CommandCacheKey.Version, + "version", "/path/to/codeql", isVersionInfo, ), @@ -173,13 +172,13 @@ test.serial( test.serial("cacheCommandOutput persists the output to the memo", async (t) => { await withCacheDir(() => { - cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", { + cacheCommandOutput("version", "/path/to/codeql", { hello: "world", }); // Tier 1: the value is immediately available from the memo. t.deepEqual( - getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), + getCachedCommandOutput("version", "/path/to/codeql"), { hello: "world" }, ); }); @@ -189,19 +188,19 @@ test.serial( "getCachedCommandOutput prefers the in-memory memo over the file", async (t) => { await withCacheDir((cacheFilePath) => { - cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", { + cacheCommandOutput("version", "/path/to/codeql", { value: 1, }); // Overwrite the file with a different value; the memo (tier 1) should win. writeCacheFile(cacheFilePath, { - [CommandCacheKey.Version]: { + version: { cmd: "/path/to/codeql", output: { value: 2 }, }, }); t.deepEqual( - getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), + getCachedCommandOutput("version", "/path/to/codeql"), { value: 1 }, ); }); diff --git a/src/cli/output-cache.ts b/src/cli/output-cache.ts index 5af8a69c19..4acb055dae 100644 --- a/src/cli/output-cache.ts +++ b/src/cli/output-cache.ts @@ -11,15 +11,8 @@ import { getActionsLogger } from "../logging"; */ const COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; -/** Named keys for the CLI command-output cache. */ -export const CommandCacheKey = { - Version: "version", - ResolveLanguages: "resolveLanguages", -} as const; - /** A key used to identify cached command output. */ -export type CommandCacheKey = - (typeof CommandCacheKey)[keyof typeof CommandCacheKey]; +export type CommandCacheKey = "version" | "resolve languages"; /** A single cached command output together with the CLI path it came from. */ interface CommandCacheEntry { diff --git a/src/codeql.ts b/src/codeql.ts index f05147c68b..9bfeba911d 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -15,7 +15,7 @@ import * as api from "./api-client"; import { cacheCommandOutput, getCachedCommandOutput, - CommandCacheKey, + type CommandCacheKey, } from "./cli/output-cache"; import { CliError, wrapCliConfigurationError } from "./cli-errors"; import { appendExtraQueryExclusions, type Config } from "./config-utils"; @@ -42,6 +42,11 @@ import { BuildMode, CleanupLevel, getErrorMessage } from "./util"; type Options = Array; +type CommandCacheKeyOutputMap = { + version: VersionInfo; + "resolve languages": ResolveLanguagesOutput; +}; + /** * Extra command line options for the codeql commands. */ @@ -547,13 +552,17 @@ export async function getCodeQLForTesting( * @param run Invokes the CLI to compute the output when it isn't cached. * @param validate Optional type guard for values loaded from the temporary file. */ -async function getCachedOrRun( - key: CommandCacheKey, +async function getCachedOrRun( + key: K, cmd: string, - run: () => Promise, - validate?: (output: unknown) => output is T, -): Promise { - let result = getCachedCommandOutput(key, cmd, validate); + run: () => Promise, + validate?: (output: unknown) => output is CommandCacheKeyOutputMap[K], +): Promise { + let result = getCachedCommandOutput( + key, + cmd, + validate, + ); if (result === undefined) { result = await run(); cacheCommandOutput(key, cmd, result); @@ -579,7 +588,7 @@ async function getCodeQLForCmd( }, async getVersion() { return getCachedOrRun( - CommandCacheKey.Version, + "version", cmd, () => runCliJson(cmd, ["version", "--format=json"], { @@ -786,7 +795,7 @@ async function getCodeQLForCmd( }, async resolveLanguages() { return getCachedOrRun( - CommandCacheKey.ResolveLanguages, + "resolve languages", cmd, async () => { const isFilterToLanguagesWithQueriesSupported = diff --git a/src/status-report.ts b/src/status-report.ts index 2d79b53073..43b279f1b7 100644 --- a/src/status-report.ts +++ b/src/status-report.ts @@ -12,7 +12,7 @@ import { isSelfHostedRunner, } from "./actions-util"; import { getAnalysisKey, getApiClient } from "./api-client"; -import { getCachedCommandOutput, CommandCacheKey } from "./cli/output-cache"; +import { getCachedCommandOutput } from "./cli/output-cache"; import { isVersionInfo } from "./codeql"; import { parseRegistriesWithoutCredentials, type Config } from "./config-utils"; import { DependencyCacheRestoreStatusReport } from "./dependency-caching"; @@ -285,7 +285,7 @@ export async function createStatusReportBase( } const runnerOs = getRequiredEnvParam("RUNNER_OS"); const codeQlCliVersion = getCachedCommandOutput( - CommandCacheKey.Version, + "version", undefined, isVersionInfo, ); From 0d698171d350266bf2b7dafa80e83d2479fa79a3 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Tue, 30 Jun 2026 15:39:36 -0500 Subject: [PATCH 23/26] Move output type validators to `output-cache.ts` module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This move simplifies the consumer-side of the module. And, also, the validators should be an internal implementation detail—not the concern of those who wish to "get" a cached output. --- src/cli/output-cache.test.ts | 30 ++------ src/cli/output-cache.ts | 120 +++++++++++++++++++++++++----- src/codeql.ts | 137 +++++++---------------------------- src/status-report.ts | 7 +- src/testing-utils.ts | 3 +- src/tools-features.ts | 2 +- 6 files changed, 143 insertions(+), 156 deletions(-) diff --git a/src/cli/output-cache.test.ts b/src/cli/output-cache.test.ts index 2504f484fe..d81c613c31 100644 --- a/src/cli/output-cache.test.ts +++ b/src/cli/output-cache.test.ts @@ -4,13 +4,13 @@ import path from "path"; import test from "ava"; -import { isVersionInfo } from "../codeql"; import { setupTests } from "../testing-utils"; import { cacheCommandOutput, getCachedCommandOutput, resetCachedCommandOutputs, + type VersionInfo, } from "./output-cache"; setupTests(test); @@ -60,7 +60,6 @@ test.serial( getCachedCommandOutput( "version", "/path/to/codeql", - isVersionInfo, ), { version: "2.20.0" }, ); @@ -82,7 +81,6 @@ test.serial( getCachedCommandOutput( "version", "/path/to/codeql", - isVersionInfo, ), undefined, ); @@ -99,7 +97,6 @@ test.serial( getCachedCommandOutput( "version", "/path/to/codeql", - isVersionInfo, ), undefined, ); @@ -115,7 +112,6 @@ test.serial( getCachedCommandOutput( "version", "/path/to/codeql", - isVersionInfo, ), undefined, ); @@ -141,7 +137,6 @@ test.serial( getCachedCommandOutput( "version", "/path/to/codeql", - isVersionInfo, ), undefined, JSON.stringify(output), @@ -162,7 +157,6 @@ test.serial( getCachedCommandOutput( "version", "/path/to/codeql", - isVersionInfo, ), undefined, ); @@ -172,15 +166,11 @@ test.serial( test.serial("cacheCommandOutput persists the output to the memo", async (t) => { await withCacheDir(() => { - cacheCommandOutput("version", "/path/to/codeql", { - hello: "world", - }); + const output: VersionInfo = { version: "2.20.0" }; + cacheCommandOutput("version", "/path/to/codeql", output); // Tier 1: the value is immediately available from the memo. - t.deepEqual( - getCachedCommandOutput("version", "/path/to/codeql"), - { hello: "world" }, - ); + t.deepEqual(getCachedCommandOutput("version", "/path/to/codeql"), output); }); }); @@ -188,21 +178,17 @@ test.serial( "getCachedCommandOutput prefers the in-memory memo over the file", async (t) => { await withCacheDir((cacheFilePath) => { - cacheCommandOutput("version", "/path/to/codeql", { - value: 1, - }); + const output: VersionInfo = { version: "2.20.0", overlayVersion: 1 }; + cacheCommandOutput("version", "/path/to/codeql", output); // Overwrite the file with a different value; the memo (tier 1) should win. writeCacheFile(cacheFilePath, { version: { cmd: "/path/to/codeql", - output: { value: 2 }, + output: { version: "2.21.0" }, }, }); - t.deepEqual( - getCachedCommandOutput("version", "/path/to/codeql"), - { value: 1 }, - ); + t.deepEqual(getCachedCommandOutput("version", "/path/to/codeql"), output); }); }, ); diff --git a/src/cli/output-cache.ts b/src/cli/output-cache.ts index 4acb055dae..78dbbe4f26 100644 --- a/src/cli/output-cache.ts +++ b/src/cli/output-cache.ts @@ -14,15 +14,97 @@ const COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; /** A key used to identify cached command output. */ export type CommandCacheKey = "version" | "resolve languages"; +export interface VersionInfo { + version: string; + features?: { [name: string]: boolean }; + /** + * The overlay version helps deal with backward incompatible changes for + * overlay analysis. When a precompiled query pack reports the same overlay + * version as the CodeQL CLI, we can use the CodeQL CLI to perform overlay + * analysis with that pack. Otherwise, if the overlay versions are different, + * or if either the pack or the CLI does not report an overlay version, + * we need to revert to non-overlay analysis. + */ + overlayVersion?: number; +} + +/** Returns true if `x` is a {@link VersionInfo}. */ +export function isVersionInfo(x: unknown): x is VersionInfo { + return ( + json.isObject(x) && + json.validateSchema( + { + version: json.string, + features: json.optional(json.object), + overlayVersion: json.optional(json.number), + }, + x, + ) + ); +} + +export interface ResolveLanguagesOutput { + aliases?: { + [alias: string]: string; + }; + extractors: { + [language: string]: Array<{ + extractor_root: string; + extractor_options?: any; + }>; + }; +} + +/** Returns true if `x` is a {@link ResolveLanguagesOutput}. */ +export function isResolveLanguagesOutput( + x: unknown, +): x is ResolveLanguagesOutput { + return ( + json.isObject(x) && + json.isObject(x.extractors) && + Object.values(x.extractors).every( + (extractorList) => + json.isArray(extractorList) && + extractorList.every( + (extractor) => + json.isObject<{ extractor_root: unknown }>(extractor) && + json.isString(extractor.extractor_root), + ), + ) && + (x.aliases === undefined || + (json.isObject(x.aliases) && + Object.values(x.aliases).every((alias) => json.isString(alias)))) + ); +} + +export type CommandCacheKeyOutputMap = { + version: VersionInfo; + "resolve languages": ResolveLanguagesOutput; +}; + +const commandCacheValidators: { + [K in CommandCacheKey]: ( + output: unknown, + ) => output is CommandCacheKeyOutputMap[K]; +} = { + version: isVersionInfo, + "resolve languages": isResolveLanguagesOutput, +}; + +interface StoredCommandCacheEntry { + cmd: string; + output: unknown; +} + /** A single cached command output together with the CLI path it came from. */ -interface CommandCacheEntry { +export interface CommandCacheEntry { /** * The path to the CodeQL CLI that produced `output`. Persisted so that a * different step using a different CodeQL bundle doesn't pick up a stale * value. */ cmd: string; - output: unknown; + output: CommandCacheKeyOutputMap[K]; } /** @@ -30,7 +112,10 @@ interface CommandCacheEntry { * whenever a value is read from the file (tier 2) or computed via the CLI * (tier 3). */ -const inMemoryCache = new Map(); +const inMemoryCache = new Map< + CommandCacheKey, + CommandCacheEntry +>(); const logger = getActionsLogger(); function getCommandCacheFilePath(): string { @@ -41,7 +126,7 @@ function getCommandCacheFilePath(): string { * Reads and parses the temporary cache file. Best-effort: a missing, malformed, * or otherwise unreadable file is treated as an empty cache. */ -function readCommandCacheFile(): Record { +function readCommandCacheFile(): Record { if (!fs.existsSync(getCommandCacheFilePath())) { return {}; } @@ -75,12 +160,12 @@ export function writeCommandCacheFile(): void { /** * Stores the output of a CLI command under `key` in a module-global object. */ -export function cacheCommandOutput( - key: CommandCacheKey, +export function cacheCommandOutput( + key: K, cmd: string, - output: unknown, + output: CommandCacheKeyOutputMap[K], ): void { - const entry: CommandCacheEntry = { cmd, output }; + const entry: CommandCacheEntry = { cmd, output }; inMemoryCache.set(key, entry); } @@ -95,32 +180,33 @@ export function cacheCommandOutput( * A return value of `undefined` signals the caller to fall back to tier 3 (the * CLI). */ -export function getCachedCommandOutput( - key: CommandCacheKey, +export function getCachedCommandOutput( + key: K, cmd?: string, - validate?: (output: unknown) => output is T, -): T | undefined { +): CommandCacheKeyOutputMap[K] | undefined { // Tier 1: the in-memory variable. const memoized = inMemoryCache.get(key); if (memoized !== undefined) { - return memoized.output as T; + return memoized.output as CommandCacheKeyOutputMap[K]; } // Tier 2: the temporary file persisted by an earlier step, if any. const entry = readCommandCacheFile()[key] as unknown; if ( - !json.isObject(entry) || + !json.isObject(entry) || !json.isString(entry.cmd) || (cmd !== undefined && entry.cmd !== cmd) || - (validate !== undefined && !validate(entry.output)) + !commandCacheValidators[key](entry.output) ) { logger.warning("Received invalid data from the command-cache file."); return undefined; } // Memoize so subsequent lookups in this process hit tier 1. - cacheCommandOutput(key, entry.cmd, entry.output); - return entry.output as T; + const cachedEntry = entry as StoredCommandCacheEntry; + const output = cachedEntry.output as CommandCacheKeyOutputMap[K]; + cacheCommandOutput(key, cachedEntry.cmd, output); + return output; } /** diff --git a/src/codeql.ts b/src/codeql.ts index 9bfeba911d..b930782868 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -15,7 +15,10 @@ import * as api from "./api-client"; import { cacheCommandOutput, getCachedCommandOutput, + type CommandCacheKeyOutputMap, type CommandCacheKey, + type ResolveLanguagesOutput, + type VersionInfo, } from "./cli/output-cache"; import { CliError, wrapCliConfigurationError } from "./cli-errors"; import { appendExtraQueryExclusions, type Config } from "./config-utils"; @@ -27,7 +30,6 @@ import { FeatureEnablement, } from "./feature-flags"; import { isAnalyzingDefaultBranch } from "./git-utils"; -import * as json from "./json"; import { Language } from "./languages"; import { Logger } from "./logging"; import { writeBaseDatabaseOidsFile, writeOverlayChangesFile } from "./overlay"; @@ -42,11 +44,6 @@ import { BuildMode, CleanupLevel, getErrorMessage } from "./util"; type Options = Array; -type CommandCacheKeyOutputMap = { - version: VersionInfo; - "resolve languages": ResolveLanguagesOutput; -}; - /** * Extra command line options for the codeql commands. */ @@ -225,73 +222,10 @@ export interface CodeQL { ): Promise; } -export interface VersionInfo { - version: string; - features?: { [name: string]: boolean }; - /** - * The overlay version helps deal with backward incompatible changes for - * overlay analysis. When a precompiled query pack reports the same overlay - * version as the CodeQL CLI, we can use the CodeQL CLI to perform overlay - * analysis with that pack. Otherwise, if the overlay versions are different, - * or if either the pack or the CLI does not report an overlay version, - * we need to revert to non-overlay analysis. - */ - overlayVersion?: number; -} - -/** Returns true if `x` is a {@link VersionInfo}. */ -export function isVersionInfo(x: unknown): x is VersionInfo { - return ( - json.isObject(x) && - json.validateSchema( - { - version: json.string, - features: json.optional(json.object), - overlayVersion: json.optional(json.number), - }, - x, - ) - ); -} - export interface ResolveDatabaseOutput { overlayBaseSpecifier?: string; } -export interface ResolveLanguagesOutput { - aliases?: { - [alias: string]: string; - }; - extractors: { - [language: string]: Array<{ - extractor_root: string; - extractor_options?: any; - }>; - }; -} - -/** Returns true if `x` is a {@link ResolveLanguagesOutput}. */ -export function isResolveLanguagesOutput( - x: unknown, -): x is ResolveLanguagesOutput { - return ( - json.isObject(x) && - json.isObject(x.extractors) && - Object.values(x.extractors).every( - (extractorList) => - json.isArray(extractorList) && - extractorList.every( - (extractor) => - json.isObject<{ extractor_root: unknown }>(extractor) && - json.isString(extractor.extractor_root), - ), - ) && - (x.aliases === undefined || - (json.isObject(x.aliases) && - Object.values(x.aliases).every((alias) => json.isString(alias)))) - ); -} - export interface ResolveBuildEnvironmentOutput { configuration?: { [language: string]: { @@ -550,19 +484,13 @@ export async function getCodeQLForTesting( * @param key The cache key identifying the command's output. * @param cmd The path to the CodeQL CLI the output is obtained from. * @param run Invokes the CLI to compute the output when it isn't cached. - * @param validate Optional type guard for values loaded from the temporary file. */ async function getCachedOrRun( key: K, cmd: string, run: () => Promise, - validate?: (output: unknown) => output is CommandCacheKeyOutputMap[K], ): Promise { - let result = getCachedCommandOutput( - key, - cmd, - validate, - ); + let result = getCachedCommandOutput(key, cmd); if (result === undefined) { result = await run(); cacheCommandOutput(key, cmd, result); @@ -587,14 +515,10 @@ async function getCodeQLForCmd( return cmd; }, async getVersion() { - return getCachedOrRun( - "version", - cmd, - () => - runCliJson(cmd, ["version", "--format=json"], { - noStreamStdout: true, - }), - isVersionInfo, + return getCachedOrRun("version", cmd, () => + runCliJson(cmd, ["version", "--format=json"], { + noStreamStdout: true, + }), ); }, async printVersion() { @@ -794,31 +718,26 @@ async function getCodeQLForCmd( await runCli(cmd, args); }, async resolveLanguages() { - return getCachedOrRun( - "resolve languages", - cmd, - async () => { - const isFilterToLanguagesWithQueriesSupported = - await this.supportsFeature( - ToolsFeature.BuiltinExtractorsSpecifyDefaultQueries, - ); - return runCliJson(cmd, [ - "resolve", - "languages", - "--format=betterjson", - "--extractor-options-verbosity=4", - "--extractor-include-aliases", - // TODO: Unconditionally include `--filter-to-languages-with-queries` - // once CODEQL_MINIMUM_VERSION is at least v2.23.0 - // — the first version to support this flag. - ...(isFilterToLanguagesWithQueriesSupported - ? ["--filter-to-languages-with-queries"] - : []), - ...getExtraOptionsFromEnv(["resolve", "languages"]), - ]); - }, - isResolveLanguagesOutput, - ); + return getCachedOrRun("resolve languages", cmd, async () => { + const isFilterToLanguagesWithQueriesSupported = + await this.supportsFeature( + ToolsFeature.BuiltinExtractorsSpecifyDefaultQueries, + ); + return runCliJson(cmd, [ + "resolve", + "languages", + "--format=betterjson", + "--extractor-options-verbosity=4", + "--extractor-include-aliases", + // TODO: Unconditionally include `--filter-to-languages-with-queries` + // once CODEQL_MINIMUM_VERSION is at least v2.23.0 + // — the first version to support this flag. + ...(isFilterToLanguagesWithQueriesSupported + ? ["--filter-to-languages-with-queries"] + : []), + ...getExtraOptionsFromEnv(["resolve", "languages"]), + ]); + }); }, async resolveBuildEnvironment( workingDir: string | undefined, diff --git a/src/status-report.ts b/src/status-report.ts index 43b279f1b7..7cf152ce1f 100644 --- a/src/status-report.ts +++ b/src/status-report.ts @@ -13,7 +13,6 @@ import { } from "./actions-util"; import { getAnalysisKey, getApiClient } from "./api-client"; import { getCachedCommandOutput } from "./cli/output-cache"; -import { isVersionInfo } from "./codeql"; import { parseRegistriesWithoutCredentials, type Config } from "./config-utils"; import { DependencyCacheRestoreStatusReport } from "./dependency-caching"; import { DocUrl } from "./doc-url"; @@ -284,11 +283,7 @@ export async function createStatusReportBase( core.exportVariable(EnvVar.WORKFLOW_STARTED_AT, workflowStartedAt); } const runnerOs = getRequiredEnvParam("RUNNER_OS"); - const codeQlCliVersion = getCachedCommandOutput( - "version", - undefined, - isVersionInfo, - ); + const codeQlCliVersion = getCachedCommandOutput("version", undefined); const actionRef = process.env["GITHUB_ACTION_REF"] || ""; const testingEnvironment = getTestingEnvironment(); // re-export the testing environment variable so that it is available to subsequent steps, diff --git a/src/testing-utils.ts b/src/testing-utils.ts index d47f3be746..50876b21fd 100644 --- a/src/testing-utils.ts +++ b/src/testing-utils.ts @@ -15,6 +15,7 @@ import { AnalysisKind } from "./analyses"; import * as apiClient from "./api-client"; import { GitHubApiDetails } from "./api-client"; import { CachingKind } from "./caching-utils"; +import type { VersionInfo } from "./cli/output-cache"; import { resetCachedCommandOutputs } from "./cli/output-cache"; import * as codeql from "./codeql"; import { Config } from "./config-utils"; @@ -479,7 +480,7 @@ export const makeVersionInfo = ( version: string, features?: { [name: string]: boolean }, overlayVersion?: number, -): codeql.VersionInfo => ({ +): VersionInfo => ({ version, features, overlayVersion, diff --git a/src/tools-features.ts b/src/tools-features.ts index ff87b754da..55be17883c 100644 --- a/src/tools-features.ts +++ b/src/tools-features.ts @@ -1,6 +1,6 @@ import * as semver from "semver"; -import type { VersionInfo } from "./codeql"; +import type { VersionInfo } from "./cli/output-cache"; export enum ToolsFeature { BuiltinExtractorsSpecifyDefaultQueries = "builtinExtractorsSpecifyDefaultQueries", From da149812f1432ca8dd89eb2c43d4acbbdb5f486c Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Tue, 30 Jun 2026 16:06:13 -0500 Subject: [PATCH 24/26] Switch `CommandCacheKey` back to an `enum` The code reads better/simpler as an `enum`. --- lib/entry-points.js | 107 +++++++++++++++++------------------ src/cli/output-cache.test.ts | 55 +++++++----------- src/cli/output-cache.ts | 17 +++--- src/codeql.ts | 6 +- src/status-report.ts | 7 ++- 5 files changed, 91 insertions(+), 101 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 348e213bd9..e713e01433 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -149863,7 +149863,7 @@ var path15 = __toESM(require("path")); var core10 = __toESM(require_core()); var toolrunner3 = __toESM(require_toolrunner()); -// src/cache.ts +// src/cli/output-cache.ts var fs6 = __toESM(require("fs")); var path6 = __toESM(require("path")); @@ -149908,11 +149908,28 @@ function formatDuration(durationMs) { return `${minutes}m${seconds}s`; } -// src/cache.ts +// src/cli/output-cache.ts var COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; -var CommandCacheKey = { - Version: "version", - ResolveLanguages: "resolveLanguages" +function isVersionInfo(x) { + return isObject(x) && validateSchema( + { + version: string, + features: optional(object), + overlayVersion: optional(number) + }, + x + ); +} +function isResolveLanguagesOutput(x) { + return isObject(x) && isObject(x.extractors) && Object.values(x.extractors).every( + (extractorList) => isArray(extractorList) && extractorList.every( + (extractor) => isObject(extractor) && isString(extractor.extractor_root) + ) + ) && (x.aliases === void 0 || isObject(x.aliases) && Object.values(x.aliases).every((alias) => isString(alias))); +} +var commandCacheValidators = { + ["version" /* Version */]: isVersionInfo, + ["resolve languages" /* ResolveLanguages */]: isResolveLanguagesOutput }; var inMemoryCache = /* @__PURE__ */ new Map(); var logger = getActionsLogger(); @@ -149948,18 +149965,20 @@ function cacheCommandOutput(key, cmd, output) { const entry = { cmd, output }; inMemoryCache.set(key, entry); } -function getCachedCommandOutput(key, cmd, validate) { +function getCachedCommandOutput(key, cmd) { const memoized = inMemoryCache.get(key); if (memoized !== void 0) { return memoized.output; } const entry = readCommandCacheFile()[key]; - if (!isObject(entry) || !isString(entry.cmd) || cmd !== void 0 && entry.cmd !== cmd || validate !== void 0 && !validate(entry.output)) { + if (!isObject(entry) || !isString(entry.cmd) || cmd !== void 0 && entry.cmd !== cmd || !commandCacheValidators[key](entry.output)) { logger.warning("Received invalid data from the command-cache file."); return void 0; } - cacheCommandOutput(key, entry.cmd, entry.output); - return entry.output; + const cachedEntry = entry; + const output = cachedEntry.output; + cacheCommandOutput(key, cachedEntry.cmd, output); + return output; } // src/cli-errors.ts @@ -153676,23 +153695,6 @@ async function getCombinedTracerConfig(codeql, config) { } // src/codeql.ts -function isVersionInfo(x) { - return isObject(x) && validateSchema( - { - version: string, - features: optional(object), - overlayVersion: optional(number) - }, - x - ); -} -function isResolveLanguagesOutput(x) { - return isObject(x) && isObject(x.extractors) && Object.values(x.extractors).every( - (extractorList) => isArray(extractorList) && extractorList.every( - (extractor) => isObject(extractor) && isString(extractor.extractor_root) - ) - ) && (x.aliases === void 0 || isObject(x.aliases) && Object.values(x.aliases).every((alias) => isString(alias))); -} var cachedCodeQL = void 0; var CODEQL_MINIMUM_VERSION = "2.19.4"; var CODEQL_NEXT_MINIMUM_VERSION = "2.19.4"; @@ -153755,8 +153757,8 @@ async function getCodeQL(cmd) { } return cachedCodeQL; } -async function getCachedOrRun(key, cmd, run9, validate) { - let result = getCachedCommandOutput(key, cmd, validate); +async function getCachedOrRun(key, cmd, run9) { + let result = getCachedCommandOutput(key, cmd); if (result === void 0) { result = await run9(); cacheCommandOutput(key, cmd, result); @@ -153770,12 +153772,11 @@ async function getCodeQLForCmd(cmd, checkVersion) { }, async getVersion() { return getCachedOrRun( - CommandCacheKey.Version, + "version" /* Version */, cmd, () => runCliJson(cmd, ["version", "--format=json"], { noStreamStdout: true - }), - isVersionInfo + }) ); }, async printVersion() { @@ -153931,28 +153932,23 @@ async function getCodeQLForCmd(cmd, checkVersion) { await runCli(cmd, args); }, async resolveLanguages() { - return getCachedOrRun( - CommandCacheKey.ResolveLanguages, - cmd, - async () => { - const isFilterToLanguagesWithQueriesSupported = await this.supportsFeature( - "builtinExtractorsSpecifyDefaultQueries" /* BuiltinExtractorsSpecifyDefaultQueries */ - ); - return runCliJson(cmd, [ - "resolve", - "languages", - "--format=betterjson", - "--extractor-options-verbosity=4", - "--extractor-include-aliases", - // TODO: Unconditionally include `--filter-to-languages-with-queries` - // once CODEQL_MINIMUM_VERSION is at least v2.23.0 - // — the first version to support this flag. - ...isFilterToLanguagesWithQueriesSupported ? ["--filter-to-languages-with-queries"] : [], - ...getExtraOptionsFromEnv(["resolve", "languages"]) - ]); - }, - isResolveLanguagesOutput - ); + return getCachedOrRun("resolve languages" /* ResolveLanguages */, cmd, async () => { + const isFilterToLanguagesWithQueriesSupported = await this.supportsFeature( + "builtinExtractorsSpecifyDefaultQueries" /* BuiltinExtractorsSpecifyDefaultQueries */ + ); + return runCliJson(cmd, [ + "resolve", + "languages", + "--format=betterjson", + "--extractor-options-verbosity=4", + "--extractor-include-aliases", + // TODO: Unconditionally include `--filter-to-languages-with-queries` + // once CODEQL_MINIMUM_VERSION is at least v2.23.0 + // — the first version to support this flag. + ...isFilterToLanguagesWithQueriesSupported ? ["--filter-to-languages-with-queries"] : [], + ...getExtraOptionsFromEnv(["resolve", "languages"]) + ]); + }); }, async resolveBuildEnvironment(workingDir, language) { const codeqlArgs = [ @@ -155213,9 +155209,8 @@ async function createStatusReportBase(actionName, status, actionStartedAt, confi } const runnerOs = getRequiredEnvParam("RUNNER_OS"); const codeQlCliVersion = getCachedCommandOutput( - CommandCacheKey.Version, - void 0, - isVersionInfo + "version" /* Version */, + void 0 ); const actionRef = process.env["GITHUB_ACTION_REF"] || ""; const testingEnvironment = getTestingEnvironment(); diff --git a/src/cli/output-cache.test.ts b/src/cli/output-cache.test.ts index d81c613c31..c66af14919 100644 --- a/src/cli/output-cache.test.ts +++ b/src/cli/output-cache.test.ts @@ -8,6 +8,7 @@ import { setupTests } from "../testing-utils"; import { cacheCommandOutput, + CommandCacheKey, getCachedCommandOutput, resetCachedCommandOutputs, type VersionInfo, @@ -51,16 +52,13 @@ test.serial( async (t) => { await withCacheDir((cacheFilePath) => { writeCacheFile(cacheFilePath, { - version: { + [CommandCacheKey.Version]: { cmd: "/path/to/codeql", output: { version: "2.20.0" }, }, }); t.deepEqual( - getCachedCommandOutput( - "version", - "/path/to/codeql", - ), + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), { version: "2.20.0" }, ); }); @@ -72,16 +70,13 @@ test.serial( async (t) => { await withCacheDir((cacheFilePath) => { writeCacheFile(cacheFilePath, { - version: { + [CommandCacheKey.Version]: { cmd: "/path/to/other-codeql", output: { version: "2.20.0" }, }, }); t.is( - getCachedCommandOutput( - "version", - "/path/to/codeql", - ), + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), undefined, ); }); @@ -94,10 +89,7 @@ test.serial( await withCacheDir((cacheFilePath) => { fs.writeFileSync(cacheFilePath, "not valid json"); t.is( - getCachedCommandOutput( - "version", - "/path/to/codeql", - ), + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), undefined, ); }); @@ -109,10 +101,7 @@ test.serial( async (t) => { await withCacheDir(() => { t.is( - getCachedCommandOutput( - "version", - "/path/to/codeql", - ), + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), undefined, ); }); @@ -131,13 +120,10 @@ test.serial( ]) { resetCachedCommandOutputs(); writeCacheFile(cacheFilePath, { - version: { cmd: "/path/to/codeql", output }, + [CommandCacheKey.Version]: { cmd: "/path/to/codeql", output }, }); t.is( - getCachedCommandOutput( - "version", - "/path/to/codeql", - ), + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), undefined, JSON.stringify(output), ); @@ -151,13 +137,10 @@ test.serial( async (t) => { await withCacheDir((cacheFilePath) => { writeCacheFile(cacheFilePath, { - version: { output: { version: "2.20.0" } }, + [CommandCacheKey.Version]: { output: { version: "2.20.0" } }, }); t.is( - getCachedCommandOutput( - "version", - "/path/to/codeql", - ), + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), undefined, ); }); @@ -167,10 +150,13 @@ test.serial( test.serial("cacheCommandOutput persists the output to the memo", async (t) => { await withCacheDir(() => { const output: VersionInfo = { version: "2.20.0" }; - cacheCommandOutput("version", "/path/to/codeql", output); + cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", output); // Tier 1: the value is immediately available from the memo. - t.deepEqual(getCachedCommandOutput("version", "/path/to/codeql"), output); + t.deepEqual( + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), + output, + ); }); }); @@ -179,16 +165,19 @@ test.serial( async (t) => { await withCacheDir((cacheFilePath) => { const output: VersionInfo = { version: "2.20.0", overlayVersion: 1 }; - cacheCommandOutput("version", "/path/to/codeql", output); + cacheCommandOutput(CommandCacheKey.Version, "/path/to/codeql", output); // Overwrite the file with a different value; the memo (tier 1) should win. writeCacheFile(cacheFilePath, { - version: { + [CommandCacheKey.Version]: { cmd: "/path/to/codeql", output: { version: "2.21.0" }, }, }); - t.deepEqual(getCachedCommandOutput("version", "/path/to/codeql"), output); + t.deepEqual( + getCachedCommandOutput(CommandCacheKey.Version, "/path/to/codeql"), + output, + ); }); }, ); diff --git a/src/cli/output-cache.ts b/src/cli/output-cache.ts index 78dbbe4f26..69ec397439 100644 --- a/src/cli/output-cache.ts +++ b/src/cli/output-cache.ts @@ -12,7 +12,10 @@ import { getActionsLogger } from "../logging"; const COMMAND_CACHE_FILENAME = "codeql-action-command-cache.json"; /** A key used to identify cached command output. */ -export type CommandCacheKey = "version" | "resolve languages"; +export enum CommandCacheKey { + Version = "version", + ResolveLanguages = "resolve languages", +} export interface VersionInfo { version: string; @@ -78,8 +81,8 @@ export function isResolveLanguagesOutput( } export type CommandCacheKeyOutputMap = { - version: VersionInfo; - "resolve languages": ResolveLanguagesOutput; + [CommandCacheKey.Version]: VersionInfo; + [CommandCacheKey.ResolveLanguages]: ResolveLanguagesOutput; }; const commandCacheValidators: { @@ -87,8 +90,8 @@ const commandCacheValidators: { output: unknown, ) => output is CommandCacheKeyOutputMap[K]; } = { - version: isVersionInfo, - "resolve languages": isResolveLanguagesOutput, + [CommandCacheKey.Version]: isVersionInfo, + [CommandCacheKey.ResolveLanguages]: isResolveLanguagesOutput, }; interface StoredCommandCacheEntry { @@ -174,8 +177,8 @@ export function cacheCommandOutput( * * Resolves tier 1 (in-memory memo) first, then tier 2 (temporary file). A value * loaded from the file is ignored unless its `cmd` matches the optional `cmd` - * argument, and it satisfies the optional `validate` type guard; valid values - * are memoized into tier 1 before being returned. + * argument and its output satisfies the internal validator for `key`; valid + * values are memoized into tier 1 before being returned. * * A return value of `undefined` signals the caller to fall back to tier 3 (the * CLI). diff --git a/src/codeql.ts b/src/codeql.ts index b930782868..129437d65f 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -14,9 +14,9 @@ import { import * as api from "./api-client"; import { cacheCommandOutput, + CommandCacheKey, getCachedCommandOutput, type CommandCacheKeyOutputMap, - type CommandCacheKey, type ResolveLanguagesOutput, type VersionInfo, } from "./cli/output-cache"; @@ -515,7 +515,7 @@ async function getCodeQLForCmd( return cmd; }, async getVersion() { - return getCachedOrRun("version", cmd, () => + return getCachedOrRun(CommandCacheKey.Version, cmd, () => runCliJson(cmd, ["version", "--format=json"], { noStreamStdout: true, }), @@ -718,7 +718,7 @@ async function getCodeQLForCmd( await runCli(cmd, args); }, async resolveLanguages() { - return getCachedOrRun("resolve languages", cmd, async () => { + return getCachedOrRun(CommandCacheKey.ResolveLanguages, cmd, async () => { const isFilterToLanguagesWithQueriesSupported = await this.supportsFeature( ToolsFeature.BuiltinExtractorsSpecifyDefaultQueries, diff --git a/src/status-report.ts b/src/status-report.ts index 7cf152ce1f..8e401ffffd 100644 --- a/src/status-report.ts +++ b/src/status-report.ts @@ -12,7 +12,7 @@ import { isSelfHostedRunner, } from "./actions-util"; import { getAnalysisKey, getApiClient } from "./api-client"; -import { getCachedCommandOutput } from "./cli/output-cache"; +import { CommandCacheKey, getCachedCommandOutput } from "./cli/output-cache"; import { parseRegistriesWithoutCredentials, type Config } from "./config-utils"; import { DependencyCacheRestoreStatusReport } from "./dependency-caching"; import { DocUrl } from "./doc-url"; @@ -283,7 +283,10 @@ export async function createStatusReportBase( core.exportVariable(EnvVar.WORKFLOW_STARTED_AT, workflowStartedAt); } const runnerOs = getRequiredEnvParam("RUNNER_OS"); - const codeQlCliVersion = getCachedCommandOutput("version", undefined); + const codeQlCliVersion = getCachedCommandOutput( + CommandCacheKey.Version, + undefined, + ); const actionRef = process.env["GITHUB_ACTION_REF"] || ""; const testingEnvironment = getTestingEnvironment(); // re-export the testing environment variable so that it is available to subsequent steps, From bba0d6c67cb441000dde909b0cc8ad52e67561d5 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Tue, 30 Jun 2026 22:25:11 -0500 Subject: [PATCH 25/26] Revert JSON module changes These have been spun off into #3980. --- src/json/index.test.ts | 31 ++++--------------------------- src/json/index.ts | 37 ++----------------------------------- src/start-proxy/types.ts | 16 ++++++++-------- 3 files changed, 14 insertions(+), 70 deletions(-) diff --git a/src/json/index.test.ts b/src/json/index.test.ts index 3e96d7639c..825bbc0e70 100644 --- a/src/json/index.test.ts +++ b/src/json/index.test.ts @@ -10,8 +10,8 @@ const testSchema = { requiredKey: json.string, }; -const optionalOrNullSchema = { - optionalKey: json.optionalOrNull(json.string), +const optionalSchema = { + optionalKey: json.optional(json.string), }; test("validateSchema - required properties are required", async (t) => { @@ -30,34 +30,11 @@ test("validateSchema - required properties are required", async (t) => { test("validateSchema - optional properties are optional", async (t) => { // Optional fields may be absent - t.true(json.validateSchema(optionalOrNullSchema, {})); - t.true(json.validateSchema(optionalOrNullSchema, { optionalKey: undefined })); - t.true(json.validateSchema(optionalOrNullSchema, { optionalKey: null })); - - // But, if present, should have the expected type - t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: 0 })); - t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: 123 })); - t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: false })); - t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: true })); - t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: [] })); - t.false(json.validateSchema(optionalOrNullSchema, { optionalKey: {} })); - t.true(json.validateSchema(optionalOrNullSchema, { optionalKey: "" })); - t.true(json.validateSchema(optionalOrNullSchema, { optionalKey: "foo" })); -}); - -const optionalSchema = { - optionalKey: json.optional(json.string), -}; - -test("validateSchema - optional properties may be absent or undefined, but reject null", async (t) => { - // Optional fields may be absent or explicitly undefined t.true(json.validateSchema(optionalSchema, {})); t.true(json.validateSchema(optionalSchema, { optionalKey: undefined })); + t.true(json.validateSchema(optionalSchema, { optionalKey: null })); - // But should reject null - t.false(json.validateSchema(optionalSchema, { optionalKey: null })); - - // And, if present, should have the expected type + // But, if present, should have the expected type t.false(json.validateSchema(optionalSchema, { optionalKey: 0 })); t.false(json.validateSchema(optionalSchema, { optionalKey: 123 })); t.false(json.validateSchema(optionalSchema, { optionalKey: false })); diff --git a/src/json/index.ts b/src/json/index.ts index 66adc606bd..8a1b60a178 100644 --- a/src/json/index.ts +++ b/src/json/index.ts @@ -30,11 +30,6 @@ export function isString(value: unknown): value is string { return typeof value === "string"; } -/** Asserts that `value` is a number. */ -export function isNumber(value: unknown): value is number { - return typeof value === "number"; -} - /** Asserts that `value` is either a string or undefined. */ export function isStringOrUndefined( value: unknown, @@ -60,23 +55,8 @@ export const string = { required: true, } as const satisfies Validator; -/** A validator for number fields in schemas. */ -export const number = { - validate: isNumber, - required: true, -} as const satisfies Validator; - -/** A validator for object fields in schemas. */ -export const object = { - validate: isObject, - required: true, -} as const satisfies Validator>; - -/** - * Transforms a validator to be optional, accepting `undefined` or `null` for an - * absent value. - */ -export function optionalOrNull(validator: Validator) { +/** Transforms a validator to be optional. */ +export function optional(validator: Validator) { return { validate: (val: unknown) => { return val === undefined || val === null || validator.validate(val); @@ -85,19 +65,6 @@ export function optionalOrNull(validator: Validator) { } as const satisfies Validator; } -/** - * Transforms a validator to be optional, accepting `undefined` for an absent - * value but, unlike `optionalOrNull`, rejecting `null`. - */ -export function optional(validator: Validator) { - return { - validate: (val: unknown): val is T | undefined => { - return val === undefined || validator.validate(val); - }, - required: false, - } as const satisfies Validator; -} - /** Represents an arbitrary object schema. */ export type Schema = Record>; diff --git a/src/start-proxy/types.ts b/src/start-proxy/types.ts index 13369edbfa..13a4ce0e8f 100644 --- a/src/start-proxy/types.ts +++ b/src/start-proxy/types.ts @@ -12,7 +12,7 @@ export type RawCredential = UnvalidatedObject; /** A schema for credential objects with a username. */ export const usernameSchema = { /** The username needed to authenticate to the package registry, if any. */ - username: json.optionalOrNull(json.string), + username: json.optional(json.string), } as const satisfies json.Schema; /** Usernames may be present for both authentication with tokens or passwords. */ @@ -29,7 +29,7 @@ export function hasUsername(config: AuthConfig): config is Username { /** A schema for credential objects with a username and password. */ export const usernamePasswordSchema = { /** The password needed to authenticate to the package registry, if any. */ - password: json.optionalOrNull(json.string), + password: json.optional(json.string), ...usernameSchema, } as const satisfies json.Schema; @@ -52,7 +52,7 @@ export function hasUsernameAndPassword( /** A schema for credential objects for token-based authentication. */ export const tokenSchema = { /** The token needed to authenticate to the package registry, if any. */ - token: json.optionalOrNull(json.string), + token: json.optional(json.string), ...usernameSchema, } as const satisfies json.Schema; @@ -100,7 +100,7 @@ export const awsConfigSchema = { "role-name": json.string, domain: json.string, "domain-owner": json.string, - audience: json.optionalOrNull(json.string), + audience: json.optional(json.string), } as const satisfies json.Schema; /** Configuration for AWS OIDC. */ @@ -116,8 +116,8 @@ export function isAWSConfig( /** A schema for JFrog OIDC configurations. */ export const jfrogConfigSchema = { "jfrog-oidc-provider-name": json.string, - audience: json.optionalOrNull(json.string), - "identity-mapping-name": json.optionalOrNull(json.string), + audience: json.optional(json.string), + "identity-mapping-name": json.optional(json.string), } as const satisfies json.Schema; /** Configuration for JFrog OIDC. */ @@ -150,8 +150,8 @@ export function isCloudsmithConfig( /** A schema for GCP OIDC configurations. */ export const gcpConfigSchema = { "workload-identity-provider": json.string, - "service-account": json.optionalOrNull(json.string), - audience: json.optionalOrNull(json.string), + "service-account": json.optional(json.string), + audience: json.optional(json.string), } as const satisfies json.Schema; /** Configuration for GCP OIDC. */ From 7f4f27e7e62ffbdfee14c96f3c882d09d8a62e64 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 1 Jul 2026 09:41:56 -0500 Subject: [PATCH 26/26] Revert change to `resolveExtractor` This is secondary work that will follow from the main purpose of this PR. --- src/codeql.ts | 37 ++++++++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/src/codeql.ts b/src/codeql.ts index 129437d65f..33838fac71 100644 --- a/src/codeql.ts +++ b/src/codeql.ts @@ -920,17 +920,32 @@ async function getCodeQLForCmd( await new toolrunner.ToolRunner(cmd, args).exec(); }, async resolveExtractor(language: Language): Promise { - // A previous implementation executed `codeql resolve extractor`. - // This can be a bit slow due to the JVM startup cost. Instead, get - // the extractor path from resolveLanguages(), which caches its output. - const output = await this.resolveLanguages(); - const extractors = output.extractors[language]; - if (extractors === undefined) { - throw new Error( - `Unable to resolve an extractor for the language '${language}'.`, - ); - } - return extractors[0].extractor_root; + // Request it using `format=json` so we don't need to strip the trailing new line generated by + // the CLI. + let extractorPath = ""; + await new toolrunner.ToolRunner( + cmd, + [ + "resolve", + "extractor", + "--format=json", + `--language=${language}`, + "--extractor-include-aliases", + ...getExtraOptionsFromEnv(["resolve", "extractor"]), + ], + { + silent: true, + listeners: { + stdout: (data) => { + extractorPath += data.toString(); + }, + stderr: (data) => { + process.stderr.write(data); + }, + }, + }, + ).exec(); + return JSON.parse(extractorPath) as string; }, async resolveQueriesStartingPacks(queries: string[]): Promise { const codeqlArgs = [