From b2b77a81a2aa74eb204b9fdd876808f4c27b6ffd Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 10:47:46 -0500 Subject: [PATCH 01/76] Add CHANGELOG.md modification check and warning comment --- .github/workflows/pr-checks.yml | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 2ae0594407..b0e2aa6b12 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -181,6 +181,31 @@ jobs: path: ${{ runner.temp }}/repo-size/ if-no-files-found: error + - name: Check for CHANGELOG.md changes + id: changelog-check + if: steps.fetch-base.outcome == 'success' + env: + BASE_SHA: ${{ steps.fetch-base.outputs.merge_base }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + if ! git diff --exit-code --quiet "$BASE_SHA" "$HEAD_SHA" -- CHANGELOG.md; then + echo "CHANGELOG.md was modified in this PR." + echo "changed=true" >> "$GITHUB_OUTPUT" + else + echo "changed=false" >> "$GITHUB_OUTPUT" + fi + + - name: Post a warning about modifying CHANGELOG.md + if: steps.changelog-check.outputs.changed == 'true' + uses: peter-evans/create-or-update-comment@e8674b075228eee787fea43ef493e45ece1004c9 # v5.0.0 + with: + issue-number: ${{ github.event.pull_request.number }} + body: >- + ⚠️ CHANGELOG.md was modified in this PR. Please do not modify CHANGELOG.md directly. + Instead, describe your change as a change-note. The CHANGELOG.md file will be automatically + generated from change-notes. For more information, + see [CONTRIBUTING.md](https://github.com/github/codeql-action/blob/main/CONTRIBUTING.md). + - name: "Backport: Check out base ref" id: checkout-base if: ${{ startsWith(github.head_ref, 'backport-') }} From fbd33ac6fcc84bf24f586f0648d71ac1fde05121 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 10:50:34 -0500 Subject: [PATCH 02/76] Gate comment-post step on successful fetch-base --- .github/workflows/pr-checks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index b0e2aa6b12..1f19b62a04 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -196,7 +196,7 @@ jobs: fi - name: Post a warning about modifying CHANGELOG.md - if: steps.changelog-check.outputs.changed == 'true' + if: steps.fetch-base.outcome == 'success' && steps.changelog-check.outputs.changed == 'true' uses: peter-evans/create-or-update-comment@e8674b075228eee787fea43ef493e45ece1004c9 # v5.0.0 with: issue-number: ${{ github.event.pull_request.number }} From 43ac64c2673106d737b19d3e66ba56c4b54a3b9d Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 11:16:19 -0500 Subject: [PATCH 03/76] Use `gh api` instead of third-party Action --- .github/workflows/pr-checks.yml | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 1f19b62a04..911e4583d0 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -197,14 +197,15 @@ jobs: - name: Post a warning about modifying CHANGELOG.md if: steps.fetch-base.outcome == 'success' && steps.changelog-check.outputs.changed == 'true' - uses: peter-evans/create-or-update-comment@e8674b075228eee787fea43ef493e45ece1004c9 # v5.0.0 - with: - issue-number: ${{ github.event.pull_request.number }} - body: >- - ⚠️ CHANGELOG.md was modified in this PR. Please do not modify CHANGELOG.md directly. - Instead, describe your change as a change-note. The CHANGELOG.md file will be automatically - generated from change-notes. For more information, - see [CONTRIBUTING.md](https://github.com/github/codeql-action/blob/main/CONTRIBUTING.md). + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + body="⚠️ CHANGELOG.md was modified in this PR. Please do not modify CHANGELOG.md directly. \ + Instead, describe your change as a change-note. The CHANGELOG.md file will be automatically \ + generated from change-notes. For more information, \ + see [CONTRIBUTING.md](https://github.com/github/codeql-action/blob/main/CONTRIBUTING.md)." + gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --field body="$body" - name: "Backport: Check out base ref" id: checkout-base From f7aa9dc1ba469698a7f5479c75abd35652c913ba Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 11:40:38 -0500 Subject: [PATCH 04/76] Move post-comment step to `post-pr-comments` job --- .github/workflows/pr-checks.yml | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 911e4583d0..37e06d44e6 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -92,6 +92,8 @@ jobs: contents: read runs-on: ubuntu-latest timeout-minutes: 10 + outputs: + changelog-changed: ${{ steps.changelog-check.outputs.changed }} concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} @@ -195,18 +197,6 @@ jobs: echo "changed=false" >> "$GITHUB_OUTPUT" fi - - name: Post a warning about modifying CHANGELOG.md - if: steps.fetch-base.outcome == 'success' && steps.changelog-check.outputs.changed == 'true' - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - PR_NUMBER: ${{ github.event.pull_request.number }} - run: | - body="⚠️ CHANGELOG.md was modified in this PR. Please do not modify CHANGELOG.md directly. \ - Instead, describe your change as a change-note. The CHANGELOG.md file will be automatically \ - generated from change-notes. For more information, \ - see [CONTRIBUTING.md](https://github.com/github/codeql-action/blob/main/CONTRIBUTING.md)." - gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --field body="$body" - - name: "Backport: Check out base ref" id: checkout-base if: ${{ startsWith(github.head_ref, 'backport-') }} @@ -227,8 +217,8 @@ jobs: exit 1 fi - post-repo-size-comment: - name: Post repo size comment + post-pr-comments: + name: Post PR comments needs: other-checks # Keep write permissions isolated from the job that checks out and tests PR code. This job only # posts the candidate comment body produced by the read-only `pr-checks` job. @@ -277,3 +267,15 @@ jobs: else echo "Skipping repo size comment because the delta is below the threshold and no sticky comment exists." fi + + - name: Post a warning about modifying CHANGELOG.md + if: needs.other-checks.outputs.changelog-changed == 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + body="⚠️ CHANGELOG.md was modified in this PR. Please do not modify CHANGELOG.md directly. \ + Instead, describe your change as a change-note. The CHANGELOG.md file will be automatically \ + generated from change-notes. For more information, \ + see [CONTRIBUTING.md](https://github.com/github/codeql-action/blob/main/CONTRIBUTING.md)." + gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --field body="$body" From 780e947861f737e875cddac65cbc9682db4740f9 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 11:48:09 -0500 Subject: [PATCH 05/76] Skip CHANGELOG.md modification warning for release and backport PRs --- .github/workflows/pr-checks.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 37e06d44e6..6dbb457e3f 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -269,7 +269,16 @@ jobs: fi - name: Post a warning about modifying CHANGELOG.md - if: needs.other-checks.outputs.changelog-changed == 'true' + # Release and backport PRs created by `update-release-branch.ts` are titled + # `Merge into `, where the target branch is always a + # `releases/v*` branch. These PRs deliberately modify CHANGELOG.md as part of the release + # process, so skip the warning for them. + if: >- + needs.other-checks.outputs.changelog-changed == 'true' && + !( + startsWith(github.event.pull_request.title, 'Merge ') && + contains(github.event.pull_request.title, ' into releases/v') + ) env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} PR_NUMBER: ${{ github.event.pull_request.number }} From ae75d466cee9de3cf2da4b0c49e9fdff274a62e2 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 12:06:32 -0500 Subject: [PATCH 06/76] Exclude "Mergeback" and "Update default bundle" PRs from CHANGELOG.md change warning --- .github/workflows/pr-checks.yml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 6dbb457e3f..3c03943289 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -269,15 +269,17 @@ jobs: fi - name: Post a warning about modifying CHANGELOG.md - # Release and backport PRs created by `update-release-branch.ts` are titled - # `Merge into `, where the target branch is always a - # `releases/v*` branch. These PRs deliberately modify CHANGELOG.md as part of the release - # process, so skip the warning for them. + # Release, backport, mergeback, and bundle-update PRs deliberately modify CHANGELOG.md, + # so skip the warning for these automation flows. if: >- needs.other-checks.outputs.changelog-changed == 'true' && !( startsWith(github.event.pull_request.title, 'Merge ') && - contains(github.event.pull_request.title, ' into releases/v') + contains(github.event.pull_request.title, ' into releases/v') || + startsWith(github.event.pull_request.title, 'Mergeback ') && + startsWith(github.event.pull_request.head.ref, 'mergeback/') || + startsWith(github.event.pull_request.title, 'Update default bundle to ') && + startsWith(github.event.pull_request.head.ref, 'update-bundle/') ) env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 6e4d3fb63d9c4d75040616dcdf7c77fadc4ef827 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 12:31:10 -0500 Subject: [PATCH 07/76] Use a sticky comment to warn about CHANGELOG.md changes --- .github/workflows/pr-checks.yml | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 3c03943289..9121b16e2e 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -282,11 +282,25 @@ jobs: startsWith(github.event.pull_request.head.ref, 'update-bundle/') ) env: + COMMENT_MARKER: "" GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} PR_NUMBER: ${{ github.event.pull_request.number }} run: | - body="⚠️ CHANGELOG.md was modified in this PR. Please do not modify CHANGELOG.md directly. \ - Instead, describe your change as a change-note. The CHANGELOG.md file will be automatically \ - generated from change-notes. For more information, \ + comment_id=$( + gh api "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" \ + --paginate \ + --jq ".[] | select(.body | contains(\"$COMMENT_MARKER\")) | .id" \ + | head -n 1 + ) + + if [[ -n "$comment_id" ]]; then + echo "CHANGELOG.md warning comment already exists ($comment_id)." + exit 0 + fi + + body="$COMMENT_MARKER + ⚠️ CHANGELOG.md was modified in this PR. Please do not modify CHANGELOG.md directly. + Instead, describe your change as a change-note. The CHANGELOG.md file will be automatically + generated from change-notes. For more information, see [CONTRIBUTING.md](https://github.com/github/codeql-action/blob/main/CONTRIBUTING.md)." gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --field body="$body" From d97a656f70b91aaa5380a8bf2278eed24c0b6b18 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 12:41:52 -0500 Subject: [PATCH 08/76] Update CHANGELOG.md warning message to reference change-notes directory --- .github/workflows/pr-checks.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 9121b16e2e..52cb664845 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -299,8 +299,8 @@ jobs: fi body="$COMMENT_MARKER - ⚠️ CHANGELOG.md was modified in this PR. Please do not modify CHANGELOG.md directly. - Instead, describe your change as a change-note. The CHANGELOG.md file will be automatically - generated from change-notes. For more information, - see [CONTRIBUTING.md](https://github.com/github/codeql-action/blob/main/CONTRIBUTING.md)." + ⚠️ CHANGELOG.md has been modified in this PR. Please do not modify CHANGELOG.md directly. + Instead, create a change-note file in `unreleased-change-notes/`. The CHANGELOG.md + file will be automatically generated from those change-notes. + See [unreleased-change-notes/README.md](unreleased-change-notes/README.md) for more information." gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --field body="$body" From ccdf69089ab5036850dc8544c4801e1c34e48237 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 12:55:10 -0500 Subject: [PATCH 09/76] Escape backticks PR comment body Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 52cb664845..39c319e5d0 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -300,7 +300,7 @@ jobs: body="$COMMENT_MARKER ⚠️ CHANGELOG.md has been modified in this PR. Please do not modify CHANGELOG.md directly. - Instead, create a change-note file in `unreleased-change-notes/`. The CHANGELOG.md + Instead, create a change-note file in \`unreleased-change-notes/\`. The CHANGELOG.md file will be automatically generated from those change-notes. See [unreleased-change-notes/README.md](unreleased-change-notes/README.md) for more information." gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --field body="$body" From 928548a094382019a950465f393317b0b7134ea0 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 12:57:52 -0500 Subject: [PATCH 10/76] Refine exclusion conditions for CHANGELOG-modification comment Refactor conditions for PR title checks in workflow. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 39c319e5d0..db067db460 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -274,8 +274,13 @@ jobs: if: >- needs.other-checks.outputs.changelog-changed == 'true' && !( - startsWith(github.event.pull_request.title, 'Merge ') && - contains(github.event.pull_request.title, ' into releases/v') || + startsWith(github.event.pull_request.title, 'Merge main into releases/v') && + startsWith(github.event.pull_request.head.ref, 'update-v') && + startsWith(github.event.pull_request.base.ref, 'releases/v') || + startsWith(github.event.pull_request.title, 'Merge releases/v') && + contains(github.event.pull_request.title, ' into releases/v') && + startsWith(github.event.pull_request.head.ref, 'backport-v') && + startsWith(github.event.pull_request.base.ref, 'releases/v') || startsWith(github.event.pull_request.title, 'Mergeback ') && startsWith(github.event.pull_request.head.ref, 'mergeback/') || startsWith(github.event.pull_request.title, 'Update default bundle to ') && From 0707124ab8cf9f077c71211fe07ec8161feabf24 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 13:11:34 -0500 Subject: [PATCH 11/76] Delete CHANGELOG.md-modification comment if CHANGELOG.md no longer modified --- .github/workflows/pr-checks.yml | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index db067db460..c5d9d55927 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -270,9 +270,8 @@ jobs: - name: Post a warning about modifying CHANGELOG.md # Release, backport, mergeback, and bundle-update PRs deliberately modify CHANGELOG.md, - # so skip the warning for these automation flows. + # so skip comment management entirely for these automation flows. if: >- - needs.other-checks.outputs.changelog-changed == 'true' && !( startsWith(github.event.pull_request.title, 'Merge main into releases/v') && startsWith(github.event.pull_request.head.ref, 'update-v') && @@ -290,6 +289,7 @@ jobs: COMMENT_MARKER: "" GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} PR_NUMBER: ${{ github.event.pull_request.number }} + CHANGED: ${{ needs.other-checks.outputs.changelog-changed }} run: | comment_id=$( gh api "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" \ @@ -298,6 +298,20 @@ jobs: | head -n 1 ) + # If CHANGELOG.md is no longer modified (e.g. a later commit reverted the change), + # remove any stale warning comment left over from an earlier push instead of leaving it + # to incorrectly claim the file is still modified. + if [[ "$CHANGED" == "false" ]]; then + if [[ -n "$comment_id" ]]; then + echo "CHANGELOG.md is no longer modified; deleting stale warning comment ($comment_id)." + gh api --method DELETE "repos/$GITHUB_REPOSITORY/issues/comments/$comment_id" + else + echo "CHANGELOG.md was not modified and no warning comment exists; nothing to do." + fi + exit 0 + fi + + # If CHANGELOG.md has been modified and a warning comment already exists, do not post a duplicate comment. if [[ -n "$comment_id" ]]; then echo "CHANGELOG.md warning comment already exists ($comment_id)." exit 0 From 27d37d97e2a09dd0a5bdde848365258b3472a1b5 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 15:19:38 -0500 Subject: [PATCH 12/76] Format all file references as inline Markdown code spans Co-authored-by: Michael B. Gale --- .github/workflows/pr-checks.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index c5d9d55927..4ae39623c7 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -318,8 +318,8 @@ jobs: fi body="$COMMENT_MARKER - ⚠️ CHANGELOG.md has been modified in this PR. Please do not modify CHANGELOG.md directly. - Instead, create a change-note file in \`unreleased-change-notes/\`. The CHANGELOG.md + ⚠️ \`CHANGELOG.md\` has been modified in this PR. Please do not modify \`CHANGELOG.md\` directly. + Instead, create a change-note file in \`unreleased-change-notes/\`. The \`CHANGELOG.md\` file will be automatically generated from those change-notes. - See [unreleased-change-notes/README.md](unreleased-change-notes/README.md) for more information." + See [\`unreleased-change-notes/README.md\`](unreleased-change-notes/README.md) for more information." gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --field body="$body" From 9fe741e77d850a82a15baa665d9365395d865677 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 15:26:56 -0500 Subject: [PATCH 13/76] Simplify `if` condition of CHANGELOG-comment-post step --- .github/workflows/pr-checks.yml | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 4ae39623c7..6a21611f49 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -272,19 +272,10 @@ jobs: # Release, backport, mergeback, and bundle-update PRs deliberately modify CHANGELOG.md, # so skip comment management entirely for these automation flows. if: >- - !( - startsWith(github.event.pull_request.title, 'Merge main into releases/v') && - startsWith(github.event.pull_request.head.ref, 'update-v') && - startsWith(github.event.pull_request.base.ref, 'releases/v') || - startsWith(github.event.pull_request.title, 'Merge releases/v') && - contains(github.event.pull_request.title, ' into releases/v') && - startsWith(github.event.pull_request.head.ref, 'backport-v') && - startsWith(github.event.pull_request.base.ref, 'releases/v') || - startsWith(github.event.pull_request.title, 'Mergeback ') && - startsWith(github.event.pull_request.head.ref, 'mergeback/') || - startsWith(github.event.pull_request.title, 'Update default bundle to ') && - startsWith(github.event.pull_request.head.ref, 'update-bundle/') - ) + !startsWith(github.event.pull_request.head.ref, 'update-v') && + !startsWith(github.event.pull_request.head.ref, 'backport-v') && + !startsWith(github.event.pull_request.head.ref, 'mergeback/') && + !startsWith(github.event.pull_request.head.ref, 'update-bundle/') env: COMMENT_MARKER: "" GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 8c8b0827d5a9af4db0ccee26aad2d80104f81d3d Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 23:02:25 -0500 Subject: [PATCH 14/76] Add script and Action for managing PR comments --- .github/actions/post-comment/action.yml | 46 +++++ pr-checks/post-comment.test.ts | 206 +++++++++++++++++++ pr-checks/post-comment.ts | 253 ++++++++++++++++++++++++ 3 files changed, 505 insertions(+) create mode 100644 .github/actions/post-comment/action.yml create mode 100644 pr-checks/post-comment.test.ts create mode 100644 pr-checks/post-comment.ts diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml new file mode 100644 index 0000000000..f2233bc97e --- /dev/null +++ b/.github/actions/post-comment/action.yml @@ -0,0 +1,46 @@ +name: "Post comment" +description: "Create, update, or delete a sticky PR comment identified by an automatically-derived HTML-comment marker. If this action is used more than once within the same job, give each step an explicit 'id:' so the derived marker stays unique." +inputs: + body: + description: "Full comment markdown." + required: true + action-condition: + description: "The business condition ('true' or 'false') that selects which action to perform." + required: true + action-if-true: + description: "Action to perform when action-condition is 'true'. One of: none, insert, upsert, delete." + required: true + action-if-false: + description: "Action to perform when action-condition is 'false'. One of: none, insert, upsert, delete." + required: true + issue-id: + description: "The issue or pull request number to post/update/delete the comment on. Defaults to the current pull request if not provided." + required: false + token: + description: "The GitHub token to authenticate with." + required: true +runs: + using: composite + steps: + - name: Post comment + shell: bash + env: + BODY: ${{ inputs.body }} + # Derived from the workflow name, job id, and step id/sequence-number so that repeated + # runs of the same step find the same comment (for upsert/delete), while distinct steps + # (even within the same job) get distinct markers. + MARKER: + GH_TOKEN: ${{ inputs.token }} + ISSUE_ID: ${{ inputs.issue-id || github.event.pull_request.number }} + ACTION_CONDITION: ${{ inputs.action-condition }} + ACTION_IF_TRUE: ${{ inputs.action-if-true }} + ACTION_IF_FALSE: ${{ inputs.action-if-false }} + run: | + npx tsx ./pr-checks/post-comment.ts \ + --body "$BODY" \ + --marker "$MARKER" \ + --action-condition "$ACTION_CONDITION" \ + --action-if-true "$ACTION_IF_TRUE" \ + --action-if-false "$ACTION_IF_FALSE" \ + --issue-id "$ISSUE_ID" \ + --repository "$GITHUB_REPOSITORY" diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts new file mode 100644 index 0000000000..c6eb76057e --- /dev/null +++ b/pr-checks/post-comment.test.ts @@ -0,0 +1,206 @@ +#!/usr/bin/env npx tsx + +/* +Tests for post-comment.ts. +*/ + +import * as assert from "node:assert/strict"; +import { describe, it } from "node:test"; + +import { type ApiClient } from "./api-client"; +import { + findExistingComment, + parseOptions, + resolveToken, +} from "./post-comment"; + +/** A baseline set of valid CLI flags, as an array, for use in parseOptions tests. */ +const validFlags = [ + "--body", + "hello", + "--marker", + "", + "--action-condition", + "true", + "--action-if-true", + "insert", + "--action-if-false", + "delete", + "--issue-id", + "42", + "--repository", + "github/codeql-action", +]; + +/** Returns a copy of `validFlags` with the value following `flag` replaced by `value`. */ +function withFlag(flag: string, value: string): string[] { + const flags = [...validFlags]; + const index = flags.indexOf(flag); + flags[index + 1] = value; + return flags; +} + +/** Returns a copy of `validFlags` with `flag` (and its value) removed entirely. */ +function withoutFlag(flag: string): string[] { + const flags = [...validFlags]; + const index = flags.indexOf(flag); + flags.splice(index, 2); + return flags; +} + +describe("parseOptions", async () => { + await it("parses valid flags", () => { + const options = parseOptions(validFlags); + assert.deepEqual(options, { + body: "hello", + marker: "", + actionCondition: true, + actionIfTrue: "insert", + actionIfFalse: "delete", + issueId: 42, + repository: { owner: "github", repo: "codeql-action" }, + }); + }); + + await it("parses action-condition=false", () => { + const options = parseOptions(withFlag("--action-condition", "false")); + assert.equal(options.actionCondition, false); + }); + + await it("rejects a missing --body", () => { + assert.throws( + () => parseOptions(withoutFlag("--body")), + /Missing required flag --body/, + ); + }); + + await it("rejects a missing --marker", () => { + assert.throws( + () => parseOptions(withoutFlag("--marker")), + /Missing required flag --marker/, + ); + }); + + await it("rejects an invalid --action-condition value", () => { + assert.throws( + () => parseOptions(withFlag("--action-condition", "yes")), + /Invalid value 'yes' for --action-condition/, + ); + }); + + await it("rejects an invalid --action-if-true value", () => { + assert.throws( + () => parseOptions(withFlag("--action-if-true", "bogus")), + /Invalid value 'bogus' for --action-if-true/, + ); + }); + + await it("rejects an invalid --action-if-false value", () => { + assert.throws( + () => parseOptions(withFlag("--action-if-false", "bogus")), + /Invalid value 'bogus' for --action-if-false/, + ); + }); + + await it("rejects a missing --issue-id", () => { + assert.throws( + () => parseOptions(withoutFlag("--issue-id")), + /Missing required flag --issue-id/, + ); + }); + + await it("rejects a non-numeric --issue-id", () => { + assert.throws( + () => parseOptions(withFlag("--issue-id", "not-a-number")), + /Invalid value 'not-a-number' for --issue-id/, + ); + }); + + await it("rejects a missing --repository", () => { + assert.throws( + () => parseOptions(withoutFlag("--repository")), + /Missing required flag --repository/, + ); + }); + + await it("rejects a --repository that isn't in the form 'owner/repo'", () => { + assert.throws( + () => parseOptions(withFlag("--repository", "not-a-slug")), + /Invalid value 'not-a-slug' for --repository/, + ); + }); +}); + +describe("resolveToken", async () => { + await it("reads the token from GH_TOKEN", () => { + assert.equal( + resolveToken({ GH_TOKEN: "gh-token", GITHUB_TOKEN: "gha-token" }), + "gh-token", + ); + }); + + await it("falls back to GITHUB_TOKEN", () => { + assert.equal(resolveToken({ GITHUB_TOKEN: "gha-token" }), "gha-token"); + }); + + await it("throws when no token is set", () => { + assert.throws(() => resolveToken({}), /Missing authentication token/); + }); +}); + +/** A minimal fake of the subset of `ApiClient` used by post-comment.ts. */ +function fakeClient(existingComments: Array<{ id: number; body?: string }>) { + const calls: { + createComment: unknown[]; + updateComment: unknown[]; + deleteComment: unknown[]; + } = { createComment: [], updateComment: [], deleteComment: [] }; + + const client = { + paginate: async () => existingComments, + rest: { + issues: { + listComments: () => {}, + createComment: async (params: unknown) => { + calls.createComment.push(params); + }, + updateComment: async (params: unknown) => { + calls.updateComment.push(params); + }, + deleteComment: async (params: unknown) => { + calls.deleteComment.push(params); + }, + }, + }, + }; + + return { client: client as unknown as ApiClient, calls }; +} + +describe("findExistingComment", async () => { + await it("finds the id of the first comment containing the marker", async () => { + const { client } = fakeClient([ + { id: 1, body: "unrelated" }, + { id: 2, body: "\nhello" }, + { id: 3, body: "\nanother" }, + ]); + const id = await findExistingComment( + client, + { owner: "owner", repo: "repo" }, + 1, + "", + ); + assert.equal(id, 2); + }); + + await it("returns undefined when no comment matches", async () => { + const { client } = fakeClient([{ id: 1, body: "unrelated" }]); + const id = await findExistingComment( + client, + { owner: "owner", repo: "repo" }, + 1, + "", + ); + assert.equal(id, undefined); + }); +}); diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts new file mode 100644 index 0000000000..f55da65d2b --- /dev/null +++ b/pr-checks/post-comment.ts @@ -0,0 +1,253 @@ +#!/usr/bin/env npx tsx + +/* +Generic CLI for creating, updating, or deleting a "sticky" PR comment identified by a hidden +HTML-comment marker. This centralizes the gh api logic previously duplicated across PR-check +workflow steps that each managed their own marked comment (e.g. a CHANGELOG.md modification +warning). + +The marker is passed explicitly via `--marker` and can be any non-empty string, though an +HTML comment (e.g. ``) is recommended so it doesn't render visibly. It is used +both to find a pre-existing comment on the pull request so that +`upsert`/`delete` actions know which comment to operate on, and is automatically prepended to +`--body` when posting or updating a comment so that future invocations can find it again. Callers +typically derive this value automatically (see `.github/actions/post-comment`) rather than +hand-authoring it. +*/ + +import { parseArgs } from "node:util"; + +import { type ApiClient, getApiClient } from "./api-client"; + +/** The set of valid actions that can be performed against a (possibly pre-existing) marked comment. */ +export const ACTIONS = ["none", "insert", "upsert", "delete"] as const; +/** An action to perform against a (possibly pre-existing) marked comment. */ +export type Action = (typeof ACTIONS)[number]; + +/** Represents the command-line options. */ +export interface Options { + /** The full comment body. */ + body: string; + /** The hidden HTML-comment marker used to find a pre-existing comment. */ + marker: string; + /** The condition that selects which action to perform. */ + actionCondition: boolean; + /** The action to perform when `actionCondition` is `true`. */ + actionIfTrue: Action; + /** The action to perform when `actionCondition` is `false`. */ + actionIfFalse: Action; + /** The issue/pull request number to post/update/delete the comment on. */ + issueId: number; + /** The repository to operate on. */ + repository: { owner: string; repo: string }; +} + +/** + * Validates and parses a required CLI flag's raw string `value`, delegating the actual + * value-specific validation/conversion to `parse`. + */ +function parseFlag( + flag: string, + value: string | undefined, + parse: (value: string) => T, +): T { + if (value === undefined) { + throw new Error(`Missing required flag --${flag}.`); + } + try { + return parse(value); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + throw new Error(`Invalid value '${value}' for --${flag}. ${reason}`); + } +} + +/** Parses and validates `value` as an `Action`. */ +function parseAction(flag: string, value: string | undefined): Action { + return parseFlag(flag, value, (raw) => { + if (!(ACTIONS as readonly string[]).includes(raw)) { + throw new Error(`Must be one of: ${ACTIONS.join(", ")}.`); + } + return raw as Action; + }); +} + +/** Parses and validates `value` as a boolean. */ +function parseBoolean(flag: string, value: string | undefined): boolean { + return parseFlag(flag, value, (raw) => { + if (raw !== "true" && raw !== "false") { + throw new Error("Must be 'true' or 'false'."); + } + return raw === "true"; + }); +} + +/** Parses and validates `value` as an issue/pull request number. */ +function parseIssueId(value: string | undefined): number { + return parseFlag("issue-id", value, (raw) => { + const parsed = Number.parseInt(raw, 10); + if (Number.isNaN(parsed)) { + throw new Error("Must be an integer."); + } + return parsed; + }); +} + +/** Parses and validates `value` as an `owner/repo` repository reference. */ +function parseRepository(value: string | undefined): { + owner: string; + repo: string; +} { + return parseFlag("repository", value, (raw) => { + const [owner, repo, ...rest] = raw.split("/"); + if (!owner || !repo || rest.length > 0) { + throw new Error("Must be in the form 'owner/repo'."); + } + return { owner, repo }; + }); +} + +/** Parses the command-line arguments into `Options`. */ +export function parseOptions(argv?: string[]): Options { + const { values } = parseArgs({ + args: argv, + options: { + body: { type: "string" }, + marker: { type: "string" }, + "action-condition": { type: "string" }, + "action-if-true": { type: "string" }, + "action-if-false": { type: "string" }, + "issue-id": { type: "string" }, + repository: { type: "string" }, + }, + strict: true, + }); + + if (values.body === undefined) { + throw new Error("Missing required flag --body."); + } + if (values.marker === undefined) { + throw new Error("Missing required flag --marker."); + } + + return { + body: values.body, + marker: values.marker, + actionCondition: parseBoolean( + "action-condition", + values["action-condition"], + ), + actionIfTrue: parseAction("action-if-true", values["action-if-true"]), + actionIfFalse: parseAction("action-if-false", values["action-if-false"]), + issueId: parseIssueId(values["issue-id"]), + repository: parseRepository(values.repository), + }; +} + +/** Resolves the GitHub API token to use, from `GH_TOKEN` or `GITHUB_TOKEN`. */ +export function resolveToken(env: NodeJS.ProcessEnv): string { + const token = env.GH_TOKEN?.trim() || env.GITHUB_TOKEN?.trim(); + if (!token) { + throw new Error( + "Missing authentication token. Set GH_TOKEN or GITHUB_TOKEN.", + ); + } + return token; +} + +/** + * Finds the first comment on the given issue/pull request whose body starts with `marker`, if any. + */ +export async function findExistingComment( + client: ApiClient, + repository: { owner: string; repo: string }, + issueNumber: number, + marker: string, +): Promise { + const comments = await client.paginate(client.rest.issues.listComments, { + ...repository, + issue_number: issueNumber, + per_page: 100, + }); + return comments.find((comment) => comment.body?.startsWith(marker))?.id; +} + +async function main(): Promise { + const options = parseOptions(); + const action = options.actionCondition + ? options.actionIfTrue + : options.actionIfFalse; + console.info(`Resolved action: ${action}`); + + const token = resolveToken(process.env); + const { issueId, marker, repository } = options; + const client = getApiClient(token); + const body = `${marker}\n${options.body}`; + + let existingCommentId: number | undefined; + if (action === "upsert" || action === "delete") { + existingCommentId = await findExistingComment( + client, + repository, + issueId, + marker, + ); + } + + switch (action) { + case "none": + console.info("No action needed."); + break; + case "insert": + console.info("Creating a new comment."); + await client.rest.issues.createComment({ + ...repository, + issue_number: issueId, + body, + }); + break; + case "upsert": + if (existingCommentId === undefined) { + console.info("No existing comment found; creating a new comment."); + await client.rest.issues.createComment({ + ...repository, + issue_number: issueId, + body, + }); + } else { + console.info(`Updating existing comment ${existingCommentId}.`); + await client.rest.issues.updateComment({ + ...repository, + comment_id: existingCommentId, + body, + }); + } + break; + case "delete": + if (existingCommentId === undefined) { + console.info("No existing comment found to delete; skipping."); + } else { + console.info(`Deleting existing comment ${existingCommentId}.`); + await client.rest.issues.deleteComment({ + ...repository, + comment_id: existingCommentId, + }); + } + break; + } + + return 0; +} + +async function run(): Promise { + try { + process.exit(await main()); + } catch (err) { + console.error(err instanceof Error ? err.message : String(err)); + process.exit(1); + } +} + +if (import.meta.main) { + void run(); +} From 14cefaa03ce3f948a8c839aa160cd1f52100a34c Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 8 Oct 2026 23:03:55 -0500 Subject: [PATCH 15/76] Replace bash/run step with local Action `post-comment` --- .github/workflows/pr-checks.yml | 69 +++++++++++++++------------------ 1 file changed, 31 insertions(+), 38 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 6a21611f49..8ebbcd0ba9 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -238,6 +238,25 @@ jobs: group: check-repo-size-${{ github.event.pull_request.number }} steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # Check out the base ref, not the PR's head, since this job runs with + # `pull-requests: write` permissions and must not execute untrusted code from the PR. + ref: ${{ github.event.pull_request.base.sha }} + sparse-checkout: | + pr-checks + .github/actions/post-comment + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + cache: "npm" + + - name: Install dependencies + run: npm ci --workspace=pr-checks + - name: Download repo size comment uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -269,6 +288,7 @@ jobs: fi - name: Post a warning about modifying CHANGELOG.md + id: post-changelog-warning # Release, backport, mergeback, and bundle-update PRs deliberately modify CHANGELOG.md, # so skip comment management entirely for these automation flows. if: >- @@ -276,41 +296,14 @@ jobs: !startsWith(github.event.pull_request.head.ref, 'backport-v') && !startsWith(github.event.pull_request.head.ref, 'mergeback/') && !startsWith(github.event.pull_request.head.ref, 'update-bundle/') - env: - COMMENT_MARKER: "" - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - PR_NUMBER: ${{ github.event.pull_request.number }} - CHANGED: ${{ needs.other-checks.outputs.changelog-changed }} - run: | - comment_id=$( - gh api "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" \ - --paginate \ - --jq ".[] | select(.body | contains(\"$COMMENT_MARKER\")) | .id" \ - | head -n 1 - ) - - # If CHANGELOG.md is no longer modified (e.g. a later commit reverted the change), - # remove any stale warning comment left over from an earlier push instead of leaving it - # to incorrectly claim the file is still modified. - if [[ "$CHANGED" == "false" ]]; then - if [[ -n "$comment_id" ]]; then - echo "CHANGELOG.md is no longer modified; deleting stale warning comment ($comment_id)." - gh api --method DELETE "repos/$GITHUB_REPOSITORY/issues/comments/$comment_id" - else - echo "CHANGELOG.md was not modified and no warning comment exists; nothing to do." - fi - exit 0 - fi - - # If CHANGELOG.md has been modified and a warning comment already exists, do not post a duplicate comment. - if [[ -n "$comment_id" ]]; then - echo "CHANGELOG.md warning comment already exists ($comment_id)." - exit 0 - fi - - body="$COMMENT_MARKER - ⚠️ \`CHANGELOG.md\` has been modified in this PR. Please do not modify \`CHANGELOG.md\` directly. - Instead, create a change-note file in \`unreleased-change-notes/\`. The \`CHANGELOG.md\` - file will be automatically generated from those change-notes. - See [\`unreleased-change-notes/README.md\`](unreleased-change-notes/README.md) for more information." - gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --field body="$body" + uses: ./.github/actions/post-comment + with: + body: | + ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. + Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` + file will be automatically generated from those change-notes. + See [`unreleased-change-notes/README.md`](unreleased-change-notes/README.md) for more information. + action-condition: ${{ needs.other-checks.outputs.changelog-changed }} + action-if-true: upsert + action-if-false: delete + token: ${{ secrets.GITHUB_TOKEN }} From 4d464b069771bb6541931592879afc5c59cd9823 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 9 Oct 2026 10:35:34 -0500 Subject: [PATCH 16/76] Improve issue ID parsing and validation logic Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- pr-checks/post-comment.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index f55da65d2b..28e0657863 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -85,9 +85,9 @@ function parseBoolean(flag: string, value: string | undefined): boolean { /** Parses and validates `value` as an issue/pull request number. */ function parseIssueId(value: string | undefined): number { return parseFlag("issue-id", value, (raw) => { - const parsed = Number.parseInt(raw, 10); - if (Number.isNaN(parsed)) { - throw new Error("Must be an integer."); + const parsed = Number(raw); + if (!Number.isInteger(parsed) || parsed <= 0) { + throw new Error("Must be a positive integer."); } return parsed; }); From 3c452a182da69a19b99b58783430dfe368591568 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 9 Oct 2026 10:36:48 -0500 Subject: [PATCH 17/76] Use HTTP link to `unreleased-change-notes/README.md` Update link in PR checks workflow to point to the correct README. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 8ebbcd0ba9..1fbab56124 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -302,7 +302,7 @@ jobs: ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` file will be automatically generated from those change-notes. - See [`unreleased-change-notes/README.md`](unreleased-change-notes/README.md) for more information. + See [`unreleased-change-notes/README.md`](https://github.com/github/codeql-action/blob/main/unreleased-change-notes/README.md) for more information. action-condition: ${{ needs.other-checks.outputs.changelog-changed }} action-if-true: upsert action-if-false: delete From f1419b8c766d21454b9ac9283a268e3dab6afdac Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 9 Oct 2026 17:11:18 -0500 Subject: [PATCH 18/76] Reject empty `--marker` --- pr-checks/post-comment.test.ts | 7 +++++++ pr-checks/post-comment.ts | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index c6eb76057e..492c45f341 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -81,6 +81,13 @@ describe("parseOptions", async () => { ); }); + await it("rejects an empty --marker", () => { + assert.throws( + () => parseOptions(withFlag("--marker", "")), + /Missing required flag --marker/, + ); + }); + await it("rejects an invalid --action-condition value", () => { assert.throws( () => parseOptions(withFlag("--action-condition", "yes")), diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 28e0657863..01b36cac7f 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -126,7 +126,7 @@ export function parseOptions(argv?: string[]): Options { if (values.body === undefined) { throw new Error("Missing required flag --body."); } - if (values.marker === undefined) { + if (values.marker === undefined || values.marker.trim() === "") { throw new Error("Missing required flag --marker."); } From e7dadca872e576f50526a5e4fb5583ffba2add03 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 9 Oct 2026 17:35:09 -0500 Subject: [PATCH 19/76] Refactor comment handling logic into `performAction` for improved testability --- pr-checks/post-comment.test.ts | 86 ++++++++++++++++++++++++++++++++++ pr-checks/post-comment.ts | 32 +++++++++---- 2 files changed, 109 insertions(+), 9 deletions(-) diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index 492c45f341..db6d455393 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -10,7 +10,9 @@ import { describe, it } from "node:test"; import { type ApiClient } from "./api-client"; import { findExistingComment, + type Options, parseOptions, + performAction, resolveToken, } from "./post-comment"; @@ -211,3 +213,87 @@ describe("findExistingComment", async () => { assert.equal(id, undefined); }); }); + +/** A baseline set of `Options`, for use in `performAction` tests. */ +const baseOptions: Options = { + body: "hello", + marker: "", + actionCondition: true, + actionIfTrue: "insert", + actionIfFalse: "delete", + issueId: 42, + repository: { owner: "owner", repo: "repo" }, +}; + +describe("performAction", async () => { + await it("does nothing for 'none'", async () => { + const { client, calls } = fakeClient([]); + await performAction(client, "none", baseOptions); + assert.deepEqual(calls, { + createComment: [], + updateComment: [], + deleteComment: [], + }); + }); + + await it("creates a new comment for 'insert', with the marker prepended", async () => { + const { client, calls } = fakeClient([]); + await performAction(client, "insert", baseOptions); + assert.deepEqual(calls.createComment, [ + { + owner: "owner", + repo: "repo", + issue_number: 42, + body: "\nhello", + }, + ]); + assert.deepEqual(calls.updateComment, []); + assert.deepEqual(calls.deleteComment, []); + }); + + await it("creates a new comment for 'upsert' when no existing comment is found", async () => { + const { client, calls } = fakeClient([{ id: 1, body: "unrelated" }]); + await performAction(client, "upsert", baseOptions); + assert.deepEqual(calls.createComment, [ + { + owner: "owner", + repo: "repo", + issue_number: 42, + body: "\nhello", + }, + ]); + assert.deepEqual(calls.updateComment, []); + }); + + await it("updates the existing comment for 'upsert' when one is found", async () => { + const { client, calls } = fakeClient([ + { id: 7, body: "\nold" }, + ]); + await performAction(client, "upsert", baseOptions); + assert.deepEqual(calls.updateComment, [ + { + owner: "owner", + repo: "repo", + comment_id: 7, + body: "\nhello", + }, + ]); + assert.deepEqual(calls.createComment, []); + }); + + await it("does nothing for 'delete' when no existing comment is found", async () => { + const { client, calls } = fakeClient([{ id: 1, body: "unrelated" }]); + await performAction(client, "delete", baseOptions); + assert.deepEqual(calls.deleteComment, []); + }); + + await it("deletes the existing comment for 'delete' when one is found", async () => { + const { client, calls } = fakeClient([ + { id: 9, body: "\nold" }, + ]); + await performAction(client, "delete", baseOptions); + assert.deepEqual(calls.deleteComment, [ + { owner: "owner", repo: "repo", comment_id: 9 }, + ]); + }); +}); diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 01b36cac7f..6c1a1e5e54 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -172,16 +172,17 @@ export async function findExistingComment( return comments.find((comment) => comment.body?.startsWith(marker))?.id; } -async function main(): Promise { - const options = parseOptions(); - const action = options.actionCondition - ? options.actionIfTrue - : options.actionIfFalse; - console.info(`Resolved action: ${action}`); - - const token = resolveToken(process.env); +/** + * Performs the resolved `action` against a (possibly pre-existing) marked comment, using + * `client` to talk to the GitHub API. This is the core dispatch logic of this script, extracted + * from `main` so it can be unit-tested with an injected (fake) `client`. + */ +export async function performAction( + client: ApiClient, + action: Action, + options: Options, +): Promise { const { issueId, marker, repository } = options; - const client = getApiClient(token); const body = `${marker}\n${options.body}`; let existingCommentId: number | undefined; @@ -235,6 +236,19 @@ async function main(): Promise { } break; } +} + +async function main(): Promise { + const options = parseOptions(); + const action = options.actionCondition + ? options.actionIfTrue + : options.actionIfFalse; + console.info(`Resolved action: ${action}`); + + const token = resolveToken(process.env); + const client = getApiClient(token); + + await performAction(client, action, options); return 0; } From ae9f97bade2e212818622329754bfded9f7073b5 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 28 Oct 2026 15:30:49 -0500 Subject: [PATCH 20/76] Make post-comment marker configurable Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/post-comment/action.yml | 10 ++++---- .github/workflows/pr-checks.yml | 1 + pr-checks/post-comment.test.ts | 34 +++++++++++++++++++++++++ pr-checks/post-comment.ts | 6 ++--- 4 files changed, 43 insertions(+), 8 deletions(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index f2233bc97e..8b3d56ee95 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -1,6 +1,9 @@ name: "Post comment" -description: "Create, update, or delete a sticky PR comment identified by an automatically-derived HTML-comment marker. If this action is used more than once within the same job, give each step an explicit 'id:' so the derived marker stays unique." +description: "Create, update, or delete a sticky PR comment identified by a caller-provided marker." inputs: + marker: + description: "Non-empty marker identifying the comment. Use a unique, stable HTML comment for each distinct comment." + required: true body: description: "Full comment markdown." required: true @@ -26,10 +29,7 @@ runs: shell: bash env: BODY: ${{ inputs.body }} - # Derived from the workflow name, job id, and step id/sequence-number so that repeated - # runs of the same step find the same comment (for upsert/delete), while distinct steps - # (even within the same job) get distinct markers. - MARKER: + MARKER: ${{ inputs.marker }} GH_TOKEN: ${{ inputs.token }} ISSUE_ID: ${{ inputs.issue-id || github.event.pull_request.number }} ACTION_CONDITION: ${{ inputs.action-condition }} diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 1fbab56124..d8450dc4b7 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -298,6 +298,7 @@ jobs: !startsWith(github.event.pull_request.head.ref, 'update-bundle/') uses: ./.github/actions/post-comment with: + marker: "" body: | ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index db6d455393..ca7f7f1dda 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -90,6 +90,13 @@ describe("parseOptions", async () => { ); }); + await it("rejects a whitespace-only --marker", () => { + assert.throws( + () => parseOptions(withFlag("--marker", " \t\n")), + /Missing required flag --marker/, + ); + }); + await it("rejects an invalid --action-condition value", () => { assert.throws( () => parseOptions(withFlag("--action-condition", "yes")), @@ -226,6 +233,33 @@ const baseOptions: Options = { }; describe("performAction", async () => { + for (const action of ["upsert", "delete"] as const) { + await it(`uses the supplied marker for '${action}' without affecting other comments`, async () => { + const marker = ""; + const { client, calls } = fakeClient([ + { id: 1, body: "\nunrelated warning" }, + { id: 2, body: `${marker}\nold warning` }, + ]); + const options = parseOptions(withFlag("--marker", marker)); + await performAction(client, action, options); + assert.deepEqual(calls, { + createComment: [], + updateComment: + action === "upsert" + ? [ + { + ...options.repository, + comment_id: 2, + body: `${marker}\nhello`, + }, + ] + : [], + deleteComment: + action === "delete" ? [{ ...options.repository, comment_id: 2 }] : [], + }); + }); + } + await it("does nothing for 'none'", async () => { const { client, calls } = fakeClient([]); await performAction(client, "none", baseOptions); diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 6c1a1e5e54..13e6f22386 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -10,9 +10,9 @@ The marker is passed explicitly via `--marker` and can be any non-empty string, HTML comment (e.g. ``) is recommended so it doesn't render visibly. It is used both to find a pre-existing comment on the pull request so that `upsert`/`delete` actions know which comment to operate on, and is automatically prepended to -`--body` when posting or updating a comment so that future invocations can find it again. Callers -typically derive this value automatically (see `.github/actions/post-comment`) rather than -hand-authoring it. +`--body` when posting or updating a comment so that future invocations can find it again. +The `.github/actions/post-comment` action requires callers to supply this value via its +`marker` input. */ import { parseArgs } from "node:util"; From 90d1bc983c4d24649d061979e129bdc9069b2293 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 28 Oct 2026 15:39:43 -0500 Subject: [PATCH 21/76] Remove bespoke post-comment argument validation Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- pr-checks/post-comment.test.ts | 60 +++------------------- pr-checks/post-comment.ts | 93 ++++------------------------------ 2 files changed, 19 insertions(+), 134 deletions(-) diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index ca7f7f1dda..6e7179bf65 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -69,13 +69,6 @@ describe("parseOptions", async () => { assert.equal(options.actionCondition, false); }); - await it("rejects a missing --body", () => { - assert.throws( - () => parseOptions(withoutFlag("--body")), - /Missing required flag --body/, - ); - }); - await it("rejects a missing --marker", () => { assert.throws( () => parseOptions(withoutFlag("--marker")), @@ -97,53 +90,16 @@ describe("parseOptions", async () => { ); }); - await it("rejects an invalid --action-condition value", () => { - assert.throws( - () => parseOptions(withFlag("--action-condition", "yes")), - /Invalid value 'yes' for --action-condition/, - ); - }); - - await it("rejects an invalid --action-if-true value", () => { - assert.throws( - () => parseOptions(withFlag("--action-if-true", "bogus")), - /Invalid value 'bogus' for --action-if-true/, - ); - }); - - await it("rejects an invalid --action-if-false value", () => { - assert.throws( - () => parseOptions(withFlag("--action-if-false", "bogus")), - /Invalid value 'bogus' for --action-if-false/, - ); - }); - - await it("rejects a missing --issue-id", () => { - assert.throws( - () => parseOptions(withoutFlag("--issue-id")), - /Missing required flag --issue-id/, - ); - }); - - await it("rejects a non-numeric --issue-id", () => { - assert.throws( - () => parseOptions(withFlag("--issue-id", "not-a-number")), - /Invalid value 'not-a-number' for --issue-id/, - ); - }); - - await it("rejects a missing --repository", () => { - assert.throws( - () => parseOptions(withoutFlag("--repository")), - /Missing required flag --repository/, - ); + await it("rejects unknown flags using parseArgs", () => { + assert.throws(() => parseOptions([...validFlags, "--unknown", "value"]), { + code: "ERR_PARSE_ARGS_UNKNOWN_OPTION", + }); }); - await it("rejects a --repository that isn't in the form 'owner/repo'", () => { - assert.throws( - () => parseOptions(withFlag("--repository", "not-a-slug")), - /Invalid value 'not-a-slug' for --repository/, - ); + await it("rejects flags without a value using parseArgs", () => { + assert.throws(() => parseOptions([...validFlags, "--body"]), { + code: "ERR_PARSE_ARGS_INVALID_OPTION_VALUE", + }); }); }); diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 13e6f22386..1c61c02216 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -15,6 +15,7 @@ The `.github/actions/post-comment` action requires callers to supply this value `marker` input. */ +import assert from "node:assert/strict"; import { parseArgs } from "node:util"; import { type ApiClient, getApiClient } from "./api-client"; @@ -42,72 +43,7 @@ export interface Options { repository: { owner: string; repo: string }; } -/** - * Validates and parses a required CLI flag's raw string `value`, delegating the actual - * value-specific validation/conversion to `parse`. - */ -function parseFlag( - flag: string, - value: string | undefined, - parse: (value: string) => T, -): T { - if (value === undefined) { - throw new Error(`Missing required flag --${flag}.`); - } - try { - return parse(value); - } catch (err) { - const reason = err instanceof Error ? err.message : String(err); - throw new Error(`Invalid value '${value}' for --${flag}. ${reason}`); - } -} - -/** Parses and validates `value` as an `Action`. */ -function parseAction(flag: string, value: string | undefined): Action { - return parseFlag(flag, value, (raw) => { - if (!(ACTIONS as readonly string[]).includes(raw)) { - throw new Error(`Must be one of: ${ACTIONS.join(", ")}.`); - } - return raw as Action; - }); -} - -/** Parses and validates `value` as a boolean. */ -function parseBoolean(flag: string, value: string | undefined): boolean { - return parseFlag(flag, value, (raw) => { - if (raw !== "true" && raw !== "false") { - throw new Error("Must be 'true' or 'false'."); - } - return raw === "true"; - }); -} - -/** Parses and validates `value` as an issue/pull request number. */ -function parseIssueId(value: string | undefined): number { - return parseFlag("issue-id", value, (raw) => { - const parsed = Number(raw); - if (!Number.isInteger(parsed) || parsed <= 0) { - throw new Error("Must be a positive integer."); - } - return parsed; - }); -} - -/** Parses and validates `value` as an `owner/repo` repository reference. */ -function parseRepository(value: string | undefined): { - owner: string; - repo: string; -} { - return parseFlag("repository", value, (raw) => { - const [owner, repo, ...rest] = raw.split("/"); - if (!owner || !repo || rest.length > 0) { - throw new Error("Must be in the form 'owner/repo'."); - } - return { owner, repo }; - }); -} - -/** Parses the command-line arguments into `Options`. */ +/** Parses CLI arguments supplied by the composite action into `Options`. */ export function parseOptions(argv?: string[]): Options { const { values } = parseArgs({ args: argv, @@ -123,24 +59,17 @@ export function parseOptions(argv?: string[]): Options { strict: true, }); - if (values.body === undefined) { - throw new Error("Missing required flag --body."); - } - if (values.marker === undefined || values.marker.trim() === "") { - throw new Error("Missing required flag --marker."); - } + assert(values.marker?.trim(), "Missing required flag --marker."); + const [owner, repo] = values.repository!.split("/"); return { - body: values.body, - marker: values.marker, - actionCondition: parseBoolean( - "action-condition", - values["action-condition"], - ), - actionIfTrue: parseAction("action-if-true", values["action-if-true"]), - actionIfFalse: parseAction("action-if-false", values["action-if-false"]), - issueId: parseIssueId(values["issue-id"]), - repository: parseRepository(values.repository), + body: values.body!, + marker: values.marker!, + actionCondition: values["action-condition"] === "true", + actionIfTrue: values["action-if-true"] as Action, + actionIfFalse: values["action-if-false"] as Action, + issueId: Number(values["issue-id"]), + repository: { owner, repo }, }; } From ae238655488f49ed7f28bd85a74333054160d984 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 28 Oct 2026 15:53:36 -0500 Subject: [PATCH 22/76] Move comment branching into workflow steps Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/post-comment/action.yml | 22 +++++----------- .github/workflows/pr-checks.yml | 19 +++++++++++--- pr-checks/post-comment.test.ts | 34 +++++++++++++------------ pr-checks/post-comment.ts | 29 +++++++-------------- 4 files changed, 49 insertions(+), 55 deletions(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index 8b3d56ee95..b8bffb3d56 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -5,16 +5,10 @@ inputs: description: "Non-empty marker identifying the comment. Use a unique, stable HTML comment for each distinct comment." required: true body: - description: "Full comment markdown." - required: true - action-condition: - description: "The business condition ('true' or 'false') that selects which action to perform." - required: true - action-if-true: - description: "Action to perform when action-condition is 'true'. One of: none, insert, upsert, delete." - required: true - action-if-false: - description: "Action to perform when action-condition is 'false'. One of: none, insert, upsert, delete." + description: "Full comment markdown. Not needed when deleting a comment." + required: false + action: + description: "Action to perform. One of: none, insert, upsert, delete." required: true issue-id: description: "The issue or pull request number to post/update/delete the comment on. Defaults to the current pull request if not provided." @@ -32,15 +26,11 @@ runs: MARKER: ${{ inputs.marker }} GH_TOKEN: ${{ inputs.token }} ISSUE_ID: ${{ inputs.issue-id || github.event.pull_request.number }} - ACTION_CONDITION: ${{ inputs.action-condition }} - ACTION_IF_TRUE: ${{ inputs.action-if-true }} - ACTION_IF_FALSE: ${{ inputs.action-if-false }} + ACTION: ${{ inputs.action }} run: | npx tsx ./pr-checks/post-comment.ts \ --body "$BODY" \ --marker "$MARKER" \ - --action-condition "$ACTION_CONDITION" \ - --action-if-true "$ACTION_IF_TRUE" \ - --action-if-false "$ACTION_IF_FALSE" \ + --action "$ACTION" \ --issue-id "$ISSUE_ID" \ --repository "$GITHUB_REPOSITORY" diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index d8450dc4b7..1f1c790202 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -292,6 +292,7 @@ jobs: # Release, backport, mergeback, and bundle-update PRs deliberately modify CHANGELOG.md, # so skip comment management entirely for these automation flows. if: >- + needs.other-checks.outputs.changelog-changed == 'true' && !startsWith(github.event.pull_request.head.ref, 'update-v') && !startsWith(github.event.pull_request.head.ref, 'backport-v') && !startsWith(github.event.pull_request.head.ref, 'mergeback/') && @@ -304,7 +305,19 @@ jobs: Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` file will be automatically generated from those change-notes. See [`unreleased-change-notes/README.md`](https://github.com/github/codeql-action/blob/main/unreleased-change-notes/README.md) for more information. - action-condition: ${{ needs.other-checks.outputs.changelog-changed }} - action-if-true: upsert - action-if-false: delete + action: upsert + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Delete the warning about modifying CHANGELOG.md + id: delete-changelog-warning + if: >- + needs.other-checks.outputs.changelog-changed != 'true' && + !startsWith(github.event.pull_request.head.ref, 'update-v') && + !startsWith(github.event.pull_request.head.ref, 'backport-v') && + !startsWith(github.event.pull_request.head.ref, 'mergeback/') && + !startsWith(github.event.pull_request.head.ref, 'update-bundle/') + uses: ./.github/actions/post-comment + with: + marker: "" + action: delete token: ${{ secrets.GITHUB_TOKEN }} diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index 6e7179bf65..cda92de9b7 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -22,12 +22,8 @@ const validFlags = [ "hello", "--marker", "", - "--action-condition", - "true", - "--action-if-true", + "--action", "insert", - "--action-if-false", - "delete", "--issue-id", "42", "--repository", @@ -56,17 +52,20 @@ describe("parseOptions", async () => { assert.deepEqual(options, { body: "hello", marker: "", - actionCondition: true, - actionIfTrue: "insert", - actionIfFalse: "delete", + action: "insert", issueId: 42, repository: { owner: "github", repo: "codeql-action" }, }); }); - await it("parses action-condition=false", () => { - const options = parseOptions(withFlag("--action-condition", "false")); - assert.equal(options.actionCondition, false); + await it("parses a delete action without a body", () => { + const options = parseOptions([ + ...withoutFlag("--body"), + "--action", + "delete", + ]); + assert.equal(options.action, "delete"); + assert.equal(options.body, ""); }); await it("rejects a missing --marker", () => { @@ -181,9 +180,7 @@ describe("findExistingComment", async () => { const baseOptions: Options = { body: "hello", marker: "", - actionCondition: true, - actionIfTrue: "insert", - actionIfFalse: "delete", + action: "insert", issueId: 42, repository: { owner: "owner", repo: "repo" }, }; @@ -281,9 +278,14 @@ describe("performAction", async () => { const { client, calls } = fakeClient([ { id: 9, body: "\nold" }, ]); - await performAction(client, "delete", baseOptions); + const options = parseOptions([ + ...withoutFlag("--body"), + "--action", + "delete", + ]); + await performAction(client, options.action, options); assert.deepEqual(calls.deleteComment, [ - { owner: "owner", repo: "repo", comment_id: 9 }, + { owner: "github", repo: "codeql-action", comment_id: 9 }, ]); }); }); diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 1c61c02216..602bf2056a 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -31,12 +31,8 @@ export interface Options { body: string; /** The hidden HTML-comment marker used to find a pre-existing comment. */ marker: string; - /** The condition that selects which action to perform. */ - actionCondition: boolean; - /** The action to perform when `actionCondition` is `true`. */ - actionIfTrue: Action; - /** The action to perform when `actionCondition` is `false`. */ - actionIfFalse: Action; + /** The action to perform. */ + action: Action; /** The issue/pull request number to post/update/delete the comment on. */ issueId: number; /** The repository to operate on. */ @@ -48,11 +44,9 @@ export function parseOptions(argv?: string[]): Options { const { values } = parseArgs({ args: argv, options: { - body: { type: "string" }, + body: { type: "string", default: "" }, marker: { type: "string" }, - "action-condition": { type: "string" }, - "action-if-true": { type: "string" }, - "action-if-false": { type: "string" }, + action: { type: "string" }, "issue-id": { type: "string" }, repository: { type: "string" }, }, @@ -63,11 +57,9 @@ export function parseOptions(argv?: string[]): Options { const [owner, repo] = values.repository!.split("/"); return { - body: values.body!, + body: values.body, marker: values.marker!, - actionCondition: values["action-condition"] === "true", - actionIfTrue: values["action-if-true"] as Action, - actionIfFalse: values["action-if-false"] as Action, + action: values.action as Action, issueId: Number(values["issue-id"]), repository: { owner, repo }, }; @@ -102,7 +94,7 @@ export async function findExistingComment( } /** - * Performs the resolved `action` against a (possibly pre-existing) marked comment, using + * Performs the supplied `action` against a (possibly pre-existing) marked comment, using * `client` to talk to the GitHub API. This is the core dispatch logic of this script, extracted * from `main` so it can be unit-tested with an injected (fake) `client`. */ @@ -169,15 +161,12 @@ export async function performAction( async function main(): Promise { const options = parseOptions(); - const action = options.actionCondition - ? options.actionIfTrue - : options.actionIfFalse; - console.info(`Resolved action: ${action}`); + console.info(`Action: ${options.action}`); const token = resolveToken(process.env); const client = getApiClient(token); - await performAction(client, action, options); + await performAction(client, options.action, options); return 0; } From 94488778fdc9296be5ba13464f1784bf439495e1 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 28 Oct 2026 16:00:37 -0500 Subject: [PATCH 23/76] Simplify post-comment to a single set-comment mode Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/post-comment/action.yml | 11 +-- .github/workflows/pr-checks.yml | 13 ++- pr-checks/post-comment.test.ts | 112 ++++++++---------------- pr-checks/post-comment.ts | 100 ++++++--------------- 4 files changed, 76 insertions(+), 160 deletions(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index b8bffb3d56..951fd17042 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -1,17 +1,14 @@ name: "Post comment" -description: "Create, update, or delete a sticky PR comment identified by a caller-provided marker." +description: "Create or update a sticky PR comment identified by a caller-provided marker." inputs: marker: description: "Non-empty marker identifying the comment. Use a unique, stable HTML comment for each distinct comment." required: true body: - description: "Full comment markdown. Not needed when deleting a comment." - required: false - action: - description: "Action to perform. One of: none, insert, upsert, delete." + description: "Full comment markdown." required: true issue-id: - description: "The issue or pull request number to post/update/delete the comment on. Defaults to the current pull request if not provided." + description: "The issue or pull request number to post/update the comment on. Defaults to the current pull request if not provided." required: false token: description: "The GitHub token to authenticate with." @@ -26,11 +23,9 @@ runs: MARKER: ${{ inputs.marker }} GH_TOKEN: ${{ inputs.token }} ISSUE_ID: ${{ inputs.issue-id || github.event.pull_request.number }} - ACTION: ${{ inputs.action }} run: | npx tsx ./pr-checks/post-comment.ts \ --body "$BODY" \ --marker "$MARKER" \ - --action "$ACTION" \ --issue-id "$ISSUE_ID" \ --repository "$GITHUB_REPOSITORY" diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 1f1c790202..fb3f6aba2b 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -305,11 +305,10 @@ jobs: Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` file will be automatically generated from those change-notes. See [`unreleased-change-notes/README.md`](https://github.com/github/codeql-action/blob/main/unreleased-change-notes/README.md) for more information. - action: upsert token: ${{ secrets.GITHUB_TOKEN }} - - name: Delete the warning about modifying CHANGELOG.md - id: delete-changelog-warning + - name: Mark the CHANGELOG.md concern as resolved + id: resolve-changelog-warning if: >- needs.other-checks.outputs.changelog-changed != 'true' && !startsWith(github.event.pull_request.head.ref, 'update-v') && @@ -319,5 +318,11 @@ jobs: uses: ./.github/actions/post-comment with: marker: "" - action: delete + body: | + ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. + Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` + file will be automatically generated from those change-notes. + See [`unreleased-change-notes/README.md`](https://github.com/github/codeql-action/blob/main/unreleased-change-notes/README.md) for more information. + + **Edit:** `CHANGELOG.md` is no longer modified in this PR. This concern is resolved. token: ${{ secrets.GITHUB_TOKEN }} diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index cda92de9b7..de840427dc 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -12,8 +12,8 @@ import { findExistingComment, type Options, parseOptions, - performAction, resolveToken, + setComment, } from "./post-comment"; /** A baseline set of valid CLI flags, as an array, for use in parseOptions tests. */ @@ -22,8 +22,6 @@ const validFlags = [ "hello", "--marker", "", - "--action", - "insert", "--issue-id", "42", "--repository", @@ -52,22 +50,11 @@ describe("parseOptions", async () => { assert.deepEqual(options, { body: "hello", marker: "", - action: "insert", issueId: 42, repository: { owner: "github", repo: "codeql-action" }, }); }); - await it("parses a delete action without a body", () => { - const options = parseOptions([ - ...withoutFlag("--body"), - "--action", - "delete", - ]); - assert.equal(options.action, "delete"); - assert.equal(options.body, ""); - }); - await it("rejects a missing --marker", () => { assert.throws( () => parseOptions(withoutFlag("--marker")), @@ -124,8 +111,7 @@ function fakeClient(existingComments: Array<{ id: number; body?: string }>) { const calls: { createComment: unknown[]; updateComment: unknown[]; - deleteComment: unknown[]; - } = { createComment: [], updateComment: [], deleteComment: [] }; + } = { createComment: [], updateComment: [] }; const client = { paginate: async () => existingComments, @@ -138,9 +124,6 @@ function fakeClient(existingComments: Array<{ id: number; body?: string }>) { updateComment: async (params: unknown) => { calls.updateComment.push(params); }, - deleteComment: async (params: unknown) => { - calls.deleteComment.push(params); - }, }, }, }; @@ -176,56 +159,38 @@ describe("findExistingComment", async () => { }); }); -/** A baseline set of `Options`, for use in `performAction` tests. */ +/** A baseline set of `Options`, for use in `setComment` tests. */ const baseOptions: Options = { body: "hello", marker: "", - action: "insert", issueId: 42, repository: { owner: "owner", repo: "repo" }, }; -describe("performAction", async () => { - for (const action of ["upsert", "delete"] as const) { - await it(`uses the supplied marker for '${action}' without affecting other comments`, async () => { - const marker = ""; - const { client, calls } = fakeClient([ - { id: 1, body: "\nunrelated warning" }, - { id: 2, body: `${marker}\nold warning` }, - ]); - const options = parseOptions(withFlag("--marker", marker)); - await performAction(client, action, options); - assert.deepEqual(calls, { - createComment: [], - updateComment: - action === "upsert" - ? [ - { - ...options.repository, - comment_id: 2, - body: `${marker}\nhello`, - }, - ] - : [], - deleteComment: - action === "delete" ? [{ ...options.repository, comment_id: 2 }] : [], - }); - }); - } - - await it("does nothing for 'none'", async () => { - const { client, calls } = fakeClient([]); - await performAction(client, "none", baseOptions); +describe("setComment", async () => { + await it("uses the supplied marker without affecting other comments", async () => { + const marker = ""; + const { client, calls } = fakeClient([ + { id: 1, body: "\nunrelated warning" }, + { id: 2, body: `${marker}\nold warning` }, + ]); + const options = parseOptions(withFlag("--marker", marker)); + await setComment(client, options); assert.deepEqual(calls, { createComment: [], - updateComment: [], - deleteComment: [], + updateComment: [ + { + ...options.repository, + comment_id: 2, + body: `${marker}\nhello`, + }, + ], }); }); - await it("creates a new comment for 'insert', with the marker prepended", async () => { + await it("creates a new comment with the marker prepended", async () => { const { client, calls } = fakeClient([]); - await performAction(client, "insert", baseOptions); + await setComment(client, baseOptions); assert.deepEqual(calls.createComment, [ { owner: "owner", @@ -235,12 +200,11 @@ describe("performAction", async () => { }, ]); assert.deepEqual(calls.updateComment, []); - assert.deepEqual(calls.deleteComment, []); }); - await it("creates a new comment for 'upsert' when no existing comment is found", async () => { + await it("creates a new comment when no existing comment matches", async () => { const { client, calls } = fakeClient([{ id: 1, body: "unrelated" }]); - await performAction(client, "upsert", baseOptions); + await setComment(client, baseOptions); assert.deepEqual(calls.createComment, [ { owner: "owner", @@ -252,11 +216,11 @@ describe("performAction", async () => { assert.deepEqual(calls.updateComment, []); }); - await it("updates the existing comment for 'upsert' when one is found", async () => { + await it("updates the existing comment when one is found", async () => { const { client, calls } = fakeClient([ { id: 7, body: "\nold" }, ]); - await performAction(client, "upsert", baseOptions); + await setComment(client, baseOptions); assert.deepEqual(calls.updateComment, [ { owner: "owner", @@ -268,24 +232,20 @@ describe("performAction", async () => { assert.deepEqual(calls.createComment, []); }); - await it("does nothing for 'delete' when no existing comment is found", async () => { - const { client, calls } = fakeClient([{ id: 1, body: "unrelated" }]); - await performAction(client, "delete", baseOptions); - assert.deepEqual(calls.deleteComment, []); - }); - - await it("deletes the existing comment for 'delete' when one is found", async () => { + await it("replaces a warning with the resolved state using the same marker", async () => { const { client, calls } = fakeClient([ { id: 9, body: "\nold" }, ]); - const options = parseOptions([ - ...withoutFlag("--body"), - "--action", - "delete", - ]); - await performAction(client, options.action, options); - assert.deepEqual(calls.deleteComment, [ - { owner: "github", repo: "codeql-action", comment_id: 9 }, + const body = + "`CHANGELOG.md` is not modified in this PR. No changelog action is needed."; + await setComment(client, { ...baseOptions, body }); + assert.deepEqual(calls.updateComment, [ + { + ...baseOptions.repository, + comment_id: 9, + body: `${baseOptions.marker}\n${body}`, + }, ]); + assert.deepEqual(calls.createComment, []); }); }); diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 602bf2056a..3f8abe40bd 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -1,15 +1,14 @@ #!/usr/bin/env npx tsx /* -Generic CLI for creating, updating, or deleting a "sticky" PR comment identified by a hidden +Generic CLI for creating or updating a "sticky" PR comment identified by a hidden HTML-comment marker. This centralizes the gh api logic previously duplicated across PR-check workflow steps that each managed their own marked comment (e.g. a CHANGELOG.md modification warning). The marker is passed explicitly via `--marker` and can be any non-empty string, though an HTML comment (e.g. ``) is recommended so it doesn't render visibly. It is used -both to find a pre-existing comment on the pull request so that -`upsert`/`delete` actions know which comment to operate on, and is automatically prepended to +both to find a pre-existing comment on the pull request to update, and is automatically prepended to `--body` when posting or updating a comment so that future invocations can find it again. The `.github/actions/post-comment` action requires callers to supply this value via its `marker` input. @@ -20,20 +19,13 @@ import { parseArgs } from "node:util"; import { type ApiClient, getApiClient } from "./api-client"; -/** The set of valid actions that can be performed against a (possibly pre-existing) marked comment. */ -export const ACTIONS = ["none", "insert", "upsert", "delete"] as const; -/** An action to perform against a (possibly pre-existing) marked comment. */ -export type Action = (typeof ACTIONS)[number]; - /** Represents the command-line options. */ export interface Options { /** The full comment body. */ body: string; /** The hidden HTML-comment marker used to find a pre-existing comment. */ marker: string; - /** The action to perform. */ - action: Action; - /** The issue/pull request number to post/update/delete the comment on. */ + /** The issue/pull request number to post/update the comment on. */ issueId: number; /** The repository to operate on. */ repository: { owner: string; repo: string }; @@ -44,9 +36,8 @@ export function parseOptions(argv?: string[]): Options { const { values } = parseArgs({ args: argv, options: { - body: { type: "string", default: "" }, + body: { type: "string" }, marker: { type: "string" }, - action: { type: "string" }, "issue-id": { type: "string" }, repository: { type: "string" }, }, @@ -57,9 +48,8 @@ export function parseOptions(argv?: string[]): Options { const [owner, repo] = values.repository!.split("/"); return { - body: values.body, + body: values.body!, marker: values.marker!, - action: values.action as Action, issueId: Number(values["issue-id"]), repository: { owner, repo }, }; @@ -94,79 +84,45 @@ export async function findExistingComment( } /** - * Performs the supplied `action` against a (possibly pre-existing) marked comment, using - * `client` to talk to the GitHub API. This is the core dispatch logic of this script, extracted - * from `main` so it can be unit-tested with an injected (fake) `client`. + * Creates or updates a marked comment using `client` to talk to the GitHub API. */ -export async function performAction( +export async function setComment( client: ApiClient, - action: Action, options: Options, ): Promise { const { issueId, marker, repository } = options; const body = `${marker}\n${options.body}`; - let existingCommentId: number | undefined; - if (action === "upsert" || action === "delete") { - existingCommentId = await findExistingComment( - client, - repository, - issueId, - marker, - ); - } - - switch (action) { - case "none": - console.info("No action needed."); - break; - case "insert": - console.info("Creating a new comment."); - await client.rest.issues.createComment({ - ...repository, - issue_number: issueId, - body, - }); - break; - case "upsert": - if (existingCommentId === undefined) { - console.info("No existing comment found; creating a new comment."); - await client.rest.issues.createComment({ - ...repository, - issue_number: issueId, - body, - }); - } else { - console.info(`Updating existing comment ${existingCommentId}.`); - await client.rest.issues.updateComment({ - ...repository, - comment_id: existingCommentId, - body, - }); - } - break; - case "delete": - if (existingCommentId === undefined) { - console.info("No existing comment found to delete; skipping."); - } else { - console.info(`Deleting existing comment ${existingCommentId}.`); - await client.rest.issues.deleteComment({ - ...repository, - comment_id: existingCommentId, - }); - } - break; + const existingCommentId = await findExistingComment( + client, + repository, + issueId, + marker, + ); + if (existingCommentId === undefined) { + console.info("No existing comment found; creating a new comment."); + await client.rest.issues.createComment({ + ...repository, + issue_number: issueId, + body, + }); + } else { + console.info(`Updating existing comment ${existingCommentId}.`); + await client.rest.issues.updateComment({ + ...repository, + comment_id: existingCommentId, + body, + }); } } async function main(): Promise { const options = parseOptions(); - console.info(`Action: ${options.action}`); const token = resolveToken(process.env); const client = getApiClient(token); - await performAction(client, options.action, options); + await setComment(client, options); return 0; } From 03137fc68db87f6ae87eba8a822f1be601efbe8a Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 28 Oct 2026 16:06:08 -0500 Subject: [PATCH 24/76] Rename changelog outputs to modified Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index fb3f6aba2b..911dbb7cd3 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -93,7 +93,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 outputs: - changelog-changed: ${{ steps.changelog-check.outputs.changed }} + changelog-modified: ${{ steps.changelog-check.outputs.modified }} concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} @@ -192,9 +192,9 @@ jobs: run: | if ! git diff --exit-code --quiet "$BASE_SHA" "$HEAD_SHA" -- CHANGELOG.md; then echo "CHANGELOG.md was modified in this PR." - echo "changed=true" >> "$GITHUB_OUTPUT" + echo "modified=true" >> "$GITHUB_OUTPUT" else - echo "changed=false" >> "$GITHUB_OUTPUT" + echo "modified=false" >> "$GITHUB_OUTPUT" fi - name: "Backport: Check out base ref" @@ -292,7 +292,7 @@ jobs: # Release, backport, mergeback, and bundle-update PRs deliberately modify CHANGELOG.md, # so skip comment management entirely for these automation flows. if: >- - needs.other-checks.outputs.changelog-changed == 'true' && + needs.other-checks.outputs.changelog-modified == 'true' && !startsWith(github.event.pull_request.head.ref, 'update-v') && !startsWith(github.event.pull_request.head.ref, 'backport-v') && !startsWith(github.event.pull_request.head.ref, 'mergeback/') && @@ -310,7 +310,7 @@ jobs: - name: Mark the CHANGELOG.md concern as resolved id: resolve-changelog-warning if: >- - needs.other-checks.outputs.changelog-changed != 'true' && + needs.other-checks.outputs.changelog-modified != 'true' && !startsWith(github.event.pull_request.head.ref, 'update-v') && !startsWith(github.event.pull_request.head.ref, 'backport-v') && !startsWith(github.event.pull_request.head.ref, 'mergeback/') && From 36f220a96c230f90737a692bd5b44eb00ef5d238 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 28 Oct 2026 16:08:22 -0500 Subject: [PATCH 25/76] Remove unused post-comment step IDs Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 911dbb7cd3..1e8b15ea60 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -288,7 +288,6 @@ jobs: fi - name: Post a warning about modifying CHANGELOG.md - id: post-changelog-warning # Release, backport, mergeback, and bundle-update PRs deliberately modify CHANGELOG.md, # so skip comment management entirely for these automation flows. if: >- @@ -308,7 +307,6 @@ jobs: token: ${{ secrets.GITHUB_TOKEN }} - name: Mark the CHANGELOG.md concern as resolved - id: resolve-changelog-warning if: >- needs.other-checks.outputs.changelog-modified != 'true' && !startsWith(github.event.pull_request.head.ref, 'update-v') && From c069d49e81684ff52f0b839a095bfb58194720f9 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Wed, 28 Oct 2026 16:46:41 -0500 Subject: [PATCH 26/76] Test sticky comments using observable state Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- pr-checks/post-comment.test.ts | 167 ++++++++++++++++++--------------- 1 file changed, 93 insertions(+), 74 deletions(-) diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index de840427dc..7babddcff3 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -75,18 +75,6 @@ describe("parseOptions", async () => { /Missing required flag --marker/, ); }); - - await it("rejects unknown flags using parseArgs", () => { - assert.throws(() => parseOptions([...validFlags, "--unknown", "value"]), { - code: "ERR_PARSE_ARGS_UNKNOWN_OPTION", - }); - }); - - await it("rejects flags without a value using parseArgs", () => { - assert.throws(() => parseOptions([...validFlags, "--body"]), { - code: "ERR_PARSE_ARGS_INVALID_OPTION_VALUE", - }); - }); }); describe("resolveToken", async () => { @@ -108,27 +96,34 @@ describe("resolveToken", async () => { /** A minimal fake of the subset of `ApiClient` used by post-comment.ts. */ function fakeClient(existingComments: Array<{ id: number; body?: string }>) { - const calls: { - createComment: unknown[]; - updateComment: unknown[]; - } = { createComment: [], updateComment: [] }; + const comments = existingComments.map((comment) => ({ ...comment })); + let nextId = + comments.reduce((maxId, comment) => Math.max(maxId, comment.id), 0) + 1; const client = { - paginate: async () => existingComments, + paginate: async () => comments, rest: { issues: { listComments: () => {}, - createComment: async (params: unknown) => { - calls.createComment.push(params); + createComment: async ({ body }: { body: string }) => { + comments.push({ id: nextId++, body }); }, - updateComment: async (params: unknown) => { - calls.updateComment.push(params); + updateComment: async ({ + comment_id, + body, + }: { + comment_id: number; + body: string; + }) => { + const comment = comments.find(({ id }) => id === comment_id); + assert.ok(comment, `Comment ${comment_id} does not exist.`); + comment.body = body; }, }, }, }; - return { client: client as unknown as ApiClient, calls }; + return { client: client as unknown as ApiClient, comments }; } describe("findExistingComment", async () => { @@ -167,85 +162,109 @@ const baseOptions: Options = { repository: { owner: "owner", repo: "repo" }, }; +function assertCommentContent( + comment: { body?: string }, + marker: string, + body: string, +): void { + assert.ok(comment.body?.startsWith(marker)); + assert.ok(comment.body?.endsWith(body)); +} + describe("setComment", async () => { await it("uses the supplied marker without affecting other comments", async () => { const marker = ""; - const { client, calls } = fakeClient([ - { id: 1, body: "\nunrelated warning" }, + const { client, comments } = fakeClient([ + { id: 1, body: `${baseOptions.marker}\nunrelated warning` }, { id: 2, body: `${marker}\nold warning` }, ]); const options = parseOptions(withFlag("--marker", marker)); + await setComment(client, options); - assert.deepEqual(calls, { - createComment: [], - updateComment: [ - { - ...options.repository, - comment_id: 2, - body: `${marker}\nhello`, - }, - ], + + // Only the comment with the supplied marker changes. + assert.equal(comments.length, 2); + assert.deepEqual(comments[0], { + id: 1, + body: `${baseOptions.marker}\nunrelated warning`, }); + assert.equal(comments[1].id, 2); + assertCommentContent(comments[1], marker, options.body); }); await it("creates a new comment with the marker prepended", async () => { - const { client, calls } = fakeClient([]); + const { client, comments } = fakeClient([]); + // No comment has the marker before posting. + assert.equal(comments.length, 0); + assert.ok( + !comments.some(({ body }) => body?.startsWith(baseOptions.marker)), + ); + await setComment(client, baseOptions); - assert.deepEqual(calls.createComment, [ - { - owner: "owner", - repo: "repo", - issue_number: 42, - body: "\nhello", - }, - ]); - assert.deepEqual(calls.updateComment, []); + + // Posting adds exactly one comment with the marker before the body. + assert.equal(comments.length, 1); + assertCommentContent(comments[0], baseOptions.marker, baseOptions.body); }); await it("creates a new comment when no existing comment matches", async () => { - const { client, calls } = fakeClient([{ id: 1, body: "unrelated" }]); + const originalComments = [ + { id: 7, body: "unrelated" }, + { id: 2, body: "another unrelated comment" }, + ]; + const { client, comments } = fakeClient(originalComments); + // Existing comments do not match the marker. + assert.ok( + !comments.some(({ body }) => body?.startsWith(baseOptions.marker)), + ); + await setComment(client, baseOptions); - assert.deepEqual(calls.createComment, [ - { - owner: "owner", - repo: "repo", - issue_number: 42, - body: "\nhello", - }, - ]); - assert.deepEqual(calls.updateComment, []); + + // A new comment is added without changing unrelated comments. + assert.equal(comments.length, originalComments.length + 1); + assert.deepEqual( + comments.slice(0, originalComments.length), + originalComments, + ); + const markedComments = comments.filter(({ body }) => + body?.startsWith(baseOptions.marker), + ); + // Exactly one comment contains the expected marker and body. + assert.equal(markedComments.length, 1); + assertCommentContent( + markedComments[0], + baseOptions.marker, + baseOptions.body, + ); + // The new comment's ID does not collide with existing IDs. + assert.equal(new Set(comments.map(({ id }) => id)).size, comments.length); }); await it("updates the existing comment when one is found", async () => { - const { client, calls } = fakeClient([ - { id: 7, body: "\nold" }, + const { client, comments } = fakeClient([ + { id: 7, body: `${baseOptions.marker}\nold` }, ]); + await setComment(client, baseOptions); - assert.deepEqual(calls.updateComment, [ - { - owner: "owner", - repo: "repo", - comment_id: 7, - body: "\nhello", - }, - ]); - assert.deepEqual(calls.createComment, []); + + // Updating preserves the comment's ID without creating a duplicate. + assert.equal(comments.length, 1); + assert.equal(comments[0].id, 7); + assertCommentContent(comments[0], baseOptions.marker, baseOptions.body); }); await it("replaces a warning with the resolved state using the same marker", async () => { - const { client, calls } = fakeClient([ - { id: 9, body: "\nold" }, + const { client, comments } = fakeClient([ + { id: 9, body: `${baseOptions.marker}\nold` }, ]); const body = "`CHANGELOG.md` is not modified in this PR. No changelog action is needed."; + await setComment(client, { ...baseOptions, body }); - assert.deepEqual(calls.updateComment, [ - { - ...baseOptions.repository, - comment_id: 9, - body: `${baseOptions.marker}\n${body}`, - }, - ]); - assert.deepEqual(calls.createComment, []); + + // The resolved state replaces the warning on the same marked comment. + assert.equal(comments.length, 1); + assert.equal(comments[0].id, 9); + assertCommentContent(comments[0], baseOptions.marker, body); }); }); From afaf32464607c0552afd8d45aacd5b8a06c400bb Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 09:49:40 -0500 Subject: [PATCH 27/76] Move `resolveToken` to `pr-checks/api-client.ts` --- pr-checks/api-client.ts | 11 +++++++++++ pr-checks/post-comment.test.ts | 3 +-- pr-checks/post-comment.ts | 13 +------------ 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/pr-checks/api-client.ts b/pr-checks/api-client.ts index b8f914d815..8f990362b9 100644 --- a/pr-checks/api-client.ts +++ b/pr-checks/api-client.ts @@ -8,3 +8,14 @@ export function getApiClient(token: string): ApiClient { const opts = githubUtils.getOctokitOptions(token); return new githubUtils.GitHub(opts); } + +/** Resolves the GitHub API token to use, from `GH_TOKEN` or `GITHUB_TOKEN`. */ +export function resolveToken(env: NodeJS.ProcessEnv): string { + const token = env.GH_TOKEN?.trim() || env.GITHUB_TOKEN?.trim(); + if (!token) { + throw new Error( + "Missing authentication token. Set GH_TOKEN or GITHUB_TOKEN.", + ); + } + return token; +} diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index 7babddcff3..8c1ad5d837 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -7,12 +7,11 @@ Tests for post-comment.ts. import * as assert from "node:assert/strict"; import { describe, it } from "node:test"; -import { type ApiClient } from "./api-client"; +import { type ApiClient, resolveToken } from "./api-client"; import { findExistingComment, type Options, parseOptions, - resolveToken, setComment, } from "./post-comment"; diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 3f8abe40bd..81c42f25a0 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -17,7 +17,7 @@ The `.github/actions/post-comment` action requires callers to supply this value import assert from "node:assert/strict"; import { parseArgs } from "node:util"; -import { type ApiClient, getApiClient } from "./api-client"; +import { type ApiClient, getApiClient, resolveToken } from "./api-client"; /** Represents the command-line options. */ export interface Options { @@ -55,17 +55,6 @@ export function parseOptions(argv?: string[]): Options { }; } -/** Resolves the GitHub API token to use, from `GH_TOKEN` or `GITHUB_TOKEN`. */ -export function resolveToken(env: NodeJS.ProcessEnv): string { - const token = env.GH_TOKEN?.trim() || env.GITHUB_TOKEN?.trim(); - if (!token) { - throw new Error( - "Missing authentication token. Set GH_TOKEN or GITHUB_TOKEN.", - ); - } - return token; -} - /** * Finds the first comment on the given issue/pull request whose body starts with `marker`, if any. */ From 3fb676f638e291635d5b0104f2f02bdfd9ff8b56 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 09:56:18 -0500 Subject: [PATCH 28/76] Use existing `RepositoryNwo` type --- pr-checks/post-comment.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 81c42f25a0..8c9703357a 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -17,6 +17,8 @@ The `.github/actions/post-comment` action requires callers to supply this value import assert from "node:assert/strict"; import { parseArgs } from "node:util"; +import { RepositoryNwo } from "../src/repository"; + import { type ApiClient, getApiClient, resolveToken } from "./api-client"; /** Represents the command-line options. */ @@ -28,7 +30,7 @@ export interface Options { /** The issue/pull request number to post/update the comment on. */ issueId: number; /** The repository to operate on. */ - repository: { owner: string; repo: string }; + repository: RepositoryNwo; } /** Parses CLI arguments supplied by the composite action into `Options`. */ @@ -60,7 +62,7 @@ export function parseOptions(argv?: string[]): Options { */ export async function findExistingComment( client: ApiClient, - repository: { owner: string; repo: string }, + repository: RepositoryNwo, issueNumber: number, marker: string, ): Promise { From 56fa196def3445e75b6f83e0451bb67e1a6d4753 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 09:58:48 -0500 Subject: [PATCH 29/76] Use YAML multiline string for the Action's inputs' descriptions --- .github/actions/post-comment/action.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index 951fd17042..a71b57d9fb 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -2,13 +2,17 @@ name: "Post comment" description: "Create or update a sticky PR comment identified by a caller-provided marker." inputs: marker: - description: "Non-empty marker identifying the comment. Use a unique, stable HTML comment for each distinct comment." + description: > + Non-empty marker identifying the comment. Use a unique, + stable HTML comment for each distinct comment. required: true body: description: "Full comment markdown." required: true issue-id: - description: "The issue or pull request number to post/update the comment on. Defaults to the current pull request if not provided." + description: > + The issue or pull request number to post/update the comment on. + Defaults to the current pull request if not provided. required: false token: description: "The GitHub token to authenticate with." From 2902eeab4d2bd10d3f6abcb6ac76da08b77366ef Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 10:01:27 -0500 Subject: [PATCH 30/76] Checkout `main` instead of PR's base for the `post-pr-comments` job --- .github/workflows/pr-checks.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 1e8b15ea60..fd3582c7de 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -241,9 +241,9 @@ jobs: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - # Check out the base ref, not the PR's head, since this job runs with + # Check out main, not the PR's head, since this job runs with # `pull-requests: write` permissions and must not execute untrusted code from the PR. - ref: ${{ github.event.pull_request.base.sha }} + ref: main sparse-checkout: | pr-checks .github/actions/post-comment From 87cac24cddbd2ba55bff057328cf9c447e9afa95 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 10:03:32 -0500 Subject: [PATCH 31/76] Avoid sparse checkout This codebase is a tad coupled; it could end up biting us. --- .github/workflows/pr-checks.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index fd3582c7de..2193a69c75 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -244,9 +244,6 @@ jobs: # Check out main, not the PR's head, since this job runs with # `pull-requests: write` permissions and must not execute untrusted code from the PR. ref: main - sparse-checkout: | - pr-checks - .github/actions/post-comment - name: Set up Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 From 5bb3554330a44fde8c21454ae017571752c6abd8 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 10:13:06 -0500 Subject: [PATCH 32/76] Make input-validation assertions more granular --- pr-checks/post-comment.test.ts | 4 ++-- pr-checks/post-comment.ts | 8 ++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index 8c1ad5d837..d82f5d2492 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -64,14 +64,14 @@ describe("parseOptions", async () => { await it("rejects an empty --marker", () => { assert.throws( () => parseOptions(withFlag("--marker", "")), - /Missing required flag --marker/, + /The value for --marker cannot be empty/, ); }); await it("rejects a whitespace-only --marker", () => { assert.throws( () => parseOptions(withFlag("--marker", " \t\n")), - /Missing required flag --marker/, + /The value for --marker cannot be empty/, ); }); }); diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 8c9703357a..20dad0cf08 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -46,12 +46,16 @@ export function parseOptions(argv?: string[]): Options { strict: true, }); - assert(values.marker?.trim(), "Missing required flag --marker."); + assert(values.marker !== undefined, "Missing required flag --marker."); + assert( + values.marker.trim() !== "", + "The value for --marker cannot be empty.", + ); const [owner, repo] = values.repository!.split("/"); return { body: values.body!, - marker: values.marker!, + marker: values.marker, issueId: Number(values["issue-id"]), repository: { owner, repo }, }; From f13bcf383fda63325ba85093fdac7a37daa38121 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 10:20:21 -0500 Subject: [PATCH 33/76] Warn if more than one marked comment was found --- pr-checks/post-comment.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 20dad0cf08..6c9542d298 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -75,7 +75,17 @@ export async function findExistingComment( issue_number: issueNumber, per_page: 100, }); - return comments.find((comment) => comment.body?.startsWith(marker))?.id; + const markedComments = comments.filter((comment) => + comment.body?.startsWith(marker), + ); + if (markedComments.length > 1) { + console.warn( + `Found ${markedComments.length} comments with marker "${marker}". ` + + "Updating the first one and leaving the others unchanged." + + "Use a unique marker for each distinct managed comment to avoid this situation.", + ); + } + return markedComments[0]?.id; } /** From 19e1ab5452dea5c862ca7af856b474750afa1dc4 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 10:28:26 -0500 Subject: [PATCH 34/76] Update `pr-checks/post-comment.ts` description comment --- pr-checks/post-comment.ts | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 6c9542d298..1b55c13b20 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -1,17 +1,19 @@ #!/usr/bin/env npx tsx /* -Generic CLI for creating or updating a "sticky" PR comment identified by a hidden -HTML-comment marker. This centralizes the gh api logic previously duplicated across PR-check -workflow steps that each managed their own marked comment (e.g. a CHANGELOG.md modification -warning). - -The marker is passed explicitly via `--marker` and can be any non-empty string, though an -HTML comment (e.g. ``) is recommended so it doesn't render visibly. It is used -both to find a pre-existing comment on the pull request to update, and is automatically prepended to -`--body` when posting or updating a comment so that future invocations can find it again. -The `.github/actions/post-comment` action requires callers to supply this value via its -`marker` input. +Creates or updates a pull request comment identified by a marker. The marker +is supplied via `--marker` (or the `.github/actions/post-comment` action's `marker` input) +and must be non-empty. The marker is prepended to `--body` and used to find +the comment on later runs. + +Example: +```sh +GH_TOKEN= npx tsx ./pr-checks/post-comment.ts \ + --body "The changelog needs updating." \ + --marker "" \ + --issue-id 123 \ + --repository github/codeql-action +``` */ import assert from "node:assert/strict"; From 9359b6b57145a73e9dcf89286a67594cbbf528db Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 10:34:12 -0500 Subject: [PATCH 35/76] Wrap `--marker` argument in HTML comment tags automatically --- .github/actions/post-comment/action.yml | 4 ++-- .github/workflows/pr-checks.yml | 4 ++-- pr-checks/post-comment.test.ts | 30 ++++++++++++------------- pr-checks/post-comment.ts | 19 ++++++++++------ 4 files changed, 31 insertions(+), 26 deletions(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index a71b57d9fb..8055bf21da 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -3,8 +3,8 @@ description: "Create or update a sticky PR comment identified by a caller-provid inputs: marker: description: > - Non-empty marker identifying the comment. Use a unique, - stable HTML comment for each distinct comment. + Non-empty plain-text identifier for the comment. Use a unique, stable value + for each distinct comment; it is automatically wrapped in a hidden HTML comment. required: true body: description: "Full comment markdown." diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 2193a69c75..eda0850499 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -295,7 +295,7 @@ jobs: !startsWith(github.event.pull_request.head.ref, 'update-bundle/') uses: ./.github/actions/post-comment with: - marker: "" + marker: "post-comment:CHANGELOG.md" body: | ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` @@ -312,7 +312,7 @@ jobs: !startsWith(github.event.pull_request.head.ref, 'update-bundle/') uses: ./.github/actions/post-comment with: - marker: "" + marker: "post-comment:CHANGELOG.md" body: | ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index d82f5d2492..960e7a0f0b 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -20,7 +20,7 @@ const validFlags = [ "--body", "hello", "--marker", - "", + "marker", "--issue-id", "42", "--repository", @@ -48,7 +48,7 @@ describe("parseOptions", async () => { const options = parseOptions(validFlags); assert.deepEqual(options, { body: "hello", - marker: "", + marker: "marker", issueId: 42, repository: { owner: "github", repo: "codeql-action" }, }); @@ -136,7 +136,7 @@ describe("findExistingComment", async () => { client, { owner: "owner", repo: "repo" }, 1, - "", + "marker", ); assert.equal(id, 2); }); @@ -147,7 +147,7 @@ describe("findExistingComment", async () => { client, { owner: "owner", repo: "repo" }, 1, - "", + "marker", ); assert.equal(id, undefined); }); @@ -156,7 +156,7 @@ describe("findExistingComment", async () => { /** A baseline set of `Options`, for use in `setComment` tests. */ const baseOptions: Options = { body: "hello", - marker: "", + marker: "marker", issueId: 42, repository: { owner: "owner", repo: "repo" }, }; @@ -166,16 +166,16 @@ function assertCommentContent( marker: string, body: string, ): void { - assert.ok(comment.body?.startsWith(marker)); + assert.ok(comment.body?.startsWith(``)); assert.ok(comment.body?.endsWith(body)); } describe("setComment", async () => { await it("uses the supplied marker without affecting other comments", async () => { - const marker = ""; + const marker = "custom-warning"; const { client, comments } = fakeClient([ - { id: 1, body: `${baseOptions.marker}\nunrelated warning` }, - { id: 2, body: `${marker}\nold warning` }, + { id: 1, body: "\nunrelated warning" }, + { id: 2, body: "\nold warning" }, ]); const options = parseOptions(withFlag("--marker", marker)); @@ -185,7 +185,7 @@ describe("setComment", async () => { assert.equal(comments.length, 2); assert.deepEqual(comments[0], { id: 1, - body: `${baseOptions.marker}\nunrelated warning`, + body: "\nunrelated warning", }); assert.equal(comments[1].id, 2); assertCommentContent(comments[1], marker, options.body); @@ -196,7 +196,7 @@ describe("setComment", async () => { // No comment has the marker before posting. assert.equal(comments.length, 0); assert.ok( - !comments.some(({ body }) => body?.startsWith(baseOptions.marker)), + !comments.some(({ body }) => body?.startsWith("")), ); await setComment(client, baseOptions); @@ -214,7 +214,7 @@ describe("setComment", async () => { const { client, comments } = fakeClient(originalComments); // Existing comments do not match the marker. assert.ok( - !comments.some(({ body }) => body?.startsWith(baseOptions.marker)), + !comments.some(({ body }) => body?.startsWith("")), ); await setComment(client, baseOptions); @@ -226,7 +226,7 @@ describe("setComment", async () => { originalComments, ); const markedComments = comments.filter(({ body }) => - body?.startsWith(baseOptions.marker), + body?.startsWith(""), ); // Exactly one comment contains the expected marker and body. assert.equal(markedComments.length, 1); @@ -241,7 +241,7 @@ describe("setComment", async () => { await it("updates the existing comment when one is found", async () => { const { client, comments } = fakeClient([ - { id: 7, body: `${baseOptions.marker}\nold` }, + { id: 7, body: "\nold" }, ]); await setComment(client, baseOptions); @@ -254,7 +254,7 @@ describe("setComment", async () => { await it("replaces a warning with the resolved state using the same marker", async () => { const { client, comments } = fakeClient([ - { id: 9, body: `${baseOptions.marker}\nold` }, + { id: 9, body: "\nold" }, ]); const body = "`CHANGELOG.md` is not modified in this PR. No changelog action is needed."; diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 1b55c13b20..7f805d1ee9 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -3,14 +3,14 @@ /* Creates or updates a pull request comment identified by a marker. The marker is supplied via `--marker` (or the `.github/actions/post-comment` action's `marker` input) -and must be non-empty. The marker is prepended to `--body` and used to find -the comment on later runs. +and must be non-empty. Supply a plain-text identifier; the CLI wraps it in a +hidden HTML comment, prepends it to `--body`, and uses it to find the comment on later runs. Example: ```sh GH_TOKEN= npx tsx ./pr-checks/post-comment.ts \ --body "The changelog needs updating." \ - --marker "" \ + --marker "my-bot" \ --issue-id 123 \ --repository github/codeql-action ``` @@ -27,7 +27,7 @@ import { type ApiClient, getApiClient, resolveToken } from "./api-client"; export interface Options { /** The full comment body. */ body: string; - /** The hidden HTML-comment marker used to find a pre-existing comment. */ + /** Plain-text identifier wrapped in a hidden HTML comment. */ marker: string; /** The issue/pull request number to post/update the comment on. */ issueId: number; @@ -35,6 +35,10 @@ export interface Options { repository: RepositoryNwo; } +function hiddenMarker(marker: string): string { + return ``; +} + /** Parses CLI arguments supplied by the composite action into `Options`. */ export function parseOptions(argv?: string[]): Options { const { values } = parseArgs({ @@ -72,17 +76,18 @@ export async function findExistingComment( issueNumber: number, marker: string, ): Promise { + const formattedMarker = hiddenMarker(marker); const comments = await client.paginate(client.rest.issues.listComments, { ...repository, issue_number: issueNumber, per_page: 100, }); const markedComments = comments.filter((comment) => - comment.body?.startsWith(marker), + comment.body?.startsWith(formattedMarker), ); if (markedComments.length > 1) { console.warn( - `Found ${markedComments.length} comments with marker "${marker}". ` + + `Found ${markedComments.length} comments with marker "${formattedMarker}". ` + "Updating the first one and leaving the others unchanged." + "Use a unique marker for each distinct managed comment to avoid this situation.", ); @@ -98,7 +103,7 @@ export async function setComment( options: Options, ): Promise { const { issueId, marker, repository } = options; - const body = `${marker}\n${options.body}`; + const body = `${hiddenMarker(marker)}\n${options.body}`; const existingCommentId = await findExistingComment( client, From e9651489af039bd0669aee0c8c9069cecfcc5690 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 10:44:10 -0500 Subject: [PATCH 36/76] Avoid non-null assertion operators by asserting arguments --- pr-checks/post-comment.test.ts | 49 ++++++++++++++++++++++++++++++++++ pr-checks/post-comment.ts | 18 +++++++++++-- 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index 960e7a0f0b..7e02c4900a 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -54,6 +54,27 @@ describe("parseOptions", async () => { }); }); + await it("rejects a missing --body", () => { + assert.throws( + () => parseOptions(withoutFlag("--body")), + /Missing required flag --body/, + ); + }); + + await it("rejects an empty --body", () => { + assert.throws( + () => parseOptions(withFlag("--body", "")), + /The value for --body cannot be empty/, + ); + }); + + await it("rejects a whitespace-only --body", () => { + assert.throws( + () => parseOptions(withFlag("--body", " \t\n")), + /The value for --body cannot be empty/, + ); + }); + await it("rejects a missing --marker", () => { assert.throws( () => parseOptions(withoutFlag("--marker")), @@ -74,6 +95,34 @@ describe("parseOptions", async () => { /The value for --marker cannot be empty/, ); }); + + await it("rejects a missing --repository", () => { + assert.throws( + () => parseOptions(withoutFlag("--repository")), + /Missing required flag --repository/, + ); + }); + + await it("rejects an empty --repository", () => { + assert.throws( + () => parseOptions(withFlag("--repository", "")), + /The value for --repository cannot be empty/, + ); + }); + + await it("rejects a whitespace-only --repository", () => { + assert.throws( + () => parseOptions(withFlag("--repository", " \t\n")), + /The value for --repository cannot be empty/, + ); + }); + + await it("rejects an invalid --repository value", () => { + assert.throws( + () => parseOptions(withFlag("--repository", "github/codeql/action")), + /Invalid --repository value/, + ); + }); }); describe("resolveToken", async () => { diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 7f805d1ee9..e254221eb5 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -52,15 +52,29 @@ export function parseOptions(argv?: string[]): Options { strict: true, }); + assert(values.body !== undefined, "Missing required flag --body."); + assert(values.body.trim() !== "", "The value for --body cannot be empty."); assert(values.marker !== undefined, "Missing required flag --marker."); assert( values.marker.trim() !== "", "The value for --marker cannot be empty.", ); - const [owner, repo] = values.repository!.split("/"); + assert( + values.repository !== undefined, + "Missing required flag --repository.", + ); + assert( + values.repository.trim() !== "", + "The value for --repository cannot be empty.", + ); + assert( + /^[\w.-]+\/[\w.-]+$/.test(values.repository), + "Invalid --repository value.", + ); + const [owner, repo] = values.repository.split("/"); return { - body: values.body!, + body: values.body, marker: values.marker, issueId: Number(values["issue-id"]), repository: { owner, repo }, From 94f0998581cb14903318950325bef8c060c04abe Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 11:32:57 -0500 Subject: [PATCH 37/76] Avoid creating resolved comments without an existing warning Use a boolean --create-if-missing flag, supplied by the composite action by default and omitted for resolution updates. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/post-comment/action.yml | 6 ++++++ .github/workflows/pr-checks.yml | 1 + pr-checks/post-comment.test.ts | 28 ++++++++++++++++++++++++- pr-checks/post-comment.ts | 10 +++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index 8055bf21da..bf8a39b481 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -9,6 +9,10 @@ inputs: body: description: "Full comment markdown." required: true + create-if-missing: + description: "Create a comment if no matching marker exists. Set to 'false' to update existing comments only." + required: false + default: "true" issue-id: description: > The issue or pull request number to post/update the comment on. @@ -25,11 +29,13 @@ runs: env: BODY: ${{ inputs.body }} MARKER: ${{ inputs.marker }} + CREATE_IF_MISSING: ${{ inputs.create-if-missing != 'false' && '--create-if-missing' || '' }} GH_TOKEN: ${{ inputs.token }} ISSUE_ID: ${{ inputs.issue-id || github.event.pull_request.number }} run: | npx tsx ./pr-checks/post-comment.ts \ --body "$BODY" \ --marker "$MARKER" \ + $CREATE_IF_MISSING \ --issue-id "$ISSUE_ID" \ --repository "$GITHUB_REPOSITORY" diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index eda0850499..7398391d3c 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -313,6 +313,7 @@ jobs: uses: ./.github/actions/post-comment with: marker: "post-comment:CHANGELOG.md" + create-if-missing: "false" body: | ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index 7e02c4900a..63e0f6caad 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -49,11 +49,17 @@ describe("parseOptions", async () => { assert.deepEqual(options, { body: "hello", marker: "marker", + createIfMissing: false, issueId: 42, repository: { owner: "github", repo: "codeql-action" }, }); }); + await it("enables creation when --create-if-missing is supplied", () => { + const options = parseOptions([...validFlags, "--create-if-missing"]); + assert.equal(options.createIfMissing, true); + }); + await it("rejects a missing --body", () => { assert.throws( () => parseOptions(withoutFlag("--body")), @@ -206,6 +212,7 @@ describe("findExistingComment", async () => { const baseOptions: Options = { body: "hello", marker: "marker", + createIfMissing: true, issueId: 42, repository: { owner: "owner", repo: "repo" }, }; @@ -220,6 +227,25 @@ function assertCommentContent( } describe("setComment", async () => { + await it("does not create a resolved comment when no comments exist", async () => { + const { client, comments } = fakeClient([]); + + await setComment(client, { ...baseOptions, createIfMissing: false }); + + // Resolution does not introduce a warning that was never posted. + assert.deepEqual(comments, []); + }); + + await it("leaves unrelated comments unchanged when creation is disabled", async () => { + const originalComments = [{ id: 7, body: "unrelated" }]; + const { client, comments } = fakeClient(originalComments); + + await setComment(client, { ...baseOptions, createIfMissing: false }); + + // Unrelated comments neither trigger resolution nor get overwritten. + assert.deepEqual(comments, originalComments); + }); + await it("uses the supplied marker without affecting other comments", async () => { const marker = "custom-warning"; const { client, comments } = fakeClient([ @@ -308,7 +334,7 @@ describe("setComment", async () => { const body = "`CHANGELOG.md` is not modified in this PR. No changelog action is needed."; - await setComment(client, { ...baseOptions, body }); + await setComment(client, { ...baseOptions, body, createIfMissing: false }); // The resolved state replaces the warning on the same marked comment. assert.equal(comments.length, 1); diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index e254221eb5..bcb598872f 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -5,10 +5,12 @@ Creates or updates a pull request comment identified by a marker. The marker is supplied via `--marker` (or the `.github/actions/post-comment` action's `marker` input) and must be non-empty. Supply a plain-text identifier; the CLI wraps it in a hidden HTML comment, prepends it to `--body`, and uses it to find the comment on later runs. +Supply `--create-if-missing` to allow creation; omit it to update existing comments only. Example: ```sh GH_TOKEN= npx tsx ./pr-checks/post-comment.ts \ + --create-if-missing \ --body "The changelog needs updating." \ --marker "my-bot" \ --issue-id 123 \ @@ -29,6 +31,8 @@ export interface Options { body: string; /** Plain-text identifier wrapped in a hidden HTML comment. */ marker: string; + /** Whether to create a comment when no matching marker exists. */ + createIfMissing: boolean; /** The issue/pull request number to post/update the comment on. */ issueId: number; /** The repository to operate on. */ @@ -46,6 +50,7 @@ export function parseOptions(argv?: string[]): Options { options: { body: { type: "string" }, marker: { type: "string" }, + "create-if-missing": { type: "boolean", default: false }, "issue-id": { type: "string" }, repository: { type: "string" }, }, @@ -76,6 +81,7 @@ export function parseOptions(argv?: string[]): Options { return { body: values.body, marker: values.marker, + createIfMissing: values["create-if-missing"], issueId: Number(values["issue-id"]), repository: { owner, repo }, }; @@ -126,6 +132,10 @@ export async function setComment( marker, ); if (existingCommentId === undefined) { + if (!options.createIfMissing) { + console.info("No existing comment found; skipping creation."); + return; + } console.info("No existing comment found; creating a new comment."); await client.rest.issues.createComment({ ...repository, From 1304cc4df1eace8988996316cfd59be1288be6c4 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 11:37:40 -0500 Subject: [PATCH 38/76] Potential fix for pull request finding 'CodeQL / Missing space in string concatenation' Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- pr-checks/post-comment.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index bcb598872f..b9081c5a1d 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -108,7 +108,7 @@ export async function findExistingComment( if (markedComments.length > 1) { console.warn( `Found ${markedComments.length} comments with marker "${formattedMarker}". ` + - "Updating the first one and leaving the others unchanged." + + "Updating the first one and leaving the others unchanged. " + "Use a unique marker for each distinct managed comment to avoid this situation.", ); } From 68a9dcbb350a27ed37657e9060ee307e988fd29c Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Thu, 29 Oct 2026 19:46:00 -0500 Subject: [PATCH 39/76] Prefer `== true` over `!= false` --- .github/actions/post-comment/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index bf8a39b481..56845e2b66 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -29,7 +29,7 @@ runs: env: BODY: ${{ inputs.body }} MARKER: ${{ inputs.marker }} - CREATE_IF_MISSING: ${{ inputs.create-if-missing != 'false' && '--create-if-missing' || '' }} + CREATE_IF_MISSING: ${{ inputs.create-if-missing == 'true' && '--create-if-missing' || '' }} GH_TOKEN: ${{ inputs.token }} ISSUE_ID: ${{ inputs.issue-id || github.event.pull_request.number }} run: | From a5878670a922f942f614d6b5d87680158eeb255b Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 30 Oct 2026 09:28:58 -0500 Subject: [PATCH 40/76] Update `actions/setup-node` action to version 7.1.0 --- .github/workflows/pr-checks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 273abdd0eb..4bfe67b781 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -248,7 +248,7 @@ jobs: ref: main - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: "npm" From 0bc39f9ffcd97a96f3d60d5ca93175c16fd20342 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 30 Oct 2026 09:35:55 -0500 Subject: [PATCH 41/76] Prefer last comment when there are multiple to choose from --- pr-checks/post-comment.test.ts | 2 +- pr-checks/post-comment.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index 63e0f6caad..8bef06104b 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -193,7 +193,7 @@ describe("findExistingComment", async () => { 1, "marker", ); - assert.equal(id, 2); + assert.equal(id, 3); }); await it("returns undefined when no comment matches", async () => { diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index b9081c5a1d..cb8debaa91 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -112,7 +112,7 @@ export async function findExistingComment( "Use a unique marker for each distinct managed comment to avoid this situation.", ); } - return markedComments[0]?.id; + return markedComments.at(-1)?.id; } /** From b25bc2e8e6ff2d5431c8bc575698e3711195b0d4 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 30 Oct 2026 09:43:29 -0500 Subject: [PATCH 42/76] Change `RepositoryNwo` import to `type` --- pr-checks/post-comment.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index cb8debaa91..2495fb1526 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -21,7 +21,7 @@ GH_TOKEN= npx tsx ./pr-checks/post-comment.ts \ import assert from "node:assert/strict"; import { parseArgs } from "node:util"; -import { RepositoryNwo } from "../src/repository"; +import type { RepositoryNwo } from "../src/repository"; import { type ApiClient, getApiClient, resolveToken } from "./api-client"; From 8ba2b06960f40a8fe33efd04d8dd57f2f84d2d24 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 30 Oct 2026 09:49:42 -0500 Subject: [PATCH 43/76] Use `parseRepositoryNwo` instead of splitting manually --- pr-checks/post-comment.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 2495fb1526..c73e153f22 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -21,7 +21,7 @@ GH_TOKEN= npx tsx ./pr-checks/post-comment.ts \ import assert from "node:assert/strict"; import { parseArgs } from "node:util"; -import type { RepositoryNwo } from "../src/repository"; +import { parseRepositoryNwo, type RepositoryNwo } from "../src/repository"; import { type ApiClient, getApiClient, resolveToken } from "./api-client"; @@ -77,13 +77,12 @@ export function parseOptions(argv?: string[]): Options { "Invalid --repository value.", ); - const [owner, repo] = values.repository.split("/"); return { body: values.body, marker: values.marker, createIfMissing: values["create-if-missing"], issueId: Number(values["issue-id"]), - repository: { owner, repo }, + repository: parseRepositoryNwo(values.repository), }; } From eec64423e6e99997acfe14f84696388aa1531037 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 30 Oct 2026 09:50:21 -0500 Subject: [PATCH 44/76] Make precedence explicit with parens --- .github/actions/post-comment/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index 56845e2b66..c60ff7e7ec 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -29,7 +29,7 @@ runs: env: BODY: ${{ inputs.body }} MARKER: ${{ inputs.marker }} - CREATE_IF_MISSING: ${{ inputs.create-if-missing == 'true' && '--create-if-missing' || '' }} + CREATE_IF_MISSING: ${{ (inputs.create-if-missing == 'true' && '--create-if-missing') || '' }} GH_TOKEN: ${{ inputs.token }} ISSUE_ID: ${{ inputs.issue-id || github.event.pull_request.number }} run: | From 97a381d7b614700d7d0cb7f260e0d19f785498c2 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 30 Oct 2026 09:51:41 -0500 Subject: [PATCH 45/76] Split long line --- .github/actions/post-comment/action.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index c60ff7e7ec..5eeba0c7c5 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -10,7 +10,9 @@ inputs: description: "Full comment markdown." required: true create-if-missing: - description: "Create a comment if no matching marker exists. Set to 'false' to update existing comments only." + description: > + Create a comment if no matching marker exists. + Set to 'false' to update existing comments only. required: false default: "true" issue-id: From 9de5eacd23fc707206a4a4119c8090e32b46dfc0 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 30 Oct 2026 09:56:15 -0500 Subject: [PATCH 46/76] Make error a bit clearer and more actionable --- pr-checks/post-comment.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index c73e153f22..bd4f0821e0 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -132,7 +132,9 @@ export async function setComment( ); if (existingCommentId === undefined) { if (!options.createIfMissing) { - console.info("No existing comment found; skipping creation."); + console.info( + "No existing comment found; skipping creation because --create-if-missing wasn't specified.", + ); return; } console.info("No existing comment found; creating a new comment."); From d71593936c378162fb5216c1378201b0630ba423 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Fri, 30 Oct 2026 10:41:05 -0500 Subject: [PATCH 47/76] Replace `--create-if-missing` to `--update-only` `--update-only` is disabled by default, whereas `--create-if-missing` should've been enabled by default but was not. --- .github/actions/post-comment/action.yml | 12 +++++------- .github/workflows/pr-checks.yml | 4 ++-- pr-checks/post-comment.test.ts | 20 ++++++++++---------- pr-checks/post-comment.ts | 15 +++++++-------- 4 files changed, 24 insertions(+), 27 deletions(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index 5eeba0c7c5..2bf84cf289 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -9,12 +9,10 @@ inputs: body: description: "Full comment markdown." required: true - create-if-missing: - description: > - Create a comment if no matching marker exists. - Set to 'false' to update existing comments only. + update-only: + description: Do nothing if no comment with the specified marker exists. required: false - default: "true" + default: "false" issue-id: description: > The issue or pull request number to post/update the comment on. @@ -31,13 +29,13 @@ runs: env: BODY: ${{ inputs.body }} MARKER: ${{ inputs.marker }} - CREATE_IF_MISSING: ${{ (inputs.create-if-missing == 'true' && '--create-if-missing') || '' }} + UPDATE_ONLY: ${{ (inputs.update-only == 'true' && '--update-only') || '' }} GH_TOKEN: ${{ inputs.token }} ISSUE_ID: ${{ inputs.issue-id || github.event.pull_request.number }} run: | npx tsx ./pr-checks/post-comment.ts \ --body "$BODY" \ --marker "$MARKER" \ - $CREATE_IF_MISSING \ + $UPDATE_ONLY \ --issue-id "$ISSUE_ID" \ --repository "$GITHUB_REPOSITORY" diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 4bfe67b781..b72c457742 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -307,7 +307,7 @@ jobs: - name: Mark the CHANGELOG.md concern as resolved if: >- - needs.other-checks.outputs.changelog-modified != 'true' && + needs.other-checks.outputs.changelog-modified == 'false' && !startsWith(github.event.pull_request.head.ref, 'update-v') && !startsWith(github.event.pull_request.head.ref, 'backport-v') && !startsWith(github.event.pull_request.head.ref, 'mergeback/') && @@ -315,7 +315,7 @@ jobs: uses: ./.github/actions/post-comment with: marker: "post-comment:CHANGELOG.md" - create-if-missing: "false" + update-only: true body: | ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` diff --git a/pr-checks/post-comment.test.ts b/pr-checks/post-comment.test.ts index 8bef06104b..db1ce178a4 100644 --- a/pr-checks/post-comment.test.ts +++ b/pr-checks/post-comment.test.ts @@ -49,15 +49,15 @@ describe("parseOptions", async () => { assert.deepEqual(options, { body: "hello", marker: "marker", - createIfMissing: false, + updateOnly: false, issueId: 42, repository: { owner: "github", repo: "codeql-action" }, }); }); - await it("enables creation when --create-if-missing is supplied", () => { - const options = parseOptions([...validFlags, "--create-if-missing"]); - assert.equal(options.createIfMissing, true); + await it("enables update-only mode when --update-only is supplied", () => { + const options = parseOptions([...validFlags, "--update-only"]); + assert.equal(options.updateOnly, true); }); await it("rejects a missing --body", () => { @@ -212,7 +212,7 @@ describe("findExistingComment", async () => { const baseOptions: Options = { body: "hello", marker: "marker", - createIfMissing: true, + updateOnly: false, issueId: 42, repository: { owner: "owner", repo: "repo" }, }; @@ -227,20 +227,20 @@ function assertCommentContent( } describe("setComment", async () => { - await it("does not create a resolved comment when no comments exist", async () => { + await it("does not create a comment in update-only mode when none exists", async () => { const { client, comments } = fakeClient([]); - await setComment(client, { ...baseOptions, createIfMissing: false }); + await setComment(client, { ...baseOptions, updateOnly: true }); // Resolution does not introduce a warning that was never posted. assert.deepEqual(comments, []); }); - await it("leaves unrelated comments unchanged when creation is disabled", async () => { + await it("leaves unrelated comments unchanged in update-only mode", async () => { const originalComments = [{ id: 7, body: "unrelated" }]; const { client, comments } = fakeClient(originalComments); - await setComment(client, { ...baseOptions, createIfMissing: false }); + await setComment(client, { ...baseOptions, updateOnly: true }); // Unrelated comments neither trigger resolution nor get overwritten. assert.deepEqual(comments, originalComments); @@ -334,7 +334,7 @@ describe("setComment", async () => { const body = "`CHANGELOG.md` is not modified in this PR. No changelog action is needed."; - await setComment(client, { ...baseOptions, body, createIfMissing: false }); + await setComment(client, { ...baseOptions, body, updateOnly: true }); // The resolved state replaces the warning on the same marked comment. assert.equal(comments.length, 1); diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index bd4f0821e0..5c39655774 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -5,12 +5,11 @@ Creates or updates a pull request comment identified by a marker. The marker is supplied via `--marker` (or the `.github/actions/post-comment` action's `marker` input) and must be non-empty. Supply a plain-text identifier; the CLI wraps it in a hidden HTML comment, prepends it to `--body`, and uses it to find the comment on later runs. -Supply `--create-if-missing` to allow creation; omit it to update existing comments only. +Supply `--update-only` to suppress creation; omit it to update or create comments. Example: ```sh GH_TOKEN= npx tsx ./pr-checks/post-comment.ts \ - --create-if-missing \ --body "The changelog needs updating." \ --marker "my-bot" \ --issue-id 123 \ @@ -31,8 +30,8 @@ export interface Options { body: string; /** Plain-text identifier wrapped in a hidden HTML comment. */ marker: string; - /** Whether to create a comment when no matching marker exists. */ - createIfMissing: boolean; + /** Whether to only update a comment if a matching marker exists. */ + updateOnly: boolean; /** The issue/pull request number to post/update the comment on. */ issueId: number; /** The repository to operate on. */ @@ -50,7 +49,7 @@ export function parseOptions(argv?: string[]): Options { options: { body: { type: "string" }, marker: { type: "string" }, - "create-if-missing": { type: "boolean", default: false }, + "update-only": { type: "boolean", default: false }, "issue-id": { type: "string" }, repository: { type: "string" }, }, @@ -80,7 +79,7 @@ export function parseOptions(argv?: string[]): Options { return { body: values.body, marker: values.marker, - createIfMissing: values["create-if-missing"], + updateOnly: values["update-only"], issueId: Number(values["issue-id"]), repository: parseRepositoryNwo(values.repository), }; @@ -131,9 +130,9 @@ export async function setComment( marker, ); if (existingCommentId === undefined) { - if (!options.createIfMissing) { + if (options.updateOnly) { console.info( - "No existing comment found; skipping creation because --create-if-missing wasn't specified.", + "No existing comment found; skipping creation because --update-only was specified.", ); return; } From 4094755f8cb29f0af52fd094a32fd3d0db7e96db Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Mon, 2 Nov 2026 09:19:54 -0600 Subject: [PATCH 48/76] Polish `post-comment.ts` usage comment --- pr-checks/post-comment.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/pr-checks/post-comment.ts b/pr-checks/post-comment.ts index 5c39655774..a546c846fe 100644 --- a/pr-checks/post-comment.ts +++ b/pr-checks/post-comment.ts @@ -1,11 +1,14 @@ #!/usr/bin/env npx tsx /* -Creates or updates a pull request comment identified by a marker. The marker -is supplied via `--marker` (or the `.github/actions/post-comment` action's `marker` input) -and must be non-empty. Supply a plain-text identifier; the CLI wraps it in a -hidden HTML comment, prepends it to `--body`, and uses it to find the comment on later runs. -Supply `--update-only` to suppress creation; omit it to update or create comments. +Creates or updates a pull-request comment identified by a marker. + +The marker is supplied via `--marker` and must be a non-empty plain-text identifier. +The CLI wraps the marker in a hidden HTML comment, prepends it to `--body`, +and uses it to find the comment on later runs. + +Supply `--update-only` to suppress creation of comment; omit it +to update or create comments. Example: ```sh From 9d1378fb6e1ce5fdacdfc4a3c1ac38f5b4c5cbd8 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Mon, 2 Nov 2026 09:23:54 -0600 Subject: [PATCH 49/76] Use new `case` expression for evaluating conditional `--update-only` flag --- .github/actions/post-comment/action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/actions/post-comment/action.yml b/.github/actions/post-comment/action.yml index 2bf84cf289..28d202a81d 100644 --- a/.github/actions/post-comment/action.yml +++ b/.github/actions/post-comment/action.yml @@ -29,7 +29,7 @@ runs: env: BODY: ${{ inputs.body }} MARKER: ${{ inputs.marker }} - UPDATE_ONLY: ${{ (inputs.update-only == 'true' && '--update-only') || '' }} + UPDATE_ONLY: ${{ case(inputs.update-only == 'true', '--update-only', '') }} GH_TOKEN: ${{ inputs.token }} ISSUE_ID: ${{ inputs.issue-id || github.event.pull_request.number }} run: | From 05870b623f9da2693ae1ceb146f1810dbc4b26ba Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Tue, 3 Nov 2026 11:13:53 -0600 Subject: [PATCH 50/76] Defer workflow activation to a follow-up PR Keep the post-comment implementation independent of the workflow that loads it from main. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 75 +-------------------------------- 1 file changed, 2 insertions(+), 73 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index b72c457742..5d2b1576f7 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -95,8 +95,6 @@ jobs: contents: read runs-on: ubuntu-latest timeout-minutes: 10 - outputs: - changelog-modified: ${{ steps.changelog-check.outputs.modified }} concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} @@ -185,20 +183,6 @@ jobs: path: ${{ runner.temp }}/repo-size/ if-no-files-found: error - - name: Check for CHANGELOG.md changes - id: changelog-check - if: steps.fetch-base.outcome == 'success' - env: - BASE_SHA: ${{ steps.fetch-base.outputs.merge_base }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - run: | - if ! git diff --exit-code --quiet "$BASE_SHA" "$HEAD_SHA" -- CHANGELOG.md; then - echo "CHANGELOG.md was modified in this PR." - echo "modified=true" >> "$GITHUB_OUTPUT" - else - echo "modified=false" >> "$GITHUB_OUTPUT" - fi - - name: "Backport: Check out base ref" id: checkout-base if: ${{ startsWith(github.head_ref, 'backport-') }} @@ -219,8 +203,8 @@ jobs: exit 1 fi - post-pr-comments: - name: Post PR comments + post-repo-size-comment: + name: Post repo size comment needs: other-checks # Keep write permissions isolated from the job that checks out and tests PR code. This job only # posts the candidate comment body produced by the read-only `pr-checks` job. @@ -240,22 +224,6 @@ jobs: group: check-repo-size-${{ github.event.pull_request.number }} steps: - - name: Checkout repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - # Check out main, not the PR's head, since this job runs with - # `pull-requests: write` permissions and must not execute untrusted code from the PR. - ref: main - - - name: Set up Node.js - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 24 - cache: "npm" - - - name: Install dependencies - run: npm ci --workspace=pr-checks - - name: Download repo size comment uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: @@ -285,42 +253,3 @@ jobs: else echo "Skipping repo size comment because the delta is below the threshold and no sticky comment exists." fi - - - name: Post a warning about modifying CHANGELOG.md - # Release, backport, mergeback, and bundle-update PRs deliberately modify CHANGELOG.md, - # so skip comment management entirely for these automation flows. - if: >- - needs.other-checks.outputs.changelog-modified == 'true' && - !startsWith(github.event.pull_request.head.ref, 'update-v') && - !startsWith(github.event.pull_request.head.ref, 'backport-v') && - !startsWith(github.event.pull_request.head.ref, 'mergeback/') && - !startsWith(github.event.pull_request.head.ref, 'update-bundle/') - uses: ./.github/actions/post-comment - with: - marker: "post-comment:CHANGELOG.md" - body: | - ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. - Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` - file will be automatically generated from those change-notes. - See [`unreleased-change-notes/README.md`](https://github.com/github/codeql-action/blob/main/unreleased-change-notes/README.md) for more information. - token: ${{ secrets.GITHUB_TOKEN }} - - - name: Mark the CHANGELOG.md concern as resolved - if: >- - needs.other-checks.outputs.changelog-modified == 'false' && - !startsWith(github.event.pull_request.head.ref, 'update-v') && - !startsWith(github.event.pull_request.head.ref, 'backport-v') && - !startsWith(github.event.pull_request.head.ref, 'mergeback/') && - !startsWith(github.event.pull_request.head.ref, 'update-bundle/') - uses: ./.github/actions/post-comment - with: - marker: "post-comment:CHANGELOG.md" - update-only: true - body: | - ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. - Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` - file will be automatically generated from those change-notes. - See [`unreleased-change-notes/README.md`](https://github.com/github/codeql-action/blob/main/unreleased-change-notes/README.md) for more information. - - **Edit:** `CHANGELOG.md` is no longer modified in this PR. This concern is resolved. - token: ${{ secrets.GITHUB_TOKEN }} From 29ddace71d5505249af76e7f6d1476e04917c2b1 Mon Sep 17 00:00:00 2001 From: "Michael B. Gale" Date: Wed, 4 Nov 2026 13:14:15 +0000 Subject: [PATCH 51/76] Move `Feature` enum to a separate file --- src/feature-flags.ts | 104 +--------------------------------- src/feature-flags/features.ts | 100 ++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 101 deletions(-) create mode 100644 src/feature-flags/features.ts diff --git a/src/feature-flags.ts b/src/feature-flags.ts index 20b7a0263f..3d05cbe9db 100644 --- a/src/feature-flags.ts +++ b/src/feature-flags.ts @@ -6,6 +6,7 @@ import * as semver from "semver"; import { getApiClient } from "./api-client"; import type { CodeQL } from "./codeql"; import * as defaults from "./defaults.json"; +import { Feature } from "./feature-flags/features"; import { Logger } from "./logging"; import { CODEQL_OVERLAY_MINIMUM_VERSION, @@ -21,6 +22,8 @@ import { RepositoryNwo } from "./repository"; import { ToolsFeature } from "./tools-features"; import * as util from "./util"; +export { Feature } from "./feature-flags/features"; + const DEFAULT_VERSION_FEATURE_FLAG_PREFIX = "default_codeql_version_"; const DEFAULT_VERSION_FEATURE_FLAG_SUFFIX = "_enabled"; @@ -61,107 +64,6 @@ export interface CodeQLDefaultVersionInfo { toolsFeatureFlagsValid?: boolean; } -/** - * Features as named by the GitHub API endpoint. - * - * Do not include the `codeql_action_` prefix as this is stripped by the API - * endpoint. - * - * Legacy features should end with `_enabled`. - */ -export enum Feature { - /** Allows supported properties of configuration files to be merged. */ - AllowMergeConfigFiles = "allow_merge_config_files", - /** Controls whether we allow multiple values for the `analysis-kinds` input. */ - AllowMultipleAnalysisKinds = "allow_multiple_analysis_kinds", - /** - * Whether to check for unsupported traced analysis. Primarily intended as an override to disable - * the check if it causes problems somehow. - */ - CheckUnsupportedTracedAnalysis = "check_unsupported_traced_analysis", - /** Whether to allow the `config-file` input to be specified via a repository property. */ - ConfigFileRepositoryProperty = "config_file_repository_property", - CppDependencyInstallation = "cpp_dependency_installation_enabled", - CsharpCacheBuildModeNone = "csharp_cache_bmn", - CsharpNewCacheKey = "csharp_new_cache_key", - DiffInformedQueries = "diff_informed_queries", - DisableCsharpBuildless = "disable_csharp_buildless", - DisableJavaBuildlessEnabled = "disable_java_buildless_enabled", - DisableKotlinAnalysisEnabled = "disable_kotlin_analysis_enabled", - ExportDiagnosticsEnabled = "export_diagnostics_enabled", - /** - * Emergency override that forces the CodeQL CLI to use the JGit-based Git backend instead of its - * default backend selection. - */ - ForceJGit = "force_jgit", - ForceNightly = "force_nightly", - IgnoreGeneratedFiles = "ignore_generated_files", - JavaNetworkDebugging = "java_network_debugging", - OverlayAnalysis = "overlay_analysis", - OverlayAnalysisCodeScanningCpp = "overlay_analysis_code_scanning_cpp", - OverlayAnalysisCodeScanningCsharp = "overlay_analysis_code_scanning_csharp", - OverlayAnalysisCodeScanningGo = "overlay_analysis_code_scanning_go", - OverlayAnalysisCodeScanningJava = "overlay_analysis_code_scanning_java", - OverlayAnalysisCodeScanningJavascript = "overlay_analysis_code_scanning_javascript", - OverlayAnalysisCodeScanningPython = "overlay_analysis_code_scanning_python", - OverlayAnalysisCodeScanningRuby = "overlay_analysis_code_scanning_ruby", - OverlayAnalysisCpp = "overlay_analysis_cpp", - OverlayAnalysisCsharp = "overlay_analysis_csharp", - OverlayAnalysisGo = "overlay_analysis_go", - OverlayAnalysisJava = "overlay_analysis_java", - OverlayAnalysisJavascript = "overlay_analysis_javascript", - /** - * Lowers the overlay minimum available disk space to 8 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk8Gb = "overlay_analysis_min_disk_8_gb", - /** - * Lowers the overlay minimum available disk space to 9 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk9Gb = "overlay_analysis_min_disk_9_gb", - /** - * Lowers the overlay minimum available disk space to 10 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk10Gb = "overlay_analysis_min_disk_10_gb", - /** - * Lowers the overlay minimum available disk space to 11 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk11Gb = "overlay_analysis_min_disk_11_gb", - /** - * Lowers the overlay minimum available disk space to 12 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk12Gb = "overlay_analysis_min_disk_12_gb", - /** - * Lowers the overlay minimum available disk space to 13 GB. The lowest enabled limit wins; if - * none are enabled, the default applies. - */ - OverlayAnalysisMinDisk13Gb = "overlay_analysis_min_disk_13_gb", - OverlayAnalysisPython = "overlay_analysis_python", - OverlayAnalysisRuby = "overlay_analysis_ruby", - /** Controls whether hardware checks are skipped for overlay analysis. */ - OverlayAnalysisSkipResourceChecks = "overlay_analysis_skip_resource_checks", - /** Controls whether the Actions cache is checked for overlay build outcomes. */ - OverlayAnalysisStatusCheck = "overlay_analysis_status_check", - /** Controls whether overlay build failures on the default branch are stored in the Actions cache. */ - OverlayAnalysisStatusSave = "overlay_analysis_status_save", - QaTelemetryEnabled = "qa_telemetry_enabled", - /** Whether we should fail early if we detect that traced analysis is unsupported. */ - AbortUnsupportedTracedAnalysis = "abort_unsupported_traced_analysis", - /** Routes (some) API requests through the registry proxy. */ - ProxyApiRequests = "proxy_api_requests", - /** Note that this currently only disables baseline file coverage information. */ - SkipFileCoverageOnPrs = "skip_file_coverage_on_prs", - StartProxyUseFeaturesRelease = "start_proxy_use_features_release", - /** Whether to allow the `tools` input to be specified via a repository property. */ - ToolsRepositoryProperty = "tools_repository_property", - UploadOverlayDbToApi = "upload_overlay_db_to_api", - ValidateDbConfig = "validate_db_config", -} - export type FeatureConfig = { /** * Default value in environments where the feature flags API is not available, diff --git a/src/feature-flags/features.ts b/src/feature-flags/features.ts new file mode 100644 index 0000000000..795f8f57ba --- /dev/null +++ b/src/feature-flags/features.ts @@ -0,0 +1,100 @@ +/** + * Features as named by the GitHub API endpoint. + * + * Do not include the `codeql_action_` prefix as this is stripped by the API + * endpoint. + * + * Legacy features should end with `_enabled`. + */ +export enum Feature { + /** Allows supported properties of configuration files to be merged. */ + AllowMergeConfigFiles = "allow_merge_config_files", + /** Controls whether we allow multiple values for the `analysis-kinds` input. */ + AllowMultipleAnalysisKinds = "allow_multiple_analysis_kinds", + /** + * Whether to check for unsupported traced analysis. Primarily intended as an override to disable + * the check if it causes problems somehow. + */ + CheckUnsupportedTracedAnalysis = "check_unsupported_traced_analysis", + /** Whether to allow the `config-file` input to be specified via a repository property. */ + ConfigFileRepositoryProperty = "config_file_repository_property", + CppDependencyInstallation = "cpp_dependency_installation_enabled", + CsharpCacheBuildModeNone = "csharp_cache_bmn", + CsharpNewCacheKey = "csharp_new_cache_key", + DiffInformedQueries = "diff_informed_queries", + DisableCsharpBuildless = "disable_csharp_buildless", + DisableJavaBuildlessEnabled = "disable_java_buildless_enabled", + DisableKotlinAnalysisEnabled = "disable_kotlin_analysis_enabled", + ExportDiagnosticsEnabled = "export_diagnostics_enabled", + /** + * Emergency override that forces the CodeQL CLI to use the JGit-based Git backend instead of its + * default backend selection. + */ + ForceJGit = "force_jgit", + ForceNightly = "force_nightly", + IgnoreGeneratedFiles = "ignore_generated_files", + JavaNetworkDebugging = "java_network_debugging", + OverlayAnalysis = "overlay_analysis", + OverlayAnalysisCodeScanningCpp = "overlay_analysis_code_scanning_cpp", + OverlayAnalysisCodeScanningCsharp = "overlay_analysis_code_scanning_csharp", + OverlayAnalysisCodeScanningGo = "overlay_analysis_code_scanning_go", + OverlayAnalysisCodeScanningJava = "overlay_analysis_code_scanning_java", + OverlayAnalysisCodeScanningJavascript = "overlay_analysis_code_scanning_javascript", + OverlayAnalysisCodeScanningPython = "overlay_analysis_code_scanning_python", + OverlayAnalysisCodeScanningRuby = "overlay_analysis_code_scanning_ruby", + OverlayAnalysisCpp = "overlay_analysis_cpp", + OverlayAnalysisCsharp = "overlay_analysis_csharp", + OverlayAnalysisGo = "overlay_analysis_go", + OverlayAnalysisJava = "overlay_analysis_java", + OverlayAnalysisJavascript = "overlay_analysis_javascript", + /** + * Lowers the overlay minimum available disk space to 8 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk8Gb = "overlay_analysis_min_disk_8_gb", + /** + * Lowers the overlay minimum available disk space to 9 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk9Gb = "overlay_analysis_min_disk_9_gb", + /** + * Lowers the overlay minimum available disk space to 10 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk10Gb = "overlay_analysis_min_disk_10_gb", + /** + * Lowers the overlay minimum available disk space to 11 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk11Gb = "overlay_analysis_min_disk_11_gb", + /** + * Lowers the overlay minimum available disk space to 12 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk12Gb = "overlay_analysis_min_disk_12_gb", + /** + * Lowers the overlay minimum available disk space to 13 GB. The lowest enabled limit wins; if + * none are enabled, the default applies. + */ + OverlayAnalysisMinDisk13Gb = "overlay_analysis_min_disk_13_gb", + OverlayAnalysisPython = "overlay_analysis_python", + OverlayAnalysisRuby = "overlay_analysis_ruby", + /** Controls whether hardware checks are skipped for overlay analysis. */ + OverlayAnalysisSkipResourceChecks = "overlay_analysis_skip_resource_checks", + /** Controls whether the Actions cache is checked for overlay build outcomes. */ + OverlayAnalysisStatusCheck = "overlay_analysis_status_check", + /** Controls whether overlay build failures on the default branch are stored in the Actions cache. */ + OverlayAnalysisStatusSave = "overlay_analysis_status_save", + QaTelemetryEnabled = "qa_telemetry_enabled", + /** Whether we should fail early if we detect that traced analysis is unsupported. */ + AbortUnsupportedTracedAnalysis = "abort_unsupported_traced_analysis", + /** Routes (some) API requests through the registry proxy. */ + ProxyApiRequests = "proxy_api_requests", + /** Note that this currently only disables baseline file coverage information. */ + SkipFileCoverageOnPrs = "skip_file_coverage_on_prs", + StartProxyUseFeaturesRelease = "start_proxy_use_features_release", + /** Whether to allow the `tools` input to be specified via a repository property. */ + ToolsRepositoryProperty = "tools_repository_property", + UploadOverlayDbToApi = "upload_overlay_db_to_api", + ValidateDbConfig = "validate_db_config", +} From e7ce43a4dc692cf703df2389513106a0bd62134e Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Tue, 3 Nov 2026 13:33:07 +0000 Subject: [PATCH 52/76] Log how long deleting each CodeQL version from the toolcache takes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- lib/entry-points.js | 5 ++++- src/tools-download.ts | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 952c615417..0d97fe4248 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -184864,13 +184864,16 @@ async function deleteToolcacheBundles({ } const versionDirectory = path12.join(toolDirectory, entry.name); try { + const deletionStart = import_perf_hooks3.performance.now(); await fs15.promises.rm(versionDirectory, { force: true, recursive: true }); deletedVersions.push(entry.name); logger2.info( - `Deleted the CodeQL tools at '${versionDirectory}' from the toolcache to free up disk space.` + `Deleted the CodeQL tools at '${versionDirectory}' from the toolcache to free up disk space (${formatDuration( + durationMsSince(deletionStart) + )}).` ); } catch (e) { failed = true; diff --git a/src/tools-download.ts b/src/tools-download.ts index a92dad0acf..a5b5a5a0da 100644 --- a/src/tools-download.ts +++ b/src/tools-download.ts @@ -342,13 +342,16 @@ export async function deleteToolcacheBundles({ const versionDirectory = path.join(toolDirectory, entry.name); try { + const deletionStart = performance.now(); await fs.promises.rm(versionDirectory, { force: true, recursive: true, }); deletedVersions.push(entry.name); logger.info( - `Deleted the CodeQL tools at '${versionDirectory}' from the toolcache to free up disk space.`, + `Deleted the CodeQL tools at '${versionDirectory}' from the toolcache to free up disk space (${formatDuration( + durationMsSince(deletionStart), + )}).`, ); } catch (e) { failed = true; From e70c0414bf2f50ae4617cac7ffe7db16cd2bf06b Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Wed, 4 Nov 2026 14:31:49 +0000 Subject: [PATCH 53/76] Record how long the toolcache cleanup takes in telemetry Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- lib/entry-points.js | 3 ++- src/setup-codeql.test.ts | 53 +++++++++++++++++++++++++++++++++++----- src/setup-codeql.ts | 3 ++- 3 files changed, 51 insertions(+), 8 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 0d97fe4248..0bceda727a 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -185372,13 +185372,14 @@ async function tryDeleteToolcacheBundles({ if (!isGitHubHostedRunner(env) || !isToolcacheOnWorkspaceFilesystem(logger2)) { return; } + const startTime = import_perf_hooks4.performance.now(); const result = await deleteToolcacheBundles({ env, logger: logger2 }); addNoLanguageDiagnostic( void 0, makeTelemetryDiagnostic( "codeql-action/toolcache-bundle-cleanup", "Toolcache CodeQL bundle cleanup", - { ...result } + { ...result, durationMs: durationMsSince(startTime) } ) ); } diff --git a/src/setup-codeql.test.ts b/src/setup-codeql.test.ts index a244501c38..e8c64c6166 100644 --- a/src/setup-codeql.test.ts +++ b/src/setup-codeql.test.ts @@ -1821,7 +1821,8 @@ function createToolcacheEntry( /** * Stubs out the download and the diagnostic sink, then downloads the CodeQL tools. * - * @returns the extraction directory and the toolcache cleanup diagnostic, if emitted. + * @returns the extraction directory and, if the toolcache cleanup diagnostic was emitted, the + * cleanup duration it reports and its other attributes. */ async function runDownloadCodeQL( toolcacheRoot: string, @@ -1837,6 +1838,7 @@ async function runDownloadCodeQL( ): Promise<{ codeqlFolder: string; cleanupDiagnostic: toolsDownload.ToolcacheCleanupResult | undefined; + cleanupDurationMs: number | undefined; }> { stubDownloadAndExtract(); const addDiagnostic = sinon.stub(diagnostics, "addNoLanguageDiagnostic"); @@ -1866,11 +1868,21 @@ async function runDownloadCodeQL( .map((call) => call.args[1]) .find((d) => d.source?.id === "codeql-action/toolcache-bundle-cleanup"); - return { - codeqlFolder, - cleanupDiagnostic: diagnostic?.attributes as - toolsDownload.ToolcacheCleanupResult | undefined, - }; + if (diagnostic === undefined) { + return { + codeqlFolder, + cleanupDiagnostic: undefined, + cleanupDurationMs: undefined, + }; + } + + // The duration varies between runs, so split it out to let tests compare the other attributes + // exactly. + const { durationMs, ...cleanupDiagnostic } = + diagnostic.attributes as toolsDownload.ToolcacheCleanupResult & { + durationMs: number; + }; + return { codeqlFolder, cleanupDiagnostic, cleanupDurationMs: durationMs }; } /** @@ -1991,6 +2003,35 @@ test.serial( }, ); +test.serial( + "downloadCodeQLBundle reports the total time taken to clean up the toolcache", + async (t) => { + await withTmpDir(async (tmpDir) => { + setupActionsVars(tmpDir, tmpDir); + + createToolcacheEntry(tmpDir, "CodeQL", CLEANUP_CLI_VERSION); + createToolcacheEntry(tmpDir, "CodeQL", CLEANUP_STALE_VERSION); + + // Advance the clock by 1.5s each time a path is deleted, so that deleting both versions + // takes 3s. + let elapsedMs = 1000; + sinon.stub(performance, "now").callsFake(() => elapsedMs); + const rm = fs.promises.rm; + sinon.stub(fs.promises, "rm").callsFake(async (...args) => { + elapsedMs += 1500; + await rm(...args); + }); + + const { cleanupDurationMs } = await runDownloadCodeQL( + tmpDir, + CLEANUP_BUNDLE_VERSION, + ); + + t.is(cleanupDurationMs, 3000); + }); + }, +); + test.serial( "downloadCodeQLBundle reports no deleted versions when the toolcache has no CodeQL bundles", async (t) => { diff --git a/src/setup-codeql.ts b/src/setup-codeql.ts index d70e1f5087..b87b81bdc0 100644 --- a/src/setup-codeql.ts +++ b/src/setup-codeql.ts @@ -814,6 +814,7 @@ async function tryDeleteToolcacheBundles({ return; } + const startTime = performance.now(); const result = await deleteToolcacheBundles({ env, logger }); addNoLanguageDiagnostic( @@ -821,7 +822,7 @@ async function tryDeleteToolcacheBundles({ makeTelemetryDiagnostic( "codeql-action/toolcache-bundle-cleanup", "Toolcache CodeQL bundle cleanup", - { ...result }, + { ...result, durationMs: util.durationMsSince(startTime) }, ), ); } From 8e42d3873f0cc4a734ca710926d6d7a69713262e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:49:21 +0000 Subject: [PATCH 54/76] Update changelog and version after v4.39.3 --- CHANGELOG.md | 4 ++++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b9c1382c35..091c04cd4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ See the [releases page](https://github.com/github/codeql-action/releases) for the relevant changes to the CodeQL CLI and language packs. +## [UNRELEASED] + +No user facing changes. + ## 4.39.3 - 04 Nov 2026 - Fixed diff-informed alert filtering incorrectly removing alerts in changed files whose paths contain spaces, special characters, or non-ASCII characters. [#4283](https://github.com/github/codeql-action/pull/4283) diff --git a/package-lock.json b/package-lock.json index ca703da546..12306cdd7f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "codeql", - "version": "4.39.3", + "version": "4.39.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "codeql", - "version": "4.39.3", + "version": "4.39.4", "license": "MIT", "workspaces": [ "pr-checks" diff --git a/package.json b/package.json index 8d917bf060..5fed5cccd4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "codeql", - "version": "4.39.3", + "version": "4.39.4", "private": true, "description": "CodeQL action", "scripts": { From d11b2246b19550e36c2fc335ba4a40632d6bc2ca Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:49:37 +0000 Subject: [PATCH 55/76] Rebuild --- lib/entry-points.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 952c615417..9297a87842 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -178724,7 +178724,7 @@ function getDiffRangesJsonFilePath(env = getEnv()) { return path2.join(getTemporaryDirectory(env), PR_DIFF_RANGE_JSON_FILENAME); } function getActionVersion() { - return "4.39.3"; + return "4.39.4"; } function getWorkflowEventName(env = getEnv()) { return env.getRequired("GITHUB_EVENT_NAME" /* GITHUB_EVENT_NAME */); From d2a785ca9cadb30d186f903821b162c12686db95 Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Fri, 6 Nov 2026 16:58:25 +0000 Subject: [PATCH 56/76] Remove `macos-14-xlarge` from `codeql` workflow Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/codeql.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index efbb246fc9..cc7d3de991 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -79,7 +79,6 @@ jobs: - ubuntu-24.04 - windows-2022 - windows-2025 - - macos-14-xlarge - macos-15-xlarge tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }} runs-on: ${{ matrix.os }} From 822e91c47d31a1c049c9bd341df1269c8d6bc59c Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Fri, 6 Nov 2026 18:24:29 +0000 Subject: [PATCH 57/76] Exclude Notify from required checks Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- pr-checks/excluded.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pr-checks/excluded.yml b/pr-checks/excluded.yml index bac0b4acee..2158e8d479 100644 --- a/pr-checks/excluded.yml +++ b/pr-checks/excluded.yml @@ -24,3 +24,5 @@ is: # PRs), so requiring them would block the PRs they don't run on. - "github-advanced-security" - "License compliance check" + # Only runs when a PR is removed from the merge queue. + - "Notify" From 9d4eb28961f1f3ab4fe71daf35ea25bd89f7d3eb Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Mon, 9 Nov 2026 13:59:30 +0000 Subject: [PATCH 58/76] Rename `linux-arm64` PR check to `runner-images` Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../workflows/{__linux-arm64.yml => __runner-images.yml} | 8 ++++---- pr-checks/checks/{linux-arm64.yml => runner-images.yml} | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) rename .github/workflows/{__linux-arm64.yml => __runner-images.yml} (94%) rename pr-checks/checks/{linux-arm64.yml => runner-images.yml} (98%) diff --git a/.github/workflows/__linux-arm64.yml b/.github/workflows/__runner-images.yml similarity index 94% rename from .github/workflows/__linux-arm64.yml rename to .github/workflows/__runner-images.yml index 02dab69f9f..c14782be6e 100644 --- a/.github/workflows/__linux-arm64.yml +++ b/.github/workflows/__runner-images.yml @@ -3,7 +3,7 @@ # pr-checks/sync.sh # to regenerate this file. -name: PR Check - Linux Arm64 +name: PR Check - Runner images env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GO111MODULE: auto @@ -47,16 +47,16 @@ defaults: shell: bash concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} - group: linux-arm64-${{github.ref}}-${{inputs.dotnet-version}}-${{inputs.go-version}} + group: runner-images-${{github.ref}}-${{inputs.dotnet-version}}-${{inputs.go-version}} jobs: - linux-arm64: + runner-images: strategy: fail-fast: false matrix: include: - os: ubuntu-24.04-arm version: nightly-latest - name: Linux Arm64 + name: Runner images if: github.triggering_actor != 'dependabot[bot]' permissions: contents: read diff --git a/pr-checks/checks/linux-arm64.yml b/pr-checks/checks/runner-images.yml similarity index 98% rename from pr-checks/checks/linux-arm64.yml rename to pr-checks/checks/runner-images.yml index 29d3eea41e..e8b22e74ae 100644 --- a/pr-checks/checks/linux-arm64.yml +++ b/pr-checks/checks/runner-images.yml @@ -1,4 +1,4 @@ -name: "Linux Arm64" +name: "Runner images" description: "An end-to-end integration test running on a Linux Arm64 runner, checking that the native linux-arm64 CodeQL bundle is downloaded and can analyze interpreted and compiled code" operatingSystems: - os: ubuntu From 02e8a5ded2a965894b7463d7d8ee86272fd4c14f Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Mon, 9 Nov 2026 14:01:20 +0000 Subject: [PATCH 59/76] Run `runner-images` check on the GitHub-hosted runner images with `linked` Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/__runner-images.yml | 26 ++++++++++++++-- pr-checks/checks/runner-images.yml | 45 ++++++++++++++++++++++----- 2 files changed, 62 insertions(+), 9 deletions(-) diff --git a/.github/workflows/__runner-images.yml b/.github/workflows/__runner-images.yml index c14782be6e..8c7ce02f7c 100644 --- a/.github/workflows/__runner-images.yml +++ b/.github/workflows/__runner-images.yml @@ -54,8 +54,30 @@ jobs: fail-fast: false matrix: include: + - os: ubuntu-22.04 + version: linked + - os: ubuntu-22.04-arm + version: linked + - os: ubuntu-24.04 + version: linked - os: ubuntu-24.04-arm - version: nightly-latest + version: linked + - os: ubuntu-26.04 + version: linked + - os: ubuntu-26.04-arm + version: linked + - os: windows-2022 + version: linked + - os: windows-2025 + version: linked + - os: macos-15-large + version: linked + - os: macos-15-xlarge + version: linked + - os: macos-26-large + version: linked + - os: macos-26-xlarge + version: linked name: Runner images if: github.triggering_actor != 'dependabot[bot]' permissions: @@ -102,5 +124,5 @@ jobs: echo "Found database for $lang" done env: - LANGUAGES: cpp,csharp,go,java,javascript,python,ruby + LANGUAGES: cpp,csharp,go,java,javascript,python,ruby${{ startsWith(matrix.os, 'macos') && ',swift' || '' }} CODEQL_ACTION_TEST_MODE: true diff --git a/pr-checks/checks/runner-images.yml b/pr-checks/checks/runner-images.yml index e8b22e74ae..70354e9ada 100644 --- a/pr-checks/checks/runner-images.yml +++ b/pr-checks/checks/runner-images.yml @@ -1,18 +1,49 @@ name: "Runner images" -description: "An end-to-end integration test running on a Linux Arm64 runner, checking that the native linux-arm64 CodeQL bundle is downloaded and can analyze interpreted and compiled code" +description: "An end-to-end integration test checking that CodeQL can analyze interpreted and compiled code on the GitHub-hosted runner images" +# This check runs on each image listed in +# https://github.com/actions/runner-images#available-images, except for: +# - `ubuntu-slim`, which is intended for lightweight jobs rather than builds like this one. +# - `windows-11-arm`, since CodeQL doesn't support Windows on Arm64. +# - `xcode-27`, a preview image that the `unsupported-macos` check runs on. operatingSystems: + # The Ubuntu 22.04 images have brownouts from 23 March 2027 and are retired on 17 April 2027, so + # remove them before the brownouts start. + # See https://github.com/actions/runner-images/issues/14254. + - os: ubuntu + runner-image: ubuntu-22.04 + - os: ubuntu + runner-image: ubuntu-22.04-arm + - os: ubuntu + runner-image: ubuntu-24.04 - os: ubuntu runner-image: ubuntu-24.04-arm -# The native linux-arm64 CodeQL bundle is only available in recent CLI releases, so we restrict this -# check to `nightly-latest`, which is guaranteed to ship it. Older stable versions do not have an -# arm64 asset, and `prepare-test` would resolve an x64 bundle URL for them on this runner. + - os: ubuntu + runner-image: ubuntu-26.04 + - os: ubuntu + runner-image: ubuntu-26.04-arm + - os: windows + runner-image: windows-2022 + - os: windows + runner-image: windows-2025 + # Use larger runners for macOS to keep these jobs off the critical path. + - os: macos + runner-image: macos-15-large + - os: macos + runner-image: macos-15-xlarge + - os: macos + runner-image: macos-26-large + - os: macos + runner-image: macos-26-xlarge +# Other PR checks cover the supported CodeQL versions, so this check only tests the linked version. +# Linux Arm64 bundles are only available for CodeQL 2.27.0 and later, so older stable versions +# can't run on the Arm64 images. versions: - - nightly-latest + - linked installGo: true installDotNet: true -# The set of languages CodeQL supports on this platform, excluding Swift (macOS only). +# The languages to build and analyze. CodeQL only supports Swift on macOS. env: - LANGUAGES: cpp,csharp,go,java,javascript,python,ruby + LANGUAGES: "cpp,csharp,go,java,javascript,python,ruby${{ startsWith(matrix.os, 'macos') && ',swift' || '' }}" steps: - uses: ./../action/init with: From 3a7f564e339a3d339dd12be916292b352bc42b3e Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Mon, 9 Nov 2026 14:14:41 +0000 Subject: [PATCH 60/76] Rerun failed `runner-images` jobs in the Deflake workflow Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/deflake.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/deflake.yml b/.github/workflows/deflake.yml index 27024b3780..b4089fc35e 100644 --- a/.github/workflows/deflake.yml +++ b/.github/workflows/deflake.yml @@ -61,6 +61,7 @@ on: - "PR Check - Remote config file" - "PR Check - Resolve environment" - "PR Check - Ruby analysis" + - "PR Check - Runner images" - "PR Check - Rust analysis" - "PR Check - Split workflow" - "PR Check - Start proxy" From b5a363211902ad0b34a96d743184d76dc3d2f113 Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Mon, 9 Nov 2026 14:02:22 +0000 Subject: [PATCH 61/76] Run `analyze-javascript` only on `ubuntu-26.04` Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/codeql.yml | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index cc7d3de991..bac0ba9c9a 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -74,14 +74,8 @@ jobs: strategy: fail-fast: false matrix: - os: - - ubuntu-22.04 - - ubuntu-24.04 - - windows-2022 - - windows-2025 - - macos-15-xlarge tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }} - runs-on: ${{ matrix.os }} + runs-on: ubuntu-26.04 permissions: contents: read @@ -107,7 +101,7 @@ jobs: uses: ./analyze with: category: "/language:javascript" - upload: ${{ (matrix.os == 'ubuntu-24.04' && !matrix.tools && github.event_name != 'merge_group' && 'always' ) || 'never' }} + upload: ${{ (!matrix.tools && github.event_name != 'merge_group' && 'always' ) || 'never' }} analyze-other: if: github.triggering_actor != 'dependabot[bot]' From 97d0cc029d68005e4403a9cf72f69d1d226797dd Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Mon, 9 Nov 2026 14:56:24 +0000 Subject: [PATCH 62/76] Only run `analyze-javascript` with the default CodeQL bundle Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/codeql.yml | 57 +----------------------------------- 1 file changed, 1 insertion(+), 56 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index bac0ba9c9a..73045aedb4 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -19,62 +19,8 @@ env: CODEQL_ACTION_TESTING_ENVIRONMENT: codeql-action-pr-checks jobs: - # Identify the CodeQL tool versions to use in the analysis job. - check-codeql-versions: - if: github.triggering_actor != 'dependabot[bot]' - runs-on: ubuntu-26.04 - outputs: - versions: ${{ steps.compare.outputs.versions }} - - permissions: - contents: read - # We currently need `security-events: read` to access feature flags. - security-events: read - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Set up default CodeQL bundle - id: setup-default - uses: ./setup-codeql - - name: Set up linked CodeQL bundle - id: setup-linked - uses: ./setup-codeql - with: - tools: linked - - name: Compare default and linked CodeQL bundle versions - id: compare - env: - CODEQL_DEFAULT: ${{ steps.setup-default.outputs.codeql-path }} - CODEQL_LINKED: ${{ steps.setup-linked.outputs.codeql-path }} - run: | - CODEQL_VERSION_DEFAULT="$("$CODEQL_DEFAULT" version --format terse)" - CODEQL_VERSION_LINKED="$("$CODEQL_LINKED" version --format terse)" - echo "Default CodeQL bundle version is $CODEQL_VERSION_DEFAULT" - echo "Linked CodeQL bundle version is $CODEQL_VERSION_LINKED" - - # If we're running on a pull request, run with both bundles, even if `tools: linked` would - # be the same as `tools: null`. This allows us to make the job for each of the bundles a - # required status check. - # - # If we're running on push or schedule, then we can skip running with `tools: linked` when it would be - # the same as running with `tools: null`. - if [[ "$GITHUB_EVENT_NAME" != "pull_request" && "$GITHUB_EVENT_NAME" != "merge_group" && "$CODEQL_VERSION_DEFAULT" == "$CODEQL_VERSION_LINKED" ]]; then - VERSIONS_JSON='[null]' - else - VERSIONS_JSON='[null, "linked"]' - fi - - # Output a JSON-encoded list with the distinct versions to test against. - echo "Suggested matrix config for analysis job: $VERSIONS_JSON" - echo "versions=${VERSIONS_JSON}" >> $GITHUB_OUTPUT - analyze-javascript: if: github.triggering_actor != 'dependabot[bot]' - needs: [check-codeql-versions] - strategy: - fail-fast: false - matrix: - tools: ${{ fromJson(needs.check-codeql-versions.outputs.versions) }} runs-on: ubuntu-26.04 permissions: @@ -90,7 +36,6 @@ jobs: with: languages: javascript config-file: ./.github/codeql/codeql-config-javascript.yml - tools: ${{ matrix.tools }} # confirm steps.init.outputs.codeql-path points to the codeql binary - name: Print CodeQL Version run: > @@ -101,7 +46,7 @@ jobs: uses: ./analyze with: category: "/language:javascript" - upload: ${{ (!matrix.tools && github.event_name != 'merge_group' && 'always' ) || 'never' }} + upload: ${{ (github.event_name != 'merge_group' && 'always') || 'never' }} analyze-other: if: github.triggering_actor != 'dependabot[bot]' From cfb394096693c34f35d26029562491b6e6b7a3b4 Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Mon, 9 Nov 2026 17:13:08 +0000 Subject: [PATCH 63/76] Respect `use-all-platform-bundle` for the latest nightly in `prepare-test` Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/prepare-test/action.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/actions/prepare-test/action.yml b/.github/actions/prepare-test/action.yml index 4c11ec4929..1276aca8eb 100644 --- a/.github/actions/prepare-test/action.yml +++ b/.github/actions/prepare-test/action.yml @@ -36,7 +36,14 @@ runs: set -e # Fail this Action if `gh release list` fails. if [[ "$VERSION" == "nightly" || "$VERSION" == "nightly-latest" ]]; then - echo "tools-url=nightly" >> "$GITHUB_OUTPUT" + if [[ "$USE_ALL_PLATFORM_BUNDLE" == "true" ]]; then + # With `tools: nightly`, the Action downloads the bundle for the runner's platform, so look + # up the latest nightly release here to get its all-platform bundle instead. + tag=$(gh release list --repo dsp-testing/codeql-cli-nightlies --limit 1 --json tagName --jq '.[0].tagName') + echo "tools-url=https://github.com/dsp-testing/codeql-cli-nightlies/releases/download/$tag/codeql-bundle.tar.gz" >> "$GITHUB_OUTPUT" + else + echo "tools-url=nightly" >> "$GITHUB_OUTPUT" + fi exit 0 elif [[ "$VERSION" == "linked" ]]; then echo "tools-url=linked" >> "$GITHUB_OUTPUT" From 91bae3ac6822bcd997cfe984db021f65dfef41b4 Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Mon, 9 Nov 2026 17:13:32 +0000 Subject: [PATCH 64/76] Check that the `all-platform-bundle` PR check uses an all-platform bundle Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/__all-platform-bundle.yml | 12 ++++++++++++ pr-checks/checks/all-platform-bundle.yml | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/.github/workflows/__all-platform-bundle.yml b/.github/workflows/__all-platform-bundle.yml index 22635a0d14..a2d8c1abb3 100644 --- a/.github/workflows/__all-platform-bundle.yml +++ b/.github/workflows/__all-platform-bundle.yml @@ -92,6 +92,18 @@ jobs: # Swift is not supported on Ubuntu so we manually exclude it from the list here languages: cpp,csharp,go,java,javascript,python,ruby tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check that the bundle contains tools for all platforms + env: + CODEQL_PATH: ${{ steps.init.outputs.codeql-path }} + run: | + # Platform-specific bundles only contain the tools for their own platform. + tools_dir="$(dirname "$CODEQL_PATH")/tools" + for platform in linux64 osx64 win64; do + if [[ ! -d "$tools_dir/$platform" ]]; then + echo "::error::Expected an all-platform CodeQL bundle, but '$tools_dir' does not contain a '$platform' directory." + exit 1 + fi + done - name: Build code run: ./build.sh - uses: ./../action/analyze diff --git a/pr-checks/checks/all-platform-bundle.yml b/pr-checks/checks/all-platform-bundle.yml index 24bd290159..40792c8768 100644 --- a/pr-checks/checks/all-platform-bundle.yml +++ b/pr-checks/checks/all-platform-bundle.yml @@ -17,6 +17,18 @@ steps: # Swift is not supported on Ubuntu so we manually exclude it from the list here languages: cpp,csharp,go,java,javascript,python,ruby tools: ${{ steps.prepare-test.outputs.tools-url }} + - name: Check that the bundle contains tools for all platforms + env: + CODEQL_PATH: ${{ steps.init.outputs.codeql-path }} + run: | + # Platform-specific bundles only contain the tools for their own platform. + tools_dir="$(dirname "$CODEQL_PATH")/tools" + for platform in linux64 osx64 win64; do + if [[ ! -d "$tools_dir/$platform" ]]; then + echo "::error::Expected an all-platform CodeQL bundle, but '$tools_dir' does not contain a '$platform' directory." + exit 1 + fi + done - name: Build code run: ./build.sh - uses: ./../action/analyze From 4e3aa4135fe5aba52aef5426aaf50b5b1b3170e6 Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Mon, 9 Nov 2026 17:13:44 +0000 Subject: [PATCH 65/76] Remove the `CodeQL Bundle All` PR check, which duplicates `all-platform-bundle` Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/deflake.yml | 1 - .github/workflows/test-codeql-bundle-all.yml | 62 -------------------- 2 files changed, 63 deletions(-) delete mode 100644 .github/workflows/test-codeql-bundle-all.yml diff --git a/.github/workflows/deflake.yml b/.github/workflows/deflake.yml index 27024b3780..9d6489dcaf 100644 --- a/.github/workflows/deflake.yml +++ b/.github/workflows/deflake.yml @@ -31,7 +31,6 @@ on: - "PR Check - C/C\\+\\+: autoinstalling dependencies is skipped (macOS)" - "PR Check - C/C\\+\\+: disabling autoinstalling dependencies (Linux)" - "PR Check - Clean up database cluster directory" - - "PR Check - CodeQL Bundle All" - "PR Check - Config export" - "PR Check - Config input" - "PR Check - Custom source root" diff --git a/.github/workflows/test-codeql-bundle-all.yml b/.github/workflows/test-codeql-bundle-all.yml deleted file mode 100644 index 9fae4b04a6..0000000000 --- a/.github/workflows/test-codeql-bundle-all.yml +++ /dev/null @@ -1,62 +0,0 @@ -name: "PR Check - CodeQL Bundle All" -env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GO111MODULE: auto -on: - push: - branches: - - main - - releases/v* - pull_request: - merge_group: - types: [checks_requested] - schedule: - - cron: "0 5 * * *" - workflow_dispatch: - -concurrency: - cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} - group: ${{ github.workflow }}-${{ github.ref }} - -defaults: - run: - shell: bash -jobs: - test-codeql-bundle-all: - strategy: - fail-fast: false - matrix: - include: - - os: ubuntu-26.04 - version: nightly-latest - name: "CodeQL Bundle All" - if: github.triggering_actor != 'dependabot[bot]' - permissions: - contents: read - security-events: read - timeout-minutes: 45 - runs-on: ${{ matrix.os }} - steps: - - name: Check out repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Prepare test - id: prepare-test - uses: ./.github/actions/prepare-test - with: - version: ${{ matrix.version }} - use-all-platform-bundle: true - - name: Install .NET - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 - with: - dotnet-version: "9.x" - - id: init - uses: ./../action/init - with: - # We manually exclude Swift from the languages list here, as it is not supported on Ubuntu - languages: cpp,csharp,go,java,javascript,python,ruby - tools: ${{ steps.prepare-test.outputs.tools-url }} - - name: Build code - run: ./build.sh - - uses: ./../action/analyze - env: - CODEQL_ACTION_TEST_MODE: true From a6827a39dec02dbb97adcc9fabd86aab02b0823a Mon Sep 17 00:00:00 2001 From: Henry Mercer Date: Mon, 9 Nov 2026 18:24:06 +0000 Subject: [PATCH 66/76] Merge `analyze-javascript` and `analyze-other` into one matrixed job Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/codeql/codeql-config-actions.yml | 5 +++ .github/workflows/codeql.yml | 48 ++++++------------------ 2 files changed, 16 insertions(+), 37 deletions(-) create mode 100644 .github/codeql/codeql-config-actions.yml diff --git a/.github/codeql/codeql-config-actions.yml b/.github/codeql/codeql-config-actions.yml new file mode 100644 index 0000000000..dda7a42c16 --- /dev/null +++ b/.github/codeql/codeql-config-actions.yml @@ -0,0 +1,5 @@ +paths-ignore: + - lib + - tests +queries: + - uses: security-and-quality diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 73045aedb4..86741ec455 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -19,10 +19,17 @@ env: CODEQL_ACTION_TESTING_ENVIRONMENT: codeql-action-pr-checks jobs: - analyze-javascript: + analyze: if: github.triggering_actor != 'dependabot[bot]' runs-on: ubuntu-26.04 + strategy: + fail-fast: false + matrix: + language: + - actions + - javascript + permissions: contents: read security-events: write @@ -34,48 +41,15 @@ jobs: uses: ./init id: init with: - languages: javascript - config-file: ./.github/codeql/codeql-config-javascript.yml + languages: ${{ matrix.language }} + build-mode: none + config-file: ./.github/codeql/codeql-config-${{ matrix.language }}.yml # confirm steps.init.outputs.codeql-path points to the codeql binary - name: Print CodeQL Version run: > "$CODEQL" version --format=json env: CODEQL: ${{steps.init.outputs.codeql-path}} - - name: Perform CodeQL Analysis - uses: ./analyze - with: - category: "/language:javascript" - upload: ${{ (github.event_name != 'merge_group' && 'always') || 'never' }} - - analyze-other: - if: github.triggering_actor != 'dependabot[bot]' - runs-on: ubuntu-26.04 - - strategy: - fail-fast: false - matrix: - include: - - language: actions - - permissions: - contents: read - security-events: write - - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Initialize CodeQL - uses: ./init - with: - languages: ${{ matrix.language }} - build-mode: none - config: > - paths-ignore: - - lib - - tests - queries: - - uses: security-and-quality - name: Perform CodeQL Analysis uses: ./analyze with: From f039c789cd905be1e071e465d66e1a170a2fbf75 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Tue, 3 Nov 2026 11:15:36 -0600 Subject: [PATCH 67/76] Warn about direct CHANGELOG.md changes in PR checks Split workflow activation from #4217 while keeping the comment action loaded from trusted main. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 75 ++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 81d88d1a7d..f32032dd58 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -95,6 +95,8 @@ jobs: contents: read runs-on: ubuntu-26.04 timeout-minutes: 10 + outputs: + changelog-modified: ${{ steps.changelog-check.outputs.modified }} concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' || false }} @@ -191,6 +193,20 @@ jobs: path: ${{ runner.temp }}/repo-size/ if-no-files-found: error + - name: Check for CHANGELOG.md changes + id: changelog-check + if: steps.fetch-base.outcome == 'success' + env: + BASE_SHA: ${{ steps.fetch-base.outputs.merge_base }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + if ! git diff --exit-code --quiet "$BASE_SHA" "$HEAD_SHA" -- CHANGELOG.md; then + echo "CHANGELOG.md was modified in this PR." + echo "modified=true" >> "$GITHUB_OUTPUT" + else + echo "modified=false" >> "$GITHUB_OUTPUT" + fi + - name: "Backport: Check out base ref" id: checkout-base if: ${{ startsWith(github.head_ref, 'backport-') }} @@ -211,8 +227,8 @@ jobs: exit 1 fi - post-repo-size-comment: - name: Post repo size comment + post-pr-comments: + name: Post PR comments needs: other-checks # Keep write permissions isolated from the job that checks out and tests PR code. This job only # posts the candidate comment body produced by the read-only `pr-checks` job. @@ -232,6 +248,22 @@ jobs: group: check-repo-size-${{ github.event.pull_request.number }} steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # Check out main, not the PR's head, since this job runs with + # `pull-requests: write` permissions and must not execute untrusted code from the PR. + ref: main + + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: "npm" + + - name: Install dependencies + run: npm ci --workspace=pr-checks + - name: Download repo size comment uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: @@ -261,3 +293,42 @@ jobs: else echo "Skipping repo size comment because the delta is below the threshold and no sticky comment exists." fi + + - name: Post a warning about modifying CHANGELOG.md + # Release, backport, mergeback, and bundle-update PRs deliberately modify CHANGELOG.md, + # so skip comment management entirely for these automation flows. + if: >- + needs.other-checks.outputs.changelog-modified == 'true' && + !startsWith(github.event.pull_request.head.ref, 'update-v') && + !startsWith(github.event.pull_request.head.ref, 'backport-v') && + !startsWith(github.event.pull_request.head.ref, 'mergeback/') && + !startsWith(github.event.pull_request.head.ref, 'update-bundle/') + uses: ./.github/actions/post-comment + with: + marker: "post-comment:CHANGELOG.md" + body: | + ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. + Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` + file will be automatically generated from those change-notes. + See [`unreleased-change-notes/README.md`](https://github.com/github/codeql-action/blob/main/unreleased-change-notes/README.md) for more information. + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Mark the CHANGELOG.md concern as resolved + if: >- + needs.other-checks.outputs.changelog-modified == 'false' && + !startsWith(github.event.pull_request.head.ref, 'update-v') && + !startsWith(github.event.pull_request.head.ref, 'backport-v') && + !startsWith(github.event.pull_request.head.ref, 'mergeback/') && + !startsWith(github.event.pull_request.head.ref, 'update-bundle/') + uses: ./.github/actions/post-comment + with: + marker: "post-comment:CHANGELOG.md" + update-only: true + body: | + ⚠️ `CHANGELOG.md` has been modified in this PR. Please do not modify `CHANGELOG.md` directly. + Instead, create a change-note file in `unreleased-change-notes/`. The `CHANGELOG.md` + file will be automatically generated from those change-notes. + See [`unreleased-change-notes/README.md`](https://github.com/github/codeql-action/blob/main/unreleased-change-notes/README.md) for more information. + + **Edit:** `CHANGELOG.md` is no longer modified in this PR. This concern is resolved. + token: ${{ secrets.GITHUB_TOKEN }} From 9e531e13096eecd895eb7f9e78d022e557e90e23 Mon Sep 17 00:00:00 2001 From: Mario Campos Date: Tue, 3 Nov 2026 11:41:42 -0600 Subject: [PATCH 68/76] Install root dependencies for PR comment action Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index f32032dd58..47d2d73bad 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -262,7 +262,7 @@ jobs: cache: "npm" - name: Install dependencies - run: npm ci --workspace=pr-checks + run: npm ci --workspace=pr-checks --include-workspace-root - name: Download repo size comment uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 From f874b0c2b229e17bd2aeaf241ab3e745cb1c5f35 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:38:34 +0000 Subject: [PATCH 69/76] Bump fast-xml-parser from 5.7.1 to 5.12.1 Bumps [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) from 5.7.1 to 5.12.1. - [Release notes](https://github.com/NaturalIntelligence/fast-xml-parser/releases) - [Changelog](https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md) - [Commits](https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.7.1...v5.12.1) --- updated-dependencies: - dependency-name: fast-xml-parser dependency-version: 5.12.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- package-lock.json | 94 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 69 insertions(+), 25 deletions(-) diff --git a/package-lock.json b/package-lock.json index 12306cdd7f..0dcc89e05c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2152,9 +2152,9 @@ } }, "node_modules/@nodable/entities": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.0.tgz", - "integrity": "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-3.1.0.tgz", + "integrity": "sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ==", "funding": [ { "type": "github", @@ -3530,6 +3530,7 @@ }, "node_modules/ansi-regex": { "version": "5.0.1", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -3539,6 +3540,7 @@ "version": "6.2.3", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -3547,6 +3549,18 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/anynum": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/anynum/-/anynum-1.0.1.tgz", + "integrity": "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, "node_modules/apache-arrow": { "version": "21.2.0", "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-21.2.0.tgz", @@ -4443,6 +4457,7 @@ }, "node_modules/color-convert": { "version": "2.0.1", + "dev": true, "license": "MIT", "dependencies": { "color-name": "~1.1.4" @@ -4453,6 +4468,7 @@ }, "node_modules/color-name": { "version": "1.1.4", + "dev": true, "license": "MIT" }, "node_modules/comment-parser": { @@ -4577,6 +4593,7 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -4831,6 +4848,7 @@ }, "node_modules/emoji-regex": { "version": "8.0.0", + "dev": true, "license": "MIT" }, "node_modules/es-abstract": { @@ -5904,9 +5922,9 @@ "license": "MIT" }, "node_modules/fast-xml-builder": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.2.0.tgz", - "integrity": "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.3.2.tgz", + "integrity": "sha512-OX91VSlShLPDgRZV7tk/YQ4l8tT75QziF5Ixg8g4PFbCVPjuTWwN+yQfAxLJ0dufJpprdOd6HlM74Jhd39TcBQ==", "funding": [ { "type": "github", @@ -5915,14 +5933,14 @@ ], "license": "MIT", "dependencies": { - "path-expression-matcher": "^1.5.0", - "xml-naming": "^0.1.0" + "path-expression-matcher": "^1.6.2", + "xml-naming": "^0.3.0" } }, "node_modules/fast-xml-parser": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.1.tgz", - "integrity": "sha512-8Cc3f8GUGUULg34pBch/KGyPLglS+OFs05deyOlY7fL2MTagYPKrVQNmR1fLF/yJ9PH5ZSTd3YDF6pnmeZU+zA==", + "version": "5.12.1", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.12.1.tgz", + "integrity": "sha512-wR8dO/fx+z8C5exuem1e7BKOWvjsuzvjS/tvA/Xu3Z1zQqJGcXrPzXbcAiaMgp2KjreEROcTkmnnisrcmJ2hYQ==", "funding": [ { "type": "github", @@ -5931,10 +5949,12 @@ ], "license": "MIT", "dependencies": { - "@nodable/entities": "^2.1.0", - "fast-xml-builder": "^1.1.5", - "path-expression-matcher": "^1.5.0", - "strnum": "^2.2.3" + "@nodable/entities": "^3.1.0", + "fast-xml-builder": "^1.3.2", + "is-unsafe": "^2.0.3", + "path-expression-matcher": "^1.6.2", + "strnum": "^2.5.1", + "xml-naming": "^0.3.0" }, "bin": { "fxparser": "src/cli/cli.js" @@ -6859,6 +6879,7 @@ }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -7114,6 +7135,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-unsafe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.3.tgz", + "integrity": "sha512-ZBllczCCO267vgdFb6Tq3pv+LhHaCiGMdr+ZsuL+OopruAg7S+3ZDs1vD0RPC0uSrkjzbraxaGjtX1YBxjPeFQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, "node_modules/is-weakmap": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", @@ -7169,6 +7202,7 @@ }, "node_modules/isexe": { "version": "2.0.0", + "dev": true, "license": "ISC" }, "node_modules/js-string-escape": { @@ -8555,9 +8589,9 @@ } }, "node_modules/path-expression-matcher": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz", - "integrity": "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==", + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.6.2.tgz", + "integrity": "sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ==", "funding": [ { "type": "github", @@ -8571,6 +8605,7 @@ }, "node_modules/path-key": { "version": "3.1.1", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -9170,6 +9205,7 @@ }, "node_modules/shebang-command": { "version": "2.0.0", + "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -9180,6 +9216,7 @@ }, "node_modules/shebang-regex": { "version": "3.0.0", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -9265,6 +9302,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, "engines": { "node": ">=14" }, @@ -9451,6 +9489,7 @@ }, "node_modules/string-width": { "version": "4.2.3", + "dev": true, "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", @@ -9536,6 +9575,7 @@ }, "node_modules/strip-ansi": { "version": "6.0.1", + "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" @@ -9577,16 +9617,19 @@ } }, "node_modules/strnum": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.2.3.tgz", - "integrity": "sha512-oKx6RUCuHfT3oyVjtnrmn19H1SiCqgJSg+54XqURKp5aCMbrXrhLjRN9TjuwMjiYstZ0MzDrHqkGZ5dFTKd+zg==", + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.5.1.tgz", + "integrity": "sha512-UM4nTLWzQiDBseVxUGxN0wJzIk0UU89Qi7pKXz9qISo+lhviJikTuikBsK/oFRlpvYHvSdz0TVoLyQ+sEpYwxA==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/NaturalIntelligence" } ], - "license": "MIT" + "license": "MIT", + "dependencies": { + "anynum": "^1.0.1" + } }, "node_modules/supertap": { "version": "3.0.1", @@ -10273,6 +10316,7 @@ }, "node_modules/which": { "version": "2.0.2", + "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -10436,9 +10480,9 @@ } }, "node_modules/xml-naming": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.1.0.tgz", - "integrity": "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==", + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.3.0.tgz", + "integrity": "sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ==", "funding": [ { "type": "github", From 0c7ad8448663d8206c30312ed725588cbbfeefca Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:41:05 +0000 Subject: [PATCH 70/76] Rebuild --- lib/entry-points.js | 1715 +++++++++++++++++++++++++------------------ 1 file changed, 1002 insertions(+), 713 deletions(-) diff --git a/lib/entry-points.js b/lib/entry-points.js index 7ff11d2666..961a879416 100644 --- a/lib/entry-points.js +++ b/lib/entry-points.js @@ -54591,103 +54591,90 @@ var require_fxp = __commonJS({ }, o: (t2, e2) => Object.prototype.hasOwnProperty.call(t2, e2), r: (t2) => { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t2, "__esModule", { value: true }); } }, e = {}; - t.r(e), t.d(e, { XMLBuilder: () => Bt, XMLParser: () => Tt, XMLValidator: () => Ut }); - const n = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD", i = new RegExp("^[" + n + "][" + n + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"); - function s(t2, e2) { - const n2 = []; - let i2 = e2.exec(t2); - for (; i2; ) { - const s2 = []; - s2.startIndex = e2.lastIndex - i2[0].length; - const r2 = i2.length; - for (let t3 = 0; t3 < r2; t3++) s2.push(i2[t3]); - n2.push(s2), i2 = e2.exec(t2); - } - return n2; - } - const r = function(t2) { + t.r(e), t.d(e, { XMLBuilder: () => $e, XMLParser: () => ce, XMLValidator: () => Oe }); + const n = ":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD", i = new RegExp("^[" + n + "][" + n + "\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"), r = function(t2) { return !(null == i.exec(t2)); - }, o = ["hasOwnProperty", "toString", "valueOf", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"], a = ["__proto__", "constructor", "prototype"], h = { allowBooleanAttributes: false, unpairedTags: [] }; + }, s = ["hasOwnProperty", "toString", "valueOf", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"], o = ["__proto__", "constructor", "prototype"], a = { allowBooleanAttributes: false, unpairedTags: [] }; function l(t2, e2) { - e2 = Object.assign({}, h, e2); + e2 = Object.assign({}, a, e2); const n2 = []; - let i2 = false, s2 = false; + let i2 = false, r2 = false; "\uFEFF" === t2[0] && (t2 = t2.substr(1)); - for (let r2 = 0; r2 < t2.length; r2++) if ("<" === t2[r2] && "?" === t2[r2 + 1]) { - if (r2 += 2, r2 = p(t2, r2), r2.err) return r2; + for (let s2 = 0; s2 < t2.length; s2++) if ("<" === t2[s2] && "?" === t2[s2 + 1]) { + if (s2 += 2, s2 = p(t2, s2), s2.err) return s2; } else { - if ("<" !== t2[r2]) { - if (u(t2[r2])) continue; - return b("InvalidChar", "char '" + t2[r2] + "' is not expected.", w(t2, r2)); + if ("<" !== t2[s2]) { + if (c(t2[s2])) continue; + return x("InvalidChar", "char '" + t2[s2] + "' is not expected.", N(t2, s2)); } { - let o2 = r2; - if (r2++, "!" === t2[r2]) { - r2 = c(t2, r2); + let o2 = s2; + if (s2++, "!" === t2[s2]) { + s2 = h(t2, s2); continue; } { let a2 = false; - "/" === t2[r2] && (a2 = true, r2++); - let h2 = ""; - for (; r2 < t2.length && ">" !== t2[r2] && " " !== t2[r2] && " " !== t2[r2] && "\n" !== t2[r2] && "\r" !== t2[r2]; r2++) h2 += t2[r2]; - if (h2 = h2.trim(), "/" === h2[h2.length - 1] && (h2 = h2.substring(0, h2.length - 1), r2--), !E(h2)) { + "/" === t2[s2] && (a2 = true, s2++); + let l2 = ""; + for (; s2 < t2.length && ">" !== t2[s2] && " " !== t2[s2] && " " !== t2[s2] && "\n" !== t2[s2] && "\r" !== t2[s2]; s2++) l2 += t2[s2]; + if (l2 = l2.trim(), "/" === l2[l2.length - 1] && (l2 = l2.substring(0, l2.length - 1), s2--), !y(l2)) { let e3; - return e3 = 0 === h2.trim().length ? "Invalid space after '<'." : "Tag '" + h2 + "' is an invalid name.", b("InvalidTag", e3, w(t2, r2)); - } - const l2 = g(t2, r2); - if (false === l2) return b("InvalidAttr", "Attributes for '" + h2 + "' have open quote.", w(t2, r2)); - let d2 = l2.value; - if (r2 = l2.index, "/" === d2[d2.length - 1]) { - const n3 = r2 - d2.length; - d2 = d2.substring(0, d2.length - 1); - const s3 = x(d2, e2); - if (true !== s3) return b(s3.err.code, s3.err.msg, w(t2, n3 + s3.err.line)); + return e3 = 0 === l2.trim().length ? "Invalid space after '<'." : "Tag '" + l2 + "' is an invalid name.", x("InvalidTag", e3, N(t2, s2)); + } + const d2 = f(t2, s2); + if (false === d2) return x("InvalidAttr", "Attributes for '" + l2 + "' have open quote.", N(t2, s2)); + let u2 = d2.value; + if (s2 = d2.index, "/" === u2[u2.length - 1]) { + const n3 = s2 - u2.length; + u2 = u2.substring(0, u2.length - 1); + const r3 = g(u2, e2); + if (true !== r3) return x(r3.err.code, r3.err.msg, N(t2, n3 + r3.err.line)); i2 = true; } else if (a2) { - if (!l2.tagClosed) return b("InvalidTag", "Closing tag '" + h2 + "' doesn't have proper closing.", w(t2, r2)); - if (d2.trim().length > 0) return b("InvalidTag", "Closing tag '" + h2 + "' can't have attributes or invalid starting.", w(t2, o2)); - if (0 === n2.length) return b("InvalidTag", "Closing tag '" + h2 + "' has not been opened.", w(t2, o2)); + if (!d2.tagClosed) return x("InvalidTag", "Closing tag '" + l2 + "' doesn't have proper closing.", N(t2, s2)); + if (u2.trim().length > 0) return x("InvalidTag", "Closing tag '" + l2 + "' can't have attributes or invalid starting.", N(t2, o2)); + if (0 === n2.length) return x("InvalidTag", "Closing tag '" + l2 + "' has not been opened.", N(t2, o2)); { const e3 = n2.pop(); - if (h2 !== e3.tagName) { - let n3 = w(t2, e3.tagStartPos); - return b("InvalidTag", "Expected closing tag '" + e3.tagName + "' (opened in line " + n3.line + ", col " + n3.col + ") instead of closing tag '" + h2 + "'.", w(t2, o2)); + if (l2 !== e3.tagName) { + let n3 = N(t2, e3.tagStartPos); + return x("InvalidTag", "Expected closing tag '" + e3.tagName + "' (opened in line " + n3.line + ", col " + n3.col + ") instead of closing tag '" + l2 + "'.", N(t2, o2)); } - 0 == n2.length && (s2 = true); + 0 == n2.length && (r2 = true); } } else { - const a3 = x(d2, e2); - if (true !== a3) return b(a3.err.code, a3.err.msg, w(t2, r2 - d2.length + a3.err.line)); - if (true === s2) return b("InvalidXml", "Multiple possible root nodes found.", w(t2, r2)); - -1 !== e2.unpairedTags.indexOf(h2) || n2.push({ tagName: h2, tagStartPos: o2 }), i2 = true; - } - for (r2++; r2 < t2.length; r2++) if ("<" === t2[r2]) { - if ("!" === t2[r2 + 1]) { - r2++, r2 = c(t2, r2); + const a3 = g(u2, e2); + if (true !== a3) return x(a3.err.code, a3.err.msg, N(t2, s2 - u2.length + a3.err.line)); + if (true === r2) return x("InvalidXml", "Multiple possible root nodes found.", N(t2, s2)); + -1 !== e2.unpairedTags.indexOf(l2) || n2.push({ tagName: l2, tagStartPos: o2 }), i2 = true; + } + for (s2++; s2 < t2.length; s2++) if ("<" === t2[s2]) { + if ("!" === t2[s2 + 1]) { + s2++, s2 = h(t2, s2); continue; } - if ("?" !== t2[r2 + 1]) break; - if (r2 = p(t2, ++r2), r2.err) return r2; - } else if ("&" === t2[r2]) { - const e3 = N(t2, r2); - if (-1 == e3) return b("InvalidChar", "char '&' is not expected.", w(t2, r2)); - r2 = e3; - } else if (true === s2 && !u(t2[r2])) return b("InvalidXml", "Extra text at the end", w(t2, r2)); - "<" === t2[r2] && r2--; + if ("?" !== t2[s2 + 1]) break; + if (s2 = p(t2, ++s2), s2.err) return s2; + } else if ("&" === t2[s2]) { + const e3 = m(t2, s2); + if (-1 == e3) return x("InvalidChar", "char '&' is not expected.", N(t2, s2)); + s2 = e3; + } else if (true === r2 && !c(t2[s2])) return x("InvalidXml", "Extra text at the end", N(t2, s2)); + "<" === t2[s2] && s2--; } } } - return i2 ? 1 == n2.length ? b("InvalidTag", "Unclosed tag '" + n2[0].tagName + "'.", w(t2, n2[0].tagStartPos)) : !(n2.length > 0) || b("InvalidXml", "Invalid '" + JSON.stringify(n2.map((t3) => t3.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }) : b("InvalidXml", "Start tag expected.", 1); + return i2 ? 1 == n2.length ? x("InvalidTag", "Unclosed tag '" + n2[0].tagName + "'.", N(t2, n2[0].tagStartPos)) : !(n2.length > 0) || x("InvalidXml", "Invalid '" + JSON.stringify(n2.map((t3) => t3.tagName), null, 4).replace(/\r?\n/g, "") + "' found.", { line: 1, col: 1 }) : x("InvalidXml", "Start tag expected.", 1); } - function u(t2) { + function c(t2) { return " " === t2 || " " === t2 || "\n" === t2 || "\r" === t2; } function p(t2, e2) { const n2 = e2; for (; e2 < t2.length; e2++) if ("?" == t2[e2] || " " == t2[e2]) { const i2 = t2.substr(n2, e2 - n2); - if (e2 > 5 && "xml" === i2) return b("InvalidXml", "XML declaration allowed only at the start of the document.", w(t2, e2)); + if (e2 > 5 && "xml" === i2) return x("InvalidXml", "XML declaration allowed only at the start of the document.", N(t2, e2)); if ("?" == t2[e2] && ">" == t2[e2 + 1]) { e2++; break; @@ -54696,7 +54683,7 @@ var require_fxp = __commonJS({ } return e2; } - function c(t2, e2) { + function h(t2, e2) { if (t2.length > e2 + 5 && "-" === t2[e2 + 1] && "-" === t2[e2 + 2]) { for (e2 += 3; e2 < t2.length; e2++) if ("-" === t2[e2] && "-" === t2[e2 + 1] && ">" === t2[e2 + 2]) { e2 += 2; @@ -54714,34 +54701,60 @@ var require_fxp = __commonJS({ } return e2; } - const d = '"', f = "'"; - function g(t2, e2) { - let n2 = "", i2 = "", s2 = false; + const d = '"', u = "'"; + function f(t2, e2) { + let n2 = "", i2 = "", r2 = false; for (; e2 < t2.length; e2++) { - if (t2[e2] === d || t2[e2] === f) "" === i2 ? i2 = t2[e2] : i2 !== t2[e2] || (i2 = ""); + if (t2[e2] === d || t2[e2] === u) "" === i2 ? i2 = t2[e2] : i2 !== t2[e2] || (i2 = ""); else if (">" === t2[e2] && "" === i2) { - s2 = true; + r2 = true; break; } n2 += t2[e2]; } - return "" === i2 && { value: n2, index: e2, tagClosed: s2 }; + return "" === i2 && { value: n2, index: e2, tagClosed: r2 }; } - const m = new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`, "g"); - function x(t2, e2) { - const n2 = s(t2, m), i2 = {}; + function g(t2, e2) { + const n2 = (function(t3) { + const e3 = [], n3 = t3.length; + let i3 = 0; + for (; i3 < n3; ) { + const r2 = i3; + for (; i3 < n3 && c(t3[i3]); ) i3++; + if (i3 >= n3) break; + if ("=" === t3[i3]) { + i3++; + continue; + } + const s2 = t3.slice(r2, i3), o2 = i3; + for (; i3 < n3 && !c(t3[i3]) && "=" !== t3[i3]; ) i3++; + const a2 = t3.slice(o2, i3); + let l2, p2, h2, d2 = i3; + for (; d2 < n3 && c(t3[d2]); ) d2++; + d2 < n3 && "=" === t3[d2] && (l2 = t3.slice(i3, d2 + 1), i3 = d2 + 1); + let u2 = i3; + for (; u2 < n3 && c(t3[u2]); ) u2++; + if (u2 < n3 && ('"' === t3[u2] || "'" === t3[u2])) { + const e4 = u2 + 1, n4 = t3.indexOf(t3[u2], e4); + -1 !== n4 && (p2 = t3[u2], h2 = t3.slice(e4, n4), i3 = n4 + 1); + } + const f2 = { startIndex: r2 }; + f2[1] = s2, f2[2] = a2, f2[3] = l2, f2[4] = void 0 !== p2 || void 0, f2[5] = p2, f2[6] = h2, e3.push(f2); + } + return e3; + })(t2), i2 = {}; for (let t3 = 0; t3 < n2.length; t3++) { - if (0 === n2[t3][1].length) return b("InvalidAttr", "Attribute '" + n2[t3][2] + "' has no space in starting.", v(n2[t3])); - if (void 0 !== n2[t3][3] && void 0 === n2[t3][4]) return b("InvalidAttr", "Attribute '" + n2[t3][2] + "' is without value.", v(n2[t3])); - if (void 0 === n2[t3][3] && !e2.allowBooleanAttributes) return b("InvalidAttr", "boolean attribute '" + n2[t3][2] + "' is not allowed.", v(n2[t3])); - const s2 = n2[t3][2]; - if (!y(s2)) return b("InvalidAttr", "Attribute '" + s2 + "' is an invalid name.", v(n2[t3])); - if (Object.prototype.hasOwnProperty.call(i2, s2)) return b("InvalidAttr", "Attribute '" + s2 + "' is repeated.", v(n2[t3])); - i2[s2] = 1; + if (0 === n2[t3][1].length) return x("InvalidAttr", "Attribute '" + n2[t3][2] + "' has no space in starting.", E(n2[t3])); + if (void 0 !== n2[t3][3] && void 0 === n2[t3][4]) return x("InvalidAttr", "Attribute '" + n2[t3][2] + "' is without value.", E(n2[t3])); + if (void 0 === n2[t3][3] && !e2.allowBooleanAttributes) return x("InvalidAttr", "boolean attribute '" + n2[t3][2] + "' is not allowed.", E(n2[t3])); + const r2 = n2[t3][2]; + if (!b(r2)) return x("InvalidAttr", "Attribute '" + r2 + "' is an invalid name.", E(n2[t3])); + if (Object.prototype.hasOwnProperty.call(i2, r2)) return x("InvalidAttr", "Attribute '" + r2 + "' is repeated.", E(n2[t3])); + i2[r2] = 1; } return true; } - function N(t2, e2) { + function m(t2, e2) { if (";" === t2[++e2]) return -1; if ("#" === t2[e2]) return (function(t3, e3) { let n3 = /\d/; @@ -54758,46 +54771,46 @@ var require_fxp = __commonJS({ } return e2; } - function b(t2, e2, n2) { + function x(t2, e2, n2) { return { err: { code: t2, msg: e2, line: n2.line || n2, col: n2.col } }; } - function y(t2) { + function b(t2) { return r(t2); } - function E(t2) { + function y(t2) { return r(t2); } - function w(t2, e2) { + function N(t2, e2) { const n2 = t2.substring(0, e2).split(/\r?\n/); return { line: n2.length, col: n2[n2.length - 1].length + 1 }; } - function v(t2) { + function E(t2) { return t2.startIndex + t2[1].length; } - const S = (t2) => o.includes(t2) ? "__" + t2 : t2, _2 = { preserveOrder: false, attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, removeNSPrefix: false, allowBooleanAttributes: false, parseTagValue: true, parseAttributeValue: false, trimValues: true, cdataPropName: false, numberParseOptions: { hex: true, leadingZeros: true, eNotation: true }, tagValueProcessor: function(t2, e2) { + const w = (t2) => s.includes(t2) ? "__" + t2 : t2, v = { preserveOrder: false, attributeNamePrefix: "@_", attributesGroupName: false, textNodeName: "#text", ignoreAttributes: true, removeNSPrefix: false, allowBooleanAttributes: false, parseTagValue: true, parseAttributeValue: false, trimValues: true, cdataPropName: false, numberParseOptions: { hex: true, leadingZeros: true, eNotation: true, unicode: false }, tagValueProcessor: function(t2, e2) { return e2; }, attributeValueProcessor: function(t2, e2) { return e2; }, stopNodes: [], alwaysCreateTextNode: false, isArray: () => false, commentPropName: false, unpairedTags: [], processEntities: true, htmlEntities: false, entityDecoder: null, ignoreDeclaration: false, ignorePiTags: false, transformTagName: false, transformAttributeName: false, updateTag: function(t2, e2, n2) { return t2; - }, captureMetaData: false, maxNestedTags: 100, strictReservedNames: true, jPath: true, onDangerousProperty: S }; - function A(t2, e2) { + }, captureMetaData: false, maxNestedTags: 100, strictReservedNames: true, jPath: true, onDangerousProperty: w }; + function S(t2, e2) { if ("string" != typeof t2) return; const n2 = t2.toLowerCase(); + if (s.some((t3) => n2 === t3.toLowerCase())) throw new Error(`[SECURITY] Invalid ${e2}: "${t2}" is a reserved JavaScript keyword that could cause prototype pollution`); if (o.some((t3) => n2 === t3.toLowerCase())) throw new Error(`[SECURITY] Invalid ${e2}: "${t2}" is a reserved JavaScript keyword that could cause prototype pollution`); - if (a.some((t3) => n2 === t3.toLowerCase())) throw new Error(`[SECURITY] Invalid ${e2}: "${t2}" is a reserved JavaScript keyword that could cause prototype pollution`); } - function T(t2, e2) { - return "boolean" == typeof t2 ? { enabled: t2, maxEntitySize: 1e4, maxExpansionDepth: 1e4, maxTotalExpansions: 1 / 0, maxExpandedLength: 1e5, maxEntityCount: 1e3, allowedTags: null, tagFilter: null, appliesTo: "all" } : "object" == typeof t2 && null !== t2 ? { enabled: false !== t2.enabled, maxEntitySize: Math.max(1, t2.maxEntitySize ?? 1e4), maxExpansionDepth: Math.max(1, t2.maxExpansionDepth ?? 1e4), maxTotalExpansions: Math.max(1, t2.maxTotalExpansions ?? 1 / 0), maxExpandedLength: Math.max(1, t2.maxExpandedLength ?? 1e5), maxEntityCount: Math.max(1, t2.maxEntityCount ?? 1e3), allowedTags: t2.allowedTags ?? null, tagFilter: t2.tagFilter ?? null, appliesTo: t2.appliesTo ?? "all" } : T(true); + function A(t2, e2) { + return "boolean" == typeof t2 ? { enabled: t2, maxEntitySize: 1e4, maxExpansionDepth: 1e4, maxTotalExpansions: 1 / 0, maxExpandedLength: 1e5, maxEntityCount: 1e3, allowedTags: null, tagFilter: null, appliesTo: "all" } : "object" == typeof t2 && null !== t2 ? { enabled: false !== t2.enabled, maxEntitySize: Math.max(1, t2.maxEntitySize ?? 1e4), maxExpansionDepth: Math.max(1, t2.maxExpansionDepth ?? 1e4), maxTotalExpansions: Math.max(1, t2.maxTotalExpansions ?? 1 / 0), maxExpandedLength: Math.max(1, t2.maxExpandedLength ?? 1e5), maxEntityCount: Math.max(1, t2.maxEntityCount ?? 1e3), allowedTags: t2.allowedTags ?? null, tagFilter: t2.tagFilter ?? null, appliesTo: t2.appliesTo ?? "all" } : A(true); } - const C = function(t2) { - const e2 = Object.assign({}, _2, t2), n2 = [{ value: e2.attributeNamePrefix, name: "attributeNamePrefix" }, { value: e2.attributesGroupName, name: "attributesGroupName" }, { value: e2.textNodeName, name: "textNodeName" }, { value: e2.cdataPropName, name: "cdataPropName" }, { value: e2.commentPropName, name: "commentPropName" }]; - for (const { value: t3, name: e3 } of n2) t3 && A(t3, e3); - return null === e2.onDangerousProperty && (e2.onDangerousProperty = S), e2.processEntities = T(e2.processEntities, e2.htmlEntities), e2.unpairedTagsSet = new Set(e2.unpairedTags), e2.stopNodes && Array.isArray(e2.stopNodes) && (e2.stopNodes = e2.stopNodes.map((t3) => "string" == typeof t3 && t3.startsWith("*.") ? ".." + t3.substring(2) : t3)), e2; + const T = function(t2) { + const e2 = Object.assign({}, v, t2), n2 = [{ value: e2.attributeNamePrefix, name: "attributeNamePrefix" }, { value: e2.attributesGroupName, name: "attributesGroupName" }, { value: e2.textNodeName, name: "textNodeName" }, { value: e2.cdataPropName, name: "cdataPropName" }, { value: e2.commentPropName, name: "commentPropName" }]; + for (const { value: t3, name: e3 } of n2) t3 && S(t3, e3); + return null === e2.onDangerousProperty && (e2.onDangerousProperty = w), e2.processEntities = A(e2.processEntities, e2.htmlEntities), e2.unpairedTagsSet = new Set(e2.unpairedTags), e2.stopNodes && Array.isArray(e2.stopNodes) && (e2.stopNodes = e2.stopNodes.map((t3) => "string" == typeof t3 && t3.startsWith("*.") ? ".." + t3.substring(2) : t3)), e2; }; - let P; - P = "function" != typeof Symbol ? "@@xmlMetadata" : /* @__PURE__ */ Symbol("XML Node Metadata"); - class O { + let _2; + _2 = "function" != typeof Symbol ? "@@xmlMetadata" : /* @__PURE__ */ Symbol("XML Node Metadata"); + class C { constructor(t2) { this.tagname = t2, this.child = [], this[":@"] = /* @__PURE__ */ Object.create(null); } @@ -54805,15 +54818,42 @@ var require_fxp = __commonJS({ "__proto__" === t2 && (t2 = "#__proto__"), this.child.push({ [t2]: e2 }); } addChild(t2, e2) { - "__proto__" === t2.tagname && (t2.tagname = "#__proto__"), t2[":@"] && Object.keys(t2[":@"]).length > 0 ? this.child.push({ [t2.tagname]: t2.child, ":@": t2[":@"] }) : this.child.push({ [t2.tagname]: t2.child }), void 0 !== e2 && (this.child[this.child.length - 1][P] = { startIndex: e2 }); + "__proto__" === t2.tagname && (t2.tagname = "#__proto__"), t2[":@"] && Object.keys(t2[":@"]).length > 0 ? this.child.push({ [t2.tagname]: t2.child, ":@": t2[":@"] }) : this.child.push({ [t2.tagname]: t2.child }), this.addStartIndex(e2); + } + addStartIndex(t2) { + void 0 !== t2 && (this.child[this.child.length - 1][_2] = { startIndex: t2 }); + } + addEndIndex(t2) { + const e2 = this.child[this.child.length - 1]; + void 0 !== e2 && void 0 !== e2[_2] && void 0 === e2[_2].endIndex && (e2[_2].endIndex = t2); } static getMetaDataSymbol() { - return P; + return _2; + } + } + const $ = ":A-Za-z_\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD", O = ":A-Za-z_\xC0-\u02FF\u0370-\u037D\u037F-\u0486\u0488-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}", P = O + "\\-\\.\\d\xB7\u0300-\u036F\u0487\u203F-\u2040", j = (t2, e2, n2 = "") => { + const i2 = `[${t2.replace(":", "")}][${e2.replace(":", "")}]*`; + return { name: new RegExp(`^[${t2}][${e2}]*$`, n2), ncName: new RegExp(`^${i2}$`, n2), qName: new RegExp(`^${i2}(?::${i2})?$`, n2), nmToken: new RegExp(`^[${e2}]+$`, n2), nmTokens: new RegExp(`^[${e2}]+(?:\\s+[${e2}]+)*$`, n2) }; + }, I = j($, $ + "\\-\\.\\d\xB7\u0300-\u036F\u203F-\u2040"), k = j(O, P, "u"), L = ":A-Za-z_", D = j(L, L + "\\-\\.\\d"), M = (t2 = "1.0", e2 = false) => e2 ? D : "1.1" === t2 ? k : I, R = (t2, { xmlVersion: e2 = "1.0", asciiOnly: n2 = false } = {}) => M(e2, n2).qName.test(t2), V = ["name", "ncName", "qName", "nmToken", "nmTokens"], q = (t2, { xmlVersion: e2 = "1.0", asciiOnly: n2 = false, maxCacheSize: i2 = 2048 } = {}) => { + if (!V.includes(t2)) throw new TypeError(`Unknown production "${t2}". Must be one of: ${V.join(", ")}`); + const r2 = M(e2, n2)[t2]; + let s2 = /* @__PURE__ */ new Map(); + const o2 = (t3) => { + const e3 = s2.get(t3); + if (void 0 !== e3) return e3; + const n3 = r2.test(t3); + return s2.size < i2 && s2.set(t3, n3), n3; + }; + return o2.reset = () => { + s2 = /* @__PURE__ */ new Map(); + }, o2; + }; + class F { + constructor(t2, e2) { + this.suppressValidationErr = !t2, this.options = t2, this.xmlVersion = e2 || 1; } - } - class $ { - constructor(t2) { - this.suppressValidationErr = !t2, this.options = t2; + setXmlVersion(t2 = 1) { + this.xmlVersion = t2; } readDocType(t2, e2) { const n2 = /* @__PURE__ */ Object.create(null); @@ -54821,134 +54861,277 @@ var require_fxp = __commonJS({ if ("O" !== t2[e2 + 3] || "C" !== t2[e2 + 4] || "T" !== t2[e2 + 5] || "Y" !== t2[e2 + 6] || "P" !== t2[e2 + 7] || "E" !== t2[e2 + 8]) throw new Error("Invalid Tag instead of DOCTYPE"); { e2 += 9; - let s2 = 1, r2 = false, o2 = false, a2 = ""; - for (; e2 < t2.length; e2++) if ("<" !== t2[e2] || o2) if (">" === t2[e2]) { - if (o2 ? "-" === t2[e2 - 1] && "-" === t2[e2 - 2] && (o2 = false, s2--) : s2--, 0 === s2) break; - } else "[" === t2[e2] ? r2 = true : a2 += t2[e2]; + let r2 = 1, s2 = false, o2 = false, a2 = null, l2 = ""; + for (; e2 < t2.length; e2++) if (null === a2) if (s2 || o2 || '"' !== t2[e2] && "'" !== t2[e2]) if ("<" !== t2[e2] || o2) if (">" === t2[e2]) { + if (o2 ? "-" === t2[e2 - 1] && "-" === t2[e2 - 2] && (o2 = false, r2--) : r2--, 0 === r2) break; + } else "[" === t2[e2] ? s2 = true : l2 += t2[e2]; else { - if (r2 && D(t2, "!ENTITY", e2)) { - let s3, r3; - if (e2 += 7, [s3, r3, e2] = this.readEntityExp(t2, e2 + 1, this.suppressValidationErr), -1 === r3.indexOf("&")) { + if (s2 && B(t2, "!ENTITY", e2)) { + let r3, s3; + if (e2 += 7, [r3, s3, e2] = this.readEntityExp(t2, e2 + 1, this.suppressValidationErr), -1 === s3.indexOf("&")) { if (false !== this.options.enabled && null != this.options.maxEntityCount && i2 >= this.options.maxEntityCount) throw new Error(`Entity count (${i2 + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`); - n2[s3] = r3, i2++; + n2[r3] = s3, i2++; } - } else if (r2 && D(t2, "!ELEMENT", e2)) { + } else if (s2 && B(t2, "!ELEMENT", e2)) { e2 += 8; const { index: n3 } = this.readElementExp(t2, e2 + 1); e2 = n3; - } else if (r2 && D(t2, "!ATTLIST", e2)) e2 += 8; - else if (r2 && D(t2, "!NOTATION", e2)) { + } else if (s2 && B(t2, "!ATTLIST", e2)) e2 += 8; + else if (s2 && B(t2, "!NOTATION", e2)) { e2 += 9; const { index: n3 } = this.readNotationExp(t2, e2 + 1, this.suppressValidationErr); e2 = n3; } else { - if (!D(t2, "!--", e2)) throw new Error("Invalid DOCTYPE"); + if (!B(t2, "!--", e2)) throw new Error("Invalid DOCTYPE"); o2 = true; } - s2++, a2 = ""; + r2++, l2 = ""; } - if (0 !== s2) throw new Error("Unclosed DOCTYPE"); + else a2 = t2[e2], l2 += t2[e2]; + else t2[e2] === a2 && (a2 = null), l2 += t2[e2]; + if (null !== a2 || 0 !== r2) throw new Error("Unclosed DOCTYPE"); } return { entities: n2, i: e2 }; } readEntityExp(t2, e2) { - const n2 = e2 = I(t2, e2); + const n2 = e2 = U(t2, e2); for (; e2 < t2.length && !/\s/.test(t2[e2]) && '"' !== t2[e2] && "'" !== t2[e2]; ) e2++; let i2 = t2.substring(n2, e2); - if (M(i2), e2 = I(t2, e2), !this.suppressValidationErr) { + if (G(i2, { xmlVersion: this.xmlVersion }), e2 = U(t2, e2), !this.suppressValidationErr) { if ("SYSTEM" === t2.substring(e2, e2 + 6).toUpperCase()) throw new Error("External entities are not supported"); if ("%" === t2[e2]) throw new Error("Parameter entities are not supported"); } - let s2 = ""; - if ([e2, s2] = this.readIdentifierVal(t2, e2, "entity"), false !== this.options.enabled && null != this.options.maxEntitySize && s2.length > this.options.maxEntitySize) throw new Error(`Entity "${i2}" size (${s2.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`); - return [i2, s2, --e2]; + let r2 = ""; + if ([e2, r2] = this.readIdentifierVal(t2, e2, "entity"), false !== this.options.enabled && null != this.options.maxEntitySize && r2.length > this.options.maxEntitySize) throw new Error(`Entity "${i2}" size (${r2.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`); + return [i2, r2, --e2]; } readNotationExp(t2, e2) { - const n2 = e2 = I(t2, e2); + const n2 = e2 = U(t2, e2); for (; e2 < t2.length && !/\s/.test(t2[e2]); ) e2++; let i2 = t2.substring(n2, e2); - !this.suppressValidationErr && M(i2), e2 = I(t2, e2); - const s2 = t2.substring(e2, e2 + 6).toUpperCase(); - if (!this.suppressValidationErr && "SYSTEM" !== s2 && "PUBLIC" !== s2) throw new Error(`Expected SYSTEM or PUBLIC, found "${s2}"`); - e2 += s2.length, e2 = I(t2, e2); - let r2 = null, o2 = null; - if ("PUBLIC" === s2) [e2, r2] = this.readIdentifierVal(t2, e2, "publicIdentifier"), '"' !== t2[e2 = I(t2, e2)] && "'" !== t2[e2] || ([e2, o2] = this.readIdentifierVal(t2, e2, "systemIdentifier")); - else if ("SYSTEM" === s2 && ([e2, o2] = this.readIdentifierVal(t2, e2, "systemIdentifier"), !this.suppressValidationErr && !o2)) throw new Error("Missing mandatory system identifier for SYSTEM notation"); - return { notationName: i2, publicIdentifier: r2, systemIdentifier: o2, index: --e2 }; + !this.suppressValidationErr && G(i2, { xmlVersion: this.xmlVersion }), e2 = U(t2, e2); + const r2 = t2.substring(e2, e2 + 6).toUpperCase(); + if (!this.suppressValidationErr && "SYSTEM" !== r2 && "PUBLIC" !== r2) throw new Error(`Expected SYSTEM or PUBLIC, found "${r2}"`); + e2 += r2.length, e2 = U(t2, e2); + let s2 = null, o2 = null; + if ("PUBLIC" === r2) [e2, s2] = this.readIdentifierVal(t2, e2, "publicIdentifier"), '"' !== t2[e2 = U(t2, e2)] && "'" !== t2[e2] || ([e2, o2] = this.readIdentifierVal(t2, e2, "systemIdentifier")); + else if ("SYSTEM" === r2 && ([e2, o2] = this.readIdentifierVal(t2, e2, "systemIdentifier"), !this.suppressValidationErr && !o2)) throw new Error("Missing mandatory system identifier for SYSTEM notation"); + return { notationName: i2, publicIdentifier: s2, systemIdentifier: o2, index: --e2 }; } readIdentifierVal(t2, e2, n2) { let i2 = ""; - const s2 = t2[e2]; - if ('"' !== s2 && "'" !== s2) throw new Error(`Expected quoted string, found "${s2}"`); - const r2 = ++e2; - for (; e2 < t2.length && t2[e2] !== s2; ) e2++; - if (i2 = t2.substring(r2, e2), t2[e2] !== s2) throw new Error(`Unterminated ${n2} value`); + const r2 = t2[e2]; + if ('"' !== r2 && "'" !== r2) throw new Error(`Expected quoted string, found "${r2}"`); + const s2 = ++e2; + for (; e2 < t2.length && t2[e2] !== r2; ) e2++; + if (i2 = t2.substring(s2, e2), t2[e2] !== r2) throw new Error(`Unterminated ${n2} value`); return [++e2, i2]; } readElementExp(t2, e2) { - const n2 = e2 = I(t2, e2); + const n2 = e2 = U(t2, e2); for (; e2 < t2.length && !/\s/.test(t2[e2]); ) e2++; let i2 = t2.substring(n2, e2); - if (!this.suppressValidationErr && !r(i2)) throw new Error(`Invalid element name: "${i2}"`); - let s2 = ""; - if ("E" === t2[e2 = I(t2, e2)] && D(t2, "MPTY", e2)) e2 += 4; - else if ("A" === t2[e2] && D(t2, "NY", e2)) e2 += 2; + if (!this.suppressValidationErr && !R(i2, { xmlVersion: this.xmlVersion })) throw new Error(`Invalid element name: "${i2}"`); + let r2 = ""; + if ("E" === t2[e2 = U(t2, e2)] && B(t2, "MPTY", e2)) e2 += 4; + else if ("A" === t2[e2] && B(t2, "NY", e2)) e2 += 2; else if ("(" === t2[e2]) { const n3 = ++e2; for (; e2 < t2.length && ")" !== t2[e2]; ) e2++; - if (s2 = t2.substring(n3, e2), ")" !== t2[e2]) throw new Error("Unterminated content model"); + if (r2 = t2.substring(n3, e2), ")" !== t2[e2]) throw new Error("Unterminated content model"); } else if (!this.suppressValidationErr) throw new Error(`Invalid Element Expression, found "${t2[e2]}"`); - return { elementName: i2, contentModel: s2.trim(), index: e2 }; + return { elementName: i2, contentModel: r2.trim(), index: e2 }; } readAttlistExp(t2, e2) { - let n2 = e2 = I(t2, e2); + let n2 = e2 = U(t2, e2); for (; e2 < t2.length && !/\s/.test(t2[e2]); ) e2++; let i2 = t2.substring(n2, e2); - for (M(i2), n2 = e2 = I(t2, e2); e2 < t2.length && !/\s/.test(t2[e2]); ) e2++; - let s2 = t2.substring(n2, e2); - if (!M(s2)) throw new Error(`Invalid attribute name: "${s2}"`); - e2 = I(t2, e2); - let r2 = ""; + for (G(i2, { xmlVersion: this.xmlVersion }), n2 = e2 = U(t2, e2); e2 < t2.length && !/\s/.test(t2[e2]); ) e2++; + let r2 = t2.substring(n2, e2); + if (!G(r2, { xmlVersion: this.xmlVersion })) throw new Error(`Invalid attribute name: "${r2}"`); + e2 = U(t2, e2); + let s2 = ""; if ("NOTATION" === t2.substring(e2, e2 + 8).toUpperCase()) { - if (r2 = "NOTATION", "(" !== t2[e2 = I(t2, e2 += 8)]) throw new Error(`Expected '(', found "${t2[e2]}"`); + if (s2 = "NOTATION", "(" !== t2[e2 = U(t2, e2 += 8)]) throw new Error(`Expected '(', found "${t2[e2]}"`); e2++; let n3 = []; for (; e2 < t2.length && ")" !== t2[e2]; ) { const i3 = e2; for (; e2 < t2.length && "|" !== t2[e2] && ")" !== t2[e2]; ) e2++; - let s3 = t2.substring(i3, e2); - if (s3 = s3.trim(), !M(s3)) throw new Error(`Invalid notation name: "${s3}"`); - n3.push(s3), "|" === t2[e2] && (e2++, e2 = I(t2, e2)); + let r3 = t2.substring(i3, e2); + if (r3 = r3.trim(), !G(r3, { xmlVersion: this.xmlVersion })) throw new Error(`Invalid notation name: "${r3}"`); + n3.push(r3), "|" === t2[e2] && (e2++, e2 = U(t2, e2)); } if (")" !== t2[e2]) throw new Error("Unterminated list of notations"); - e2++, r2 += " (" + n3.join("|") + ")"; + e2++, s2 += " (" + n3.join("|") + ")"; } else { const n3 = e2; for (; e2 < t2.length && !/\s/.test(t2[e2]); ) e2++; - r2 += t2.substring(n3, e2); + s2 += t2.substring(n3, e2); const i3 = ["CDATA", "ID", "IDREF", "IDREFS", "ENTITY", "ENTITIES", "NMTOKEN", "NMTOKENS"]; - if (!this.suppressValidationErr && !i3.includes(r2.toUpperCase())) throw new Error(`Invalid attribute type: "${r2}"`); + if (!this.suppressValidationErr && !i3.includes(s2.toUpperCase())) throw new Error(`Invalid attribute type: "${s2}"`); } - e2 = I(t2, e2); + e2 = U(t2, e2); let o2 = ""; - return "#REQUIRED" === t2.substring(e2, e2 + 8).toUpperCase() ? (o2 = "#REQUIRED", e2 += 8) : "#IMPLIED" === t2.substring(e2, e2 + 7).toUpperCase() ? (o2 = "#IMPLIED", e2 += 7) : [e2, o2] = this.readIdentifierVal(t2, e2, "ATTLIST"), { elementName: i2, attributeName: s2, attributeType: r2, defaultValue: o2, index: e2 }; + return "#REQUIRED" === t2.substring(e2, e2 + 8).toUpperCase() ? (o2 = "#REQUIRED", e2 += 8) : "#IMPLIED" === t2.substring(e2, e2 + 7).toUpperCase() ? (o2 = "#IMPLIED", e2 += 7) : [e2, o2] = this.readIdentifierVal(t2, e2, "ATTLIST"), { elementName: i2, attributeName: r2, attributeType: s2, defaultValue: o2, index: e2 }; } } - const I = (t2, e2) => { + const U = (t2, e2) => { for (; e2 < t2.length && /\s/.test(t2[e2]); ) e2++; return e2; }; - function D(t2, e2, n2) { + function B(t2, e2, n2) { for (let i2 = 0; i2 < e2.length; i2++) if (e2[i2] !== t2[n2 + i2 + 1]) return false; return true; } - function M(t2) { - if (r(t2)) return t2; + function G(t2, e2) { + if (R(t2, { xmlVersion: e2 })) return t2; throw new Error(`Invalid entity name ${t2}`); } - const j = /^[-+]?0x[a-fA-F0-9]+$/, V = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/, L = { hex: true, leadingZeros: true, decimalPoint: ".", eNotation: true, infinity: "original" }; - const k = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/; - class F { + const X = [48, 1632, 1776, 2406, 2534, 2662, 2790, 2918, 3046, 3174, 3302, 3430, 3558, 3664, 3792, 3872, 4160, 4240, 6112, 6160, 6470, 6608, 6784, 6800, 6992, 7088, 7232, 7248, 65296, 120782, 120792, 120802, 120812, 120822, 66720, 68912, 69734, 69872, 69942, 70096, 70384, 70736, 70864, 71248, 71360, 71472, 71904, 72016, 72688, 72784, 73040, 73120, 73552, 92768, 92864, 93008, 123200, 123632, 124144, 125264, 130032], W = /* @__PURE__ */ new Map(), z = 1632, Y = new Uint8Array(63904).fill(255); + for (const t2 of X) for (let e2 = 0; e2 < 10; e2++) { + const n2 = t2 + e2; + n2 <= 65535 ? Y[n2 - z] = e2 : W.set(n2, e2); + } + const H = /* @__PURE__ */ new Set([8722, 65293, 65123]), Q = /^[-+]?0x[a-fA-F0-9]+$/, J = /^0b[01]+$/, Z = /^0o[0-7]+$/, K = /^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/, tt = { hex: true, binary: false, octal: false, leadingZeros: true, decimalPoint: ".", eNotation: true, infinity: "original", unicode: false }; + function et(t2, e2 = {}) { + if (e2 = Object.assign({}, tt, e2), !t2 || "string" != typeof t2) return t2; + let n2 = t2.trim(); + if (0 === n2.length) return t2; + if (void 0 !== e2.skipLike && e2.skipLike.test(n2)) return t2; + if ("0" === n2) return 0; + if (e2.unicode && (n2 = (function(t3) { + if ("string" != typeof t3) return t3; + const e3 = t3.length; + if (0 === e3) return t3; + let n3 = -1; + for (let i3 = 0; i3 < e3; i3++) { + const r2 = t3.charCodeAt(i3); + if (!(r2 >= 48 && r2 <= 57 || 45 === r2)) { + if (r2 < z) { + if (H.has(r2)) { + n3 = i3; + break; + } + } else if (r2 >= 55296 && r2 <= 56319) { + if (i3 + 1 < e3) { + const e4 = t3.charCodeAt(i3 + 1); + if (e4 >= 56320 && e4 <= 57343) { + const t4 = 65536 + (r2 - 55296 << 10) + (e4 - 56320); + if (W.has(t4)) { + n3 = i3; + break; + } + } + } + } else if (255 !== Y[r2 - z] || H.has(r2)) { + n3 = i3; + break; + } + } + } + if (-1 === n3) return t3; + const i2 = []; + n3 > 0 && i2.push(t3.slice(0, n3)); + for (let r2 = n3; r2 < e3; r2++) { + const n4 = t3.charCodeAt(r2); + if (n4 >= 48 && n4 <= 57 || 45 === n4) { + i2.push(t3[r2]); + continue; + } + if (n4 < z) { + i2.push(H.has(n4) ? "-" : t3[r2]); + continue; + } + if (n4 >= 55296 && n4 <= 56319) { + if (r2 + 1 < e3) { + const e4 = t3.charCodeAt(r2 + 1); + if (e4 >= 56320 && e4 <= 57343) { + const t4 = 65536 + (n4 - 55296 << 10) + (e4 - 56320), s3 = W.get(t4); + if (void 0 !== s3) { + i2.push(String.fromCharCode(s3 + 48)), r2++; + continue; + } + } + } + i2.push(t3[r2]); + continue; + } + if (H.has(n4)) { + i2.push("-"); + continue; + } + const s2 = Y[n4 - z]; + i2.push(255 !== s2 ? String.fromCharCode(s2 + 48) : t3[r2]); + } + return i2.join(""); + })(n2), "0" === n2)) return 0; + if (e2.hex && Q.test(n2)) return it(n2, 16); + if (e2.binary && J.test(n2)) return it(n2, 2); + if (e2.octal && Z.test(n2)) return it(n2, 8); + if (isFinite(n2)) { + if (n2.includes("e") || n2.includes("E")) return (function(t3, e3, n3) { + if (!n3.eNotation) return t3; + const i2 = e3.match(nt); + if (i2) { + let r2 = i2[1] || ""; + const s2 = -1 === i2[3].indexOf("e") ? "E" : "e", o2 = i2[2], a2 = r2 ? e3[o2.length + 1] === s2 : e3[o2.length] === s2; + return o2.length > 1 && a2 ? t3 : (1 !== o2.length || !i2[3].startsWith(`.${s2}`) && i2[3][0] !== s2) && o2.length > 0 ? n3.leadingZeros && !a2 ? Number(e3) : t3 : Number(e3); + } + return t3; + })(t2, n2, e2); + { + const i2 = K.exec(n2); + if (i2) { + const r2 = i2[1] || "", s2 = i2[2]; + let o2 = (function(t3) { + if (t3 && -1 !== t3.indexOf(".")) { + let e3 = t3.length; + for (; e3 > 0 && 48 === t3.charCodeAt(e3 - 1); ) e3--; + return "." === (t3 = t3.slice(0, e3)) ? t3 = "0" : "." === t3[0] ? t3 = "0" + t3 : "." === t3[t3.length - 1] && (t3 = t3.substring(0, t3.length - 1)), t3; + } + return t3; + })(i2[3]); + const a2 = r2 ? "." === n2[s2.length + 1] : "." === n2[s2.length]; + if (!e2.leadingZeros && (s2.length > 1 || 1 === s2.length && !a2)) return t2; + { + const i3 = Number(n2), a3 = String(i3); + if (0 === i3) return i3; + if (-1 !== a3.search(/[eE]/)) return e2.eNotation ? i3 : t2; + if (-1 !== n2.indexOf(".")) return "0" === a3 || a3 === o2 || a3 === `${r2}${o2}` ? i3 : t2; + let l2 = s2 ? o2 : n2; + return s2 ? l2 === a3 || r2 + l2 === a3 ? i3 : t2 : l2 === a3 || l2 === r2 + a3 ? i3 : t2; + } + } + return t2; + } + } + { + const i2 = Number(n2); + return Number.isNaN(i2) ? t2 : (function(t3, e3, n3) { + const i3 = e3 === 1 / 0; + switch (n3.infinity.toLowerCase()) { + case "null": + return null; + case "infinity": + return e3; + case "string": + return i3 ? "Infinity" : "-Infinity"; + default: + return t3; + } + })(t2, i2, e2); + } + } + const nt = /^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/; + function it(t2, e2) { + const n2 = t2.trim(); + if (2 !== e2 && 8 !== e2 || (t2 = n2.substring(2)), parseInt) return parseInt(t2, e2); + if (Number.parseInt) return Number.parseInt(t2, e2); + if (window && window.parseInt) return window.parseInt(t2, e2); + throw new Error("parseInt, Number.parseInt, window.parseInt are not supported"); + } + class rt { constructor(t2) { this._matcher = t2; } @@ -54973,6 +55156,12 @@ var require_fxp = __commonJS({ const n2 = e2[e2.length - 1]; return void 0 !== n2.values && t2 in n2.values; } + getAnyParentAttr(t2) { + return this._matcher.getAnyParentAttr(t2); + } + hasAnyParentAttr(t2) { + return this._matcher.hasAnyParentAttr(t2); + } getPosition() { const t2 = this._matcher.path; return 0 === t2.length ? -1 : t2[t2.length - 1].position ?? 0; @@ -55000,26 +55189,33 @@ var require_fxp = __commonJS({ return t2.matchesAny(this._matcher); } } - class R { + class st { constructor(t2 = {}) { - this.separator = t2.separator || ".", this.path = [], this.siblingStacks = [], this._pathStringCache = null, this._view = new F(this); + this.separator = t2.separator || ".", this.path = [], this.siblingStacks = [], this._pathStringCache = null, this._view = new rt(this), this._keptAttrs = []; } - push(t2, e2 = null, n2 = null) { + push(t2, e2 = null, n2 = null, i2 = null) { this._pathStringCache = null, this.path.length > 0 && (this.path[this.path.length - 1].values = void 0); - const i2 = this.path.length; - this.siblingStacks[i2] || (this.siblingStacks[i2] = /* @__PURE__ */ new Map()); - const s2 = this.siblingStacks[i2], r2 = n2 ? `${n2}:${t2}` : t2, o2 = s2.get(r2) || 0; - let a2 = 0; - for (const t3 of s2.values()) a2 += t3; - s2.set(r2, o2 + 1); - const h2 = { tag: t2, position: a2, counter: o2 }; - null != n2 && (h2.namespace = n2), null != e2 && (h2.values = e2), this.path.push(h2); + const r2 = this.path.length; + let s2 = this.siblingStacks[r2]; + s2 || (s2 = { counts: /* @__PURE__ */ new Map(), total: 0 }, this.siblingStacks[r2] = s2); + const o2 = n2 ? `${n2}:${t2}` : t2, a2 = s2.counts.get(o2) || 0, l2 = s2.total; + s2.counts.set(o2, a2 + 1), s2.total++; + const c2 = { tag: t2, position: l2, counter: a2 }; + null != n2 && (c2.namespace = n2), null != e2 && (c2.values = e2), this.path.push(c2); + const p2 = this.path.length, h2 = null !== i2 ? i2.keep : null; + if (null != h2 && h2.length > 0 && e2) for (let t3 = 0; t3 < h2.length; t3++) { + const n3 = h2[t3]; + void 0 !== e2[n3] && this._keptAttrs.push({ depth: p2, name: n3, value: e2[n3] }); + } } pop() { if (0 === this.path.length) return; this._pathStringCache = null; const t2 = this.path.pop(); - return this.siblingStacks.length > this.path.length + 1 && (this.siblingStacks.length = this.path.length + 1), t2; + this.siblingStacks.length > this.path.length + 1 && (this.siblingStacks.length = this.path.length + 1); + const e2 = this.path.length + 1; + for (; this._keptAttrs.length > 0 && this._keptAttrs[this._keptAttrs.length - 1].depth >= e2; ) this._keptAttrs.pop(); + return t2; } updateCurrent(t2) { if (this.path.length > 0) { @@ -55041,6 +55237,15 @@ var require_fxp = __commonJS({ const e2 = this.path[this.path.length - 1]; return void 0 !== e2.values && t2 in e2.values; } + getAnyParentAttr(t2) { + const e2 = this._keptAttrs; + for (let n2 = e2.length - 1; n2 >= 0; n2--) if (e2[n2].name === t2) return e2[n2].value; + } + hasAnyParentAttr(t2) { + const e2 = this._keptAttrs; + for (let n2 = e2.length - 1; n2 >= 0; n2--) if (e2[n2].name === t2) return true; + return false; + } getPosition() { return 0 === this.path.length ? -1 : this.path[this.path.length - 1].position ?? 0; } @@ -55066,7 +55271,7 @@ var require_fxp = __commonJS({ return this.path.map((t2) => t2.tag); } reset() { - this._pathStringCache = null, this.path = [], this.siblingStacks = []; + this._pathStringCache = null, this.path = [], this.siblingStacks = [], this._keptAttrs = []; } matches(t2) { const e2 = t2.segments; @@ -55084,12 +55289,12 @@ var require_fxp = __commonJS({ if ("deep-wildcard" === i2.type) { if (n2--, n2 < 0) return true; const i3 = t2[n2]; - let s2 = false; + let r2 = false; for (let t3 = e2; t3 >= 0; t3--) if (this._matchSegment(i3, this.path[t3], t3 === this.path.length - 1)) { - e2 = t3 - 1, n2--, s2 = true; + e2 = t3 - 1, n2--, r2 = true; break; } - if (!s2) return false; + if (!r2) return false; } else { if (!this._matchSegment(i2, this.path[e2], e2 === this.path.length - 1)) return false; e2--, n2--; @@ -55119,16 +55324,16 @@ var require_fxp = __commonJS({ return t2.matchesAny(this); } snapshot() { - return { path: this.path.map((t2) => ({ ...t2 })), siblingStacks: this.siblingStacks.map((t2) => new Map(t2)) }; + return { path: this.path.map((t2) => ({ ...t2 })), siblingStacks: this.siblingStacks.map((t2) => t2 ? { counts: new Map(t2.counts), total: t2.total } : t2), keptAttrs: this._keptAttrs.map((t2) => ({ ...t2 })) }; } restore(t2) { - this._pathStringCache = null, this.path = t2.path.map((t3) => ({ ...t3 })), this.siblingStacks = t2.siblingStacks.map((t3) => new Map(t3)); + this._pathStringCache = null, this.path = t2.path.map((t3) => ({ ...t3 })), this.siblingStacks = t2.siblingStacks.map((t3) => t3 ? { counts: new Map(t3.counts), total: t3.total } : t3), this._keptAttrs = (t2.keptAttrs || []).map((t3) => ({ ...t3 })); } readOnly() { return this._view; } } - class G { + class ot { constructor(t2, e2 = {}, n2) { this.pattern = t2, this.separator = e2.separator || ".", this.segments = this._parse(t2), this.data = n2, this._hasDeepWildcard = this.segments.some((t3) => "deep-wildcard" === t3.type), this._hasAttributeCondition = this.segments.some((t3) => void 0 !== t3.attrName), this._hasPositionSelector = this.segments.some((t3) => void 0 !== t3.position); } @@ -55141,29 +55346,29 @@ var require_fxp = __commonJS({ _parseSegment(t2) { const e2 = { type: "tag" }; let n2 = null, i2 = t2; - const s2 = t2.match(/^([^\[]+)(\[[^\]]*\])(.*)$/); - if (s2 && (i2 = s2[1] + s2[3], s2[2])) { - const t3 = s2[2].slice(1, -1); + const r2 = t2.match(/^([^\[]+)(\[[^\]]*\])(.*)$/); + if (r2 && (i2 = r2[1] + r2[3], r2[2])) { + const t3 = r2[2].slice(1, -1); t3 && (n2 = t3); } - let r2, o2, a2 = i2; + let s2, o2, a2 = i2; if (i2.includes("::")) { const e3 = i2.indexOf("::"); - if (r2 = i2.substring(0, e3).trim(), a2 = i2.substring(e3 + 2).trim(), !r2) throw new Error(`Invalid namespace in pattern: ${t2}`); + if (s2 = i2.substring(0, e3).trim(), a2 = i2.substring(e3 + 2).trim(), !s2) throw new Error(`Invalid namespace in pattern: ${t2}`); } - let h2 = null; + let l2 = null; if (a2.includes(":")) { const t3 = a2.lastIndexOf(":"), e3 = a2.substring(0, t3).trim(), n3 = a2.substring(t3 + 1).trim(); - ["first", "last", "odd", "even"].includes(n3) || /^nth\(\d+\)$/.test(n3) ? (o2 = e3, h2 = n3) : o2 = a2; + ["first", "last", "odd", "even"].includes(n3) || /^nth\(\d+\)$/.test(n3) ? (o2 = e3, l2 = n3) : o2 = a2; } else o2 = a2; if (!o2) throw new Error(`Invalid segment pattern: ${t2}`); - if (e2.tag = o2, r2 && (e2.namespace = r2), n2) if (n2.includes("=")) { + if (e2.tag = o2, s2 && (e2.namespace = s2), n2) if (n2.includes("=")) { const t3 = n2.indexOf("="); e2.attrName = n2.substring(0, t3).trim(), e2.attrValue = n2.substring(t3 + 1).trim(); } else e2.attrName = n2.trim(); - if (h2) { - const t3 = h2.match(/^nth\((\d+)\)$/); - t3 ? (e2.position = "nth", e2.positionValue = parseInt(t3[1], 10)) : e2.position = h2; + if (l2) { + const t3 = l2.match(/^nth\((\d+)\)$/); + t3 ? (e2.position = "nth", e2.positionValue = parseInt(t3[1], 10)) : e2.position = l2; } return e2; } @@ -55183,14 +55388,21 @@ var require_fxp = __commonJS({ return this.pattern; } } - class B { + class at { constructor() { - this._byDepthAndTag = /* @__PURE__ */ new Map(), this._wildcardByDepth = /* @__PURE__ */ new Map(), this._deepWildcards = [], this._patterns = /* @__PURE__ */ new Set(), this._sealed = false; + this._byDepthAndTag = /* @__PURE__ */ new Map(), this._wildcardByDepth = /* @__PURE__ */ new Map(), this._deepWildcards = [], this._deepByTerminalTag = /* @__PURE__ */ new Map(), this._patterns = /* @__PURE__ */ new Set(), this._sealed = false; } add(t2) { if (this._sealed) throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions."); if (this._patterns.has(t2.pattern)) return this; - if (this._patterns.add(t2.pattern), t2.hasDeepWildcard()) return this._deepWildcards.push(t2), this; + if (this._patterns.add(t2.pattern), t2.hasDeepWildcard()) { + const e3 = t2.segments[t2.segments.length - 1]; + if (e3 && "deep-wildcard" !== e3.type && "*" !== e3.tag) { + const n3 = e3.tag; + this._deepByTerminalTag.has(n3) || this._deepByTerminalTag.set(n3, []), this._deepByTerminalTag.get(n3).push(t2); + } else this._deepWildcards.push(t2); + return this; + } const e2 = t2.length, n2 = t2.segments[t2.segments.length - 1], i2 = n2?.tag; if (i2 && "*" !== i2) { const n3 = `${e2}:${i2}`; @@ -55218,25 +55430,29 @@ var require_fxp = __commonJS({ return null !== this.findMatch(t2); } findMatch(t2) { - const e2 = t2.getDepth(), n2 = `${e2}:${t2.getCurrentTag()}`, i2 = this._byDepthAndTag.get(n2); - if (i2) { - for (let e3 = 0; e3 < i2.length; e3++) if (t2.matches(i2[e3])) return i2[e3]; + const e2 = t2.getDepth(), n2 = t2.getCurrentTag(), i2 = `${e2}:${n2}`, r2 = this._byDepthAndTag.get(i2); + if (r2) { + for (let e3 = 0; e3 < r2.length; e3++) if (t2.matches(r2[e3])) return r2[e3]; } const s2 = this._wildcardByDepth.get(e2); if (s2) { for (let e3 = 0; e3 < s2.length; e3++) if (t2.matches(s2[e3])) return s2[e3]; } + const o2 = this._deepByTerminalTag.get(n2); + if (o2) { + for (let e3 = 0; e3 < o2.length; e3++) if (t2.matches(o2[e3])) return o2[e3]; + } for (let e3 = 0; e3 < this._deepWildcards.length; e3++) if (t2.matches(this._deepWildcards[e3])) return this._deepWildcards[e3]; return null; } } - const U = { cent: "\xA2", pound: "\xA3", curren: "\xA4", yen: "\xA5", euro: "\u20AC", dollar: "$", euro: "\u20AC", fnof: "\u0192", inr: "\u20B9", af: "\u060B", birr: "\u1265\u122D", peso: "\u20B1", rub: "\u20BD", won: "\u20A9", yuan: "\xA5", cedil: "\xB8" }, W = { amp: "&", apos: "'", gt: ">", lt: "<", quot: '"' }, X = { nbsp: "\xA0", copy: "\xA9", reg: "\xAE", trade: "\u2122", mdash: "\u2014", ndash: "\u2013", hellip: "\u2026", laquo: "\xAB", raquo: "\xBB", lsquo: "\u2018", rsquo: "\u2019", ldquo: "\u201C", rdquo: "\u201D", bull: "\u2022", para: "\xB6", sect: "\xA7", deg: "\xB0", frac12: "\xBD", frac14: "\xBC", frac34: "\xBE" }, Y = new Set("!?\\\\/[]$%{}^&*()<>|+"); - function z(t2) { + const lt2 = { cent: "\xA2", pound: "\xA3", curren: "\xA4", yen: "\xA5", euro: "\u20AC", dollar: "$", fnof: "\u0192", inr: "\u20B9", af: "\u060B", birr: "\u1265\u122D", peso: "\u20B1", rub: "\u20BD", won: "\u20A9", yuan: "\xA5", cedil: "\xB8" }, ct = { amp: "&", apos: "'", gt: ">", lt: "<", quot: '"' }, pt = { nbsp: "\xA0", copy: "\xA9", reg: "\xAE", trade: "\u2122", mdash: "\u2014", ndash: "\u2013", hellip: "\u2026", laquo: "\xAB", raquo: "\xBB", lsquo: "\u2018", rsquo: "\u2019", ldquo: "\u201C", rdquo: "\u201D", bull: "\u2022", para: "\xB6", sect: "\xA7", deg: "\xB0", frac12: "\xBD", frac14: "\xBC", frac34: "\xBE" }, ht = Object.freeze({ ALLOW: "allow", BLOCK: "block", THROW: "throw" }), dt = new Set("!?\\\\/[]$%{}^&*()<>|+"); + function ut(t2) { if ("#" === t2[0]) throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t2}"`); - for (const e2 of t2) if (Y.has(e2)) throw new Error(`[EntityReplacer] Invalid character '${e2}' in entity name: "${t2}"`); + for (const e2 of t2) if (dt.has(e2)) throw new Error(`[EntityReplacer] Invalid character '${e2}' in entity name: "${t2}"`); return t2; } - function q(...t2) { + function ft(...t2) { const e2 = /* @__PURE__ */ Object.create(null); for (const n2 of t2) if (n2) for (const t3 of Object.keys(n2)) { const i2 = n2[t3]; @@ -55248,27 +55464,40 @@ var require_fxp = __commonJS({ } return e2; } - const Z = "external", J = "base", K = "all", Q = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 }), H = /* @__PURE__ */ new Set([9, 10, 13]); - class tt { + const gt = "external", mt = "base", xt = "all", bt = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 }), yt = /* @__PURE__ */ new Set([9, 10, 13]); + class Nt { constructor(t2 = {}) { var e2; - this._limit = t2.limit || {}, this._maxTotalExpansions = this._limit.maxTotalExpansions || 0, this._maxExpandedLength = this._limit.maxExpandedLength || 0, this._postCheck = "function" == typeof t2.postCheck ? t2.postCheck : (t3) => t3, this._limitTiers = (e2 = this._limit.applyLimitsTo ?? Z) && e2 !== Z ? e2 === K ? /* @__PURE__ */ new Set([K]) : e2 === J ? /* @__PURE__ */ new Set([J]) : Array.isArray(e2) ? new Set(e2) : /* @__PURE__ */ new Set([Z]) : /* @__PURE__ */ new Set([Z]), this._numericAllowed = t2.numericAllowed ?? true, this._baseMap = q(W, t2.namedEntities || null), this._externalMap = /* @__PURE__ */ Object.create(null), this._inputMap = /* @__PURE__ */ Object.create(null), this._totalExpansions = 0, this._expandedLength = 0, this._removeSet = new Set(t2.remove && Array.isArray(t2.remove) ? t2.remove : []), this._leaveSet = new Set(t2.leave && Array.isArray(t2.leave) ? t2.leave : []); + this._limit = t2.limit || {}, this._maxTotalExpansions = this._limit.maxTotalExpansions || 0, this._maxExpandedLength = this._limit.maxExpandedLength || 0, this._postCheck = "function" == typeof t2.postCheck ? t2.postCheck : (t3) => t3, this._limitTiers = (e2 = this._limit.applyLimitsTo ?? gt) && e2 !== gt ? e2 === xt ? /* @__PURE__ */ new Set([xt]) : e2 === mt ? /* @__PURE__ */ new Set([mt]) : Array.isArray(e2) ? new Set(e2) : /* @__PURE__ */ new Set([gt]) : /* @__PURE__ */ new Set([gt]), this._numericAllowed = t2.numericAllowed ?? true, this._baseMap = ft(ct, t2.namedEntities || null), this._externalMap = /* @__PURE__ */ Object.create(null), this._inputMap = /* @__PURE__ */ Object.create(null), this._totalExpansions = 0, this._expandedLength = 0, this._removeSet = new Set(t2.remove && Array.isArray(t2.remove) ? t2.remove : []), this._leaveSet = new Set(t2.leave && Array.isArray(t2.leave) ? t2.leave : []); const n2 = (function(t3) { - if (!t3) return { xmlVersion: 1, onLevel: Q.allow, nullLevel: Q.remove }; - const e3 = 1.1 === t3.xmlVersion ? 1.1 : 1, n3 = Q[t3.onNCR] ?? Q.allow, i2 = Q[t3.nullNCR] ?? Q.remove; - return { xmlVersion: e3, onLevel: n3, nullLevel: Math.max(i2, Q.remove) }; + if (!t3) return { xmlVersion: 1, onLevel: bt.allow, nullLevel: bt.remove }; + const e3 = 1.1 === t3.xmlVersion ? 1.1 : 1, n3 = bt[t3.onNCR] ?? bt.allow, i2 = bt[t3.nullNCR] ?? bt.remove; + return { xmlVersion: e3, onLevel: n3, nullLevel: Math.max(i2, bt.remove) }; })(t2.ncr); - this._ncrXmlVersion = n2.xmlVersion, this._ncrOnLevel = n2.onLevel, this._ncrNullLevel = n2.nullLevel; + this._ncrXmlVersion = n2.xmlVersion, this._ncrOnLevel = n2.onLevel, this._ncrNullLevel = n2.nullLevel, this._onExternalEntity = "function" == typeof t2.onExternalEntity ? t2.onExternalEntity : null, this._onInputEntity = "function" == typeof t2.onInputEntity ? t2.onInputEntity : null; + } + _applyRegistrationHook(t2, e2, n2, i2) { + if (!t2) return true; + const r2 = t2(e2, n2); + if (r2 === ht.BLOCK) return false; + if (r2 === ht.THROW) throw new Error(`[EntityDecoder] Registration of ${i2} entity "&${e2};" was rejected by hook`); + return true; } setExternalEntities(t2) { - if (t2) for (const e2 of Object.keys(t2)) z(e2); - this._externalMap = q(t2); + if (t2) for (const e3 of Object.keys(t2)) ut(e3); + if (!this._onExternalEntity) return void (this._externalMap = ft(t2)); + const e2 = ft(t2), n2 = /* @__PURE__ */ Object.create(null); + for (const [t3, i2] of Object.entries(e2)) this._applyRegistrationHook(this._onExternalEntity, t3, i2, "external") && (n2[t3] = i2); + this._externalMap = n2; } addExternalEntity(t2, e2) { - z(t2), "string" == typeof e2 && -1 === e2.indexOf("&") && (this._externalMap[t2] = e2); + ut(t2), "string" == typeof e2 && -1 === e2.indexOf("&") && this._applyRegistrationHook(this._onExternalEntity, t2, e2, "external") && (this._externalMap[t2] = e2); } addInputEntities(t2) { - this._totalExpansions = 0, this._expandedLength = 0, this._inputMap = q(t2); + if (this._totalExpansions = 0, this._expandedLength = 0, !this._onInputEntity) return void (this._inputMap = ft(t2)); + const e2 = ft(t2), n2 = /* @__PURE__ */ Object.create(null); + for (const [t3, i2] of Object.entries(e2)) this._applyRegistrationHook(this._onInputEntity, t3, i2, "input") && (n2[t3] = i2); + this._inputMap = n2; } reset() { return this._inputMap = /* @__PURE__ */ Object.create(null), this._totalExpansions = 0, this._expandedLength = 0, this; @@ -55278,76 +55507,77 @@ var require_fxp = __commonJS({ } decode(t2) { if ("string" != typeof t2 || 0 === t2.length) return t2; + if (-1 === t2.indexOf("&")) return t2; const e2 = t2, n2 = [], i2 = t2.length; - let s2 = 0, r2 = 0; - const o2 = this._maxTotalExpansions > 0, a2 = this._maxExpandedLength > 0, h2 = o2 || a2; - for (; r2 < i2; ) { - if (38 !== t2.charCodeAt(r2)) { - r2++; + let r2 = 0, s2 = 0; + const o2 = this._maxTotalExpansions > 0, a2 = this._maxExpandedLength > 0, l2 = o2 || a2; + for (; s2 < i2; ) { + if (38 !== t2.charCodeAt(s2)) { + s2++; continue; } - let e3 = r2 + 1; - for (; e3 < i2 && 59 !== t2.charCodeAt(e3) && e3 - r2 <= 32; ) e3++; + let e3 = s2 + 1; + for (; e3 < i2 && 59 !== t2.charCodeAt(e3) && e3 - s2 <= 32; ) e3++; if (e3 >= i2 || 59 !== t2.charCodeAt(e3)) { - r2++; + s2++; continue; } - const l3 = t2.slice(r2 + 1, e3); - if (0 === l3.length) { - r2++; + const c3 = t2.slice(s2 + 1, e3); + if (0 === c3.length) { + s2++; continue; } - let u2, p2; - if (this._removeSet.has(l3)) u2 = "", void 0 === p2 && (p2 = Z); + let p2, h2; + if (this._removeSet.has(c3)) p2 = "", void 0 === h2 && (h2 = gt); else { - if (this._leaveSet.has(l3)) { - r2++; + if (this._leaveSet.has(c3)) { + s2++; continue; } - if (35 === l3.charCodeAt(0)) { - const t3 = this._resolveNCR(l3); + if (35 === c3.charCodeAt(0)) { + const t3 = this._resolveNCR(c3); if (void 0 === t3) { - r2++; + s2++; continue; } - u2 = t3, p2 = J; + p2 = t3, h2 = mt; } else { - const t3 = this._resolveName(l3); - u2 = t3?.value, p2 = t3?.tier; + const t3 = this._resolveName(c3); + p2 = t3?.value, h2 = t3?.tier; } } - if (void 0 !== u2) { - if (r2 > s2 && n2.push(t2.slice(s2, r2)), n2.push(u2), s2 = e3 + 1, r2 = s2, h2 && this._tierCounts(p2)) { + if (void 0 !== p2) { + if (s2 > r2 && n2.push(t2.slice(r2, s2)), n2.push(p2), r2 = e3 + 1, s2 = r2, l2 && this._tierCounts(h2)) { if (o2 && (this._totalExpansions++, this._totalExpansions > this._maxTotalExpansions)) throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`); if (a2) { - const t3 = u2.length - (l3.length + 2); + const t3 = p2.length - (c3.length + 2); if (t3 > 0 && (this._expandedLength += t3, this._expandedLength > this._maxExpandedLength)) throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`); } } - } else r2++; + } else s2++; } - s2 < i2 && n2.push(t2.slice(s2)); - const l2 = 0 === n2.length ? t2 : n2.join(""); - return this._postCheck(l2, e2); + r2 < i2 && n2.push(t2.slice(r2)); + const c2 = 0 === n2.length ? t2 : n2.join(""); + return this._postCheck(c2, e2); } _tierCounts(t2) { - return !!this._limitTiers.has(K) || this._limitTiers.has(t2); + return !!this._limitTiers.has(xt) || this._limitTiers.has(t2); } _resolveName(t2) { - return t2 in this._inputMap ? { value: this._inputMap[t2], tier: Z } : t2 in this._externalMap ? { value: this._externalMap[t2], tier: Z } : t2 in this._baseMap ? { value: this._baseMap[t2], tier: J } : void 0; + return t2 in this._inputMap ? { value: this._inputMap[t2], tier: gt } : t2 in this._externalMap ? { value: this._externalMap[t2], tier: gt } : t2 in this._baseMap ? { value: this._baseMap[t2], tier: mt } : void 0; } _classifyNCR(t2) { - return 0 === t2 ? this._ncrNullLevel : t2 >= 55296 && t2 <= 57343 || 1 === this._ncrXmlVersion && t2 >= 1 && t2 <= 31 && !H.has(t2) ? Q.remove : -1; + return 0 === t2 ? this._ncrNullLevel : t2 >= 55296 && t2 <= 57343 || 1 === this._ncrXmlVersion && t2 >= 1 && t2 <= 31 && !yt.has(t2) ? bt.remove : -1; } _applyNCRAction(t2, e2, n2) { switch (t2) { - case Q.allow: + case bt.allow: return String.fromCodePoint(n2); - case Q.remove: + case bt.remove: return ""; - case Q.leave: + case bt.leave: return; - case Q.throw: + case bt.throw: throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e2}; (U+${n2.toString(16).toUpperCase().padStart(4, "0")})`); default: return String.fromCodePoint(n2); @@ -55358,12 +55588,46 @@ var require_fxp = __commonJS({ let n2; if (n2 = 120 === e2 || 88 === e2 ? parseInt(t2.slice(2), 16) : parseInt(t2.slice(1), 10), Number.isNaN(n2) || n2 < 0 || n2 > 1114111) return; const i2 = this._classifyNCR(n2); - if (!this._numericAllowed && i2 < Q.remove) return; - const s2 = -1 === i2 ? this._ncrOnLevel : Math.max(this._ncrOnLevel, i2); - return this._applyNCRAction(s2, t2, n2); + if (!this._numericAllowed && i2 < bt.remove) return; + const r2 = -1 === i2 ? this._ncrOnLevel : Math.max(this._ncrOnLevel, i2); + return this._applyNCRAction(r2, t2, n2); } } - function et(t2, e2) { + const Et = [{ id: "sql-block-comment-open", description: "SQL block comment open: /* ... */ \u2014 unusual in legitimate user text", pattern: /\/\*/ }, { id: "sql-union-select", description: "UNION SELECT \u2014 most common SQL injection aggregation attack", pattern: /\bUNION\s{1,20}(?:ALL\s{1,20})?SELECT\b/i }, { id: "sql-drop-table", description: "DROP TABLE \u2014 destructive DDL injection", pattern: /\bDROP\s{1,20}TABLE\b/i }, { id: "sql-drop-database", description: "DROP DATABASE \u2014 destructive DDL injection", pattern: /\bDROP\s{1,20}DATABASE\b/i }, { id: "sql-insert-into", description: "INSERT INTO \u2014 data injection", pattern: /\bINSERT\s{1,20}INTO\b/i }, { id: "sql-delete-from", description: "DELETE FROM \u2014 data deletion injection", pattern: /\bDELETE\s{1,20}FROM\b/i }, { id: "sql-update-set", description: "UPDATE ... SET \u2014 data modification injection", pattern: /\bUPDATE\b[\s\S]{1,60}\bSET\b/i }, { id: "sql-exec-xp", description: "EXEC xp_ \u2014 MSSQL extended stored procedure execution", pattern: /\bEXEC(?:UTE)?\s{1,20}xp_/i }, { id: "sql-tautology-string", description: `Classic string tautology: ' OR '1'='1 or " OR "1"="1"`, pattern: /'\s{0,10}OR\s{0,10}'[^']{0,20}'\s*=\s*'[^']{0,20}/i }, { id: "sql-tautology-numeric", description: "Numeric tautology: OR 1=1", pattern: /\bOR\s{1,10}1\s*=\s*1\b/i }, { id: "sql-always-true-zero", description: "Numeric tautology: OR 0=0", pattern: /\bOR\s{1,10}0\s*=\s*0\b/i }, { id: "sql-sleep-benchmark", description: "Time-based blind injection: SLEEP() or BENCHMARK()", pattern: /\b(?:SLEEP|BENCHMARK)\s*\(/i }, { id: "sql-waitfor-delay", description: "MSSQL time-based blind injection: WAITFOR DELAY", pattern: /\bWAITFOR\s{1,20}DELAY\b/i }, { id: "sql-char-function", description: "CHAR() function \u2014 used to obfuscate injected strings", pattern: /\bCHAR\s*\(\s*\d{1,3}/i }, { id: "sql-information-schema", description: "INFORMATION_SCHEMA \u2014 reconnaissance query for table/column enumeration", pattern: /\bINFORMATION_SCHEMA\b/i }], wt = [...Et, { id: "sql-line-comment", description: "SQL line comment: -- followed by whitespace or end of string", pattern: /--(?:\s|$)/ }, { id: "sql-stacked-query", description: "Stacked queries: semicolon immediately followed by a SQL keyword", pattern: /;\s{0,10}(?:SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC)\b/i }, { id: "sql-hex-encoding", description: "Hex-encoded string injection: 0x41414141 style (MySQL)", pattern: /\b0x[0-9a-f]{4,}/i }], vt = Object.freeze({ colon: ":", Tab: " ", NewLine: "\n" }), St = /&(?:#[xX]0*([0-9a-fA-F]{1,6});?|#0*([0-9]{1,7});?|([a-zA-Z][a-zA-Z0-9]{1,15});)/g, At = [{ id: "html-script-open", description: "]/i }, { id: "html-javascript-protocol", description: "javascript: URI scheme (with optional whitespace/encoding)", pattern: /j[\t\n\r ]*a[\t\n\r ]*v[\t\n\r ]*a[\t\n\r ]*s[\t\n\r ]*c[\t\n\r ]*r[\t\n\r ]*i[\t\n\r ]*p[\t\n\r ]*t[\t\n\r ]*:/i }, { id: "html-vbscript-protocol", description: "vbscript: URI scheme", pattern: /vbscript[\t\n\r ]*:/i }, { id: "html-data-html", description: "data:text/html URI \u2014 can execute scripts in browsers", pattern: /data[\t\n\r ]*:[\t\n\r ]*text\/html/i }, { id: "html-data-xhtml", description: "data:application/xhtml+xml URI", pattern: /data[\t\n\r ]*:[\t\n\r ]*application\/xhtml/i }, { id: "html-data-svg", description: "data:image/svg+xml URI \u2014 can execute scripts", pattern: /data[\t\n\r ]*:[\t\n\r ]*image\/svg\+xml/i }, { id: "html-inline-event-handler", description: "Inline event handler attributes: onclick=, onerror=, onload=, etc.", pattern: /\bon\w{1,30}\s*=/i }, { id: "html-entity-obfuscated-script", description: "HTML-entity-encoded