@benchcutlogic/reg-notify-plugin 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,187 @@
1
- # Temporary Holding Version
1
+ # @benchcutlogic/reg-notify-plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [reg-suit](https://github.com/reg-viz/reg-suit) notifier plugin for GitHub pull requests, plus a
4
+ small CLI for the approval and baseline-wait steps around it.
5
+
6
+ After each `reg-suit run`, the plugin:
7
+
8
+ - sets a commit status on the head SHA (failure when screenshots changed or were deleted, or when
9
+ every screenshot is new because no baseline was found);
10
+ - posts or updates one sticky PR comment with counts, thumbnails, an **Approve screenshots**
11
+ checkbox bound to the head SHA, and a machine-readable JSON block;
12
+ - adds `visual` and `visual: stories` (or `visual: pages`) labels while a review is pending;
13
+ - optionally posts a Slack message for changed screenshots.
14
+
15
+ The `bench-reg` CLI checks a ticked checkbox, flips the status to success, and handles PRs whose base
16
+ baseline has not been published yet.
17
+
18
+ ## Requirements
19
+
20
+ - Node.js 20 or later.
21
+ - `reg-suit` 0.14 and a publisher plugin such as `reg-publish-s3-plugin`.
22
+ - A GitHub token with `statuses: write`, `pull-requests: write`, and `issues: write`.
23
+ - The AWS CLI on `PATH`, only for `bench-reg resume-waiters`.
24
+
25
+ ## Install
26
+
27
+ ```sh
28
+ npm install --save-dev @benchcutlogic/reg-notify-plugin reg-suit
29
+ ```
30
+
31
+ ## reg-suit plugin
32
+
33
+ Add the package to `regconfig.json`. Every option is optional.
34
+
35
+ ```json
36
+ {
37
+ "core": { "workingDir": ".reg", "actualDir": "screenshots" },
38
+ "plugins": {
39
+ "@benchcutlogic/reg-notify-plugin": {
40
+ "statusContext": "visual-regression",
41
+ "customDomain": "reports.example.com",
42
+ "pathPrefix": "storybook",
43
+ "sampleCap": 5,
44
+ "slackUserMapPath": ".github/slack-user-map.json"
45
+ }
46
+ }
47
+ }
48
+ ```
49
+
50
+ | Option | Default | Meaning |
51
+ | ------------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
52
+ | `statusContext` | `reg-suit` | Commit status context. It also keys the sticky comment, so use a different value per reg-suit config in one repository. |
53
+ | `customDomain` | `REG_S3_CUSTOM_DOMAIN` | Host that serves published reports. With it, the comment links `https://<domain>/<pathPrefix>/<sha>/` and embeds thumbnails. |
54
+ | `pathPrefix` | `storybook` | Report prefix under `customDomain`. The value `pages` switches the heading and the scoped label to pages. |
55
+ | `sampleCap` | `5` | Thumbnails per section of the comment. |
56
+ | `slackUserMap` | none | GitHub login to Slack user ID map, used to mention the PR author. |
57
+ | `slackUserMapPath` | none | JSON file with the same map, resolved from the working directory. A missing or invalid file logs a warning and disables the mention. |
58
+
59
+ Environment variables read by the plugin:
60
+
61
+ | Variable | Purpose |
62
+ | -------------------------- | ------------------------------------------------------------------------------------------ |
63
+ | `GITHUB_TOKEN` | Required. Without it, or without `GITHUB_REPOSITORY` and a SHA, the plugin logs and skips. |
64
+ | `GITHUB_REPOSITORY` | `owner/repo`. |
65
+ | `GITHUB_HEAD_SHA` | Head SHA to report on. Falls back to `GITHUB_SHA`; set it on `pull_request` runs. |
66
+ | `GITHUB_REF` | A `refs/pull/<n>/...` ref selects the PR directly; otherwise the PR is looked up by SHA. |
67
+ | `GITHUB_EVENT_NAME` | `push` and `workflow_dispatch` runs only publish; they set no status and post no comment. |
68
+ | `GITHUB_API_URL` | API base for GitHub Enterprise Server. Defaults to `https://api.github.com`. |
69
+ | `GITHUB_SERVER_URL` | Web base used in links. Defaults to `https://github.com`. |
70
+ | `GITHUB_PR_AUTHOR` | PR author login, used for the Slack mention. |
71
+ | `GITHUB_PR_TITLE` | PR title, quoted in the Slack message. |
72
+ | `SLACK_DESIGN_WEBHOOK_URL` | Slack incoming webhook. When unset, no Slack message is sent. |
73
+
74
+ The Slack message is sent once per open review. A failed webhook only logs a warning; it never
75
+ changes the commit status.
76
+
77
+ ## CLI: `bench-reg`
78
+
79
+ Run `npx bench-reg --help` for every command and variable.
80
+
81
+ ### `verify-approval`
82
+
83
+ Run it from an `issue_comment` `edited` workflow. It checks four things: the comment carries the
84
+ status marker, the ticked checkbox names the SHA recorded in the comment, that SHA is still the PR
85
+ head, and the actor has write, maintain, or admin permission. It then sets the status to success
86
+ and removes the labels.
87
+
88
+ ```sh
89
+ GITHUB_TOKEN=... GITHUB_REPOSITORY=owner/repo PR=42 ACTOR=octocat \
90
+ COMMENT_BODY="$(cat comment.md)" \
91
+ npx bench-reg verify-approval --context visual-regression
92
+ ```
93
+
94
+ Pass `--action rerun --job <job name> --workflow <file>` to handle the **Re-run comparison**
95
+ checkbox, which re-runs that job of the latest workflow run for the head SHA.
96
+
97
+ ### `mark-waiter` and `resume-waiters`
98
+
99
+ When a PR's base commit has no published baseline yet, `mark-waiter` sets a pending status and a
100
+ comment instead of reporting every screenshot as new. When the base run finishes, `resume-waiters`
101
+ checks the bucket with `aws s3api list-objects-v2` and re-runs the waiting comparison.
102
+
103
+ ```sh
104
+ GITHUB_TOKEN=... GITHUB_REPOSITORY=owner/repo COMPLETED_SHA=<40-char sha> \
105
+ COMPLETED_BRANCH=main COMPLETED_RUN_ID=123 REG_S3_BUCKET_NAME=my-bucket \
106
+ npx bench-reg resume-waiters
107
+ ```
108
+
109
+ `REG_S3_ENDPOINT` is needed only for S3-compatible providers other than AWS. The region comes from
110
+ `AWS_REGION`, then `REG_S3_REGION`, then the AWS CLI configuration.
111
+
112
+ ### `catalog`
113
+
114
+ Writes a JSON list of Storybook story files. Files tagged `'!visual'` are listed under `excluded`.
115
+
116
+ ```sh
117
+ npx bench-reg catalog --root src --out visual-catalog.json
118
+ npx bench-reg catalog --root src --out visual-catalog.json --check # exit 1 when stale
119
+ ```
120
+
121
+ ## Library exports
122
+
123
+ The root export is the CommonJS plugin factory that reg-suit loads. The other subpaths are ES
124
+ modules; import them with `import`, not `require`.
125
+
126
+ ### `@benchcutlogic/reg-notify-plugin`
127
+
128
+ ```js
129
+ const plugin = require('@benchcutlogic/reg-notify-plugin');
130
+
131
+ plugin.markerFor(plugin.DEFAULT_CONTEXT); // '<!-- reg-suit:do-not-edit -->'
132
+ plugin.visualApprovalLabelFor('pages'); // 'visual: pages'
133
+ ```
134
+
135
+ ### `@benchcutlogic/reg-notify-plugin/approval`
136
+
137
+ ```js
138
+ import {
139
+ createGitHubApi,
140
+ parseApprovalComment,
141
+ verifyApproval
142
+ } from '@benchcutlogic/reg-notify-plugin/approval';
143
+
144
+ const parsed = parseApprovalComment(commentBody, { context: 'visual-regression' });
145
+ if (parsed.ok) {
146
+ const api = createGitHubApi(process.env.GITHUB_TOKEN, 'owner', 'repo');
147
+ const result = await verifyApproval({
148
+ api,
149
+ owner: 'owner',
150
+ repo: 'repo',
151
+ prNumber: 42,
152
+ actor: 'octocat',
153
+ commentBody,
154
+ context: 'visual-regression'
155
+ });
156
+ console.log(result.status); // 'approved', 'ignored', 'denied', 'rerun', or 'error'
157
+ }
158
+ ```
159
+
160
+ ### `@benchcutlogic/reg-notify-plugin/wait`
161
+
162
+ ```js
163
+ import { createGitHubApi } from '@benchcutlogic/reg-notify-plugin/approval';
164
+ import { createS3Publisher, resumeWaiters } from '@benchcutlogic/reg-notify-plugin/wait';
165
+
166
+ const results = await resumeWaiters({
167
+ api: createGitHubApi(process.env.GITHUB_TOKEN, 'owner', 'repo'),
168
+ owner: 'owner',
169
+ completedSha: process.env.COMPLETED_SHA,
170
+ completedBranch: 'main',
171
+ completedRunId: Number(process.env.COMPLETED_RUN_ID),
172
+ isPublished: createS3Publisher({ bucket: 'my-bucket' })
173
+ });
174
+ ```
175
+
176
+ ### `@benchcutlogic/reg-notify-plugin/catalog`
177
+
178
+ ```js
179
+ import { generateVisualCatalog } from '@benchcutlogic/reg-notify-plugin/catalog';
180
+
181
+ const catalog = generateVisualCatalog('src', { ignoreDirs: ['fixtures'] });
182
+ console.log(catalog.visualEntries.map((entry) => entry.title));
183
+ ```
184
+
185
+ ## License
186
+
187
+ Apache-2.0. See [LICENSE](LICENSE).
package/approval.d.mts ADDED
@@ -0,0 +1,59 @@
1
+ export type ApprovalAction = 'approve' | 'rerun';
2
+
3
+ export type ParsedApprovalComment =
4
+ | { ok: false; reason: 'missing-marker' | 'missing-sha' }
5
+ | { ok: false; reason: 'not-checked'; commentSha: string; shortSha: string }
6
+ | {
7
+ ok: true;
8
+ commentSha: string;
9
+ shortSha: string;
10
+ action: ApprovalAction;
11
+ context: string;
12
+ };
13
+
14
+ export type VerifyApprovalResult =
15
+ | { status: 'ignored'; reason: string; commentSha?: string; headSha?: string }
16
+ | { status: 'denied'; reason: 'insufficient-permission'; permission: string; actor: string }
17
+ | { status: 'error'; reason: string; headSha?: string; runId?: number; jobName?: string }
18
+ | { status: 'rerun'; headSha: string; runId: number; jobId: number }
19
+ | { status: 'approved'; headSha: string; context: string; actor: string };
20
+
21
+ /** Default commit status context: `reg-suit`. */
22
+ export declare const DEFAULT_CONTEXT: string;
23
+ /** Default scoped approval label: `visual: stories`. */
24
+ export declare const DEFAULT_APPROVAL_LABEL: string;
25
+
26
+ export declare function normalizeLineEndings(text: unknown): string;
27
+ export declare function markerFor(context: string): string;
28
+ export declare function parseApprovalComment(
29
+ body: string,
30
+ options?: { context?: string; action?: ApprovalAction }
31
+ ): ParsedApprovalComment;
32
+ export declare function createGitHubApi(
33
+ token: string,
34
+ owner: string,
35
+ repo: string,
36
+ fetchImpl?: typeof fetch,
37
+ /** Defaults to `GITHUB_API_URL`, then `https://api.github.com`. */
38
+ apiUrl?: string
39
+ ): <T = unknown>(
40
+ method: string,
41
+ apiPath: string,
42
+ schema: { parse(input: unknown): T } | null,
43
+ body?: unknown
44
+ ) => Promise<T>;
45
+ export declare function verifyApproval(params: {
46
+ api: ReturnType<typeof createGitHubApi>;
47
+ owner: string;
48
+ repo: string;
49
+ prNumber: number;
50
+ actor: string;
51
+ commentBody: string;
52
+ context?: string;
53
+ approvalLabel?: string;
54
+ action?: ApprovalAction;
55
+ workflowFile?: string;
56
+ jobName?: string;
57
+ /** Used for the status target URL. Defaults to `GITHUB_SERVER_URL`, then `https://github.com`. */
58
+ serverUrl?: string;
59
+ }): Promise<VerifyApprovalResult>;
package/approval.mjs ADDED
@@ -0,0 +1,204 @@
1
+ import { z } from 'zod';
2
+
3
+ const SHA_PATTERN = /<!--\s*sha:\s*([a-f0-9]{40})\s*-->/i;
4
+ export const DEFAULT_CONTEXT = 'reg-suit';
5
+ export const DEFAULT_APPROVAL_LABEL = 'visual: stories';
6
+ const ALLOWED_PERMISSIONS = new Set(['admin', 'maintain', 'write']);
7
+
8
+ const PullSchema = z
9
+ .object({
10
+ head: z.object({ sha: z.string().regex(/^[a-f0-9]{40}$/) })
11
+ })
12
+ .passthrough();
13
+
14
+ const PermissionSchema = z
15
+ .object({
16
+ permission: z.string().min(1)
17
+ })
18
+ .passthrough();
19
+
20
+ const LabelsSchema = z.array(z.object({ name: z.string() }).passthrough());
21
+
22
+ const WorkflowRunsSchema = z.object({
23
+ workflow_runs: z.array(z.object({ id: z.number().int().positive() }).passthrough())
24
+ });
25
+
26
+ const JobsSchema = z.object({
27
+ jobs: z.array(z.object({ id: z.number().int().positive(), name: z.string() }).passthrough())
28
+ });
29
+
30
+ /**
31
+ * Normalize CRLF / CR line endings to LF so GitHub web checkbox edits
32
+ * (which submit `\r\n` bodies) match whole-line checkbox predicates reliably.
33
+ */
34
+ export function normalizeLineEndings(text) {
35
+ return String(text ?? '').replace(/\r\n?/g, '\n');
36
+ }
37
+
38
+ export function markerFor(context) {
39
+ return `<!-- ${context}:do-not-edit -->`;
40
+ }
41
+
42
+ /**
43
+ * Parse and validate an approval or rerun comment body.
44
+ * Always normalizes CRLF -> LF before inspecting lines.
45
+ */
46
+ export function parseApprovalComment(body, options = {}) {
47
+ const context = options.context || DEFAULT_CONTEXT;
48
+ const action = options.action || 'approve';
49
+ const normalized = normalizeLineEndings(body);
50
+
51
+ const marker = markerFor(context);
52
+ if (!normalized.includes(marker)) {
53
+ return { ok: false, reason: 'missing-marker' };
54
+ }
55
+
56
+ const shaMatch = normalized.match(SHA_PATTERN);
57
+ if (!shaMatch) {
58
+ return { ok: false, reason: 'missing-sha' };
59
+ }
60
+
61
+ const commentSha = shaMatch[1].toLowerCase();
62
+ const shortSha = commentSha.slice(0, 7);
63
+ const expectedLine =
64
+ action === 'rerun'
65
+ ? `- [x] **Re-run comparison** for \`${shortSha}\``
66
+ : `- [x] **Approve screenshots** for \`${shortSha}\``;
67
+
68
+ const lines = normalized.split('\n').map((line) => line.trimEnd());
69
+ const checked = lines.some((line) => line === expectedLine);
70
+ if (!checked) {
71
+ return { ok: false, reason: 'not-checked', commentSha, shortSha };
72
+ }
73
+
74
+ return { ok: true, commentSha, shortSha, action, context };
75
+ }
76
+
77
+ export function createGitHubApi(
78
+ token,
79
+ owner,
80
+ repo,
81
+ fetchImpl = fetch,
82
+ apiUrl = process.env.GITHUB_API_URL || 'https://api.github.com'
83
+ ) {
84
+ const base = apiUrl.replace(/\/+$/, '');
85
+ return async function api(method, apiPath, schema, body) {
86
+ const response = await fetchImpl(`${base}/repos/${owner}/${repo}${apiPath}`, {
87
+ method,
88
+ signal: AbortSignal.timeout(30_000),
89
+ headers: {
90
+ Authorization: `Bearer ${token}`,
91
+ Accept: 'application/vnd.github+json',
92
+ 'X-GitHub-Api-Version': '2022-11-28',
93
+ 'User-Agent': 'benchcutlogic-reg-notify-plugin',
94
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' })
95
+ },
96
+ ...(body === undefined ? {} : { body: JSON.stringify(body) })
97
+ });
98
+ if (!response.ok) {
99
+ const detail = await response.text().catch(() => '');
100
+ throw new Error(`GitHub API ${method} ${apiPath} -> ${response.status} ${detail}`.trim());
101
+ }
102
+ if (!schema || response.status === 204) return null;
103
+ return schema.parse(await response.json());
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Verify all 4 gates on a visual approval / rerun checkbox toggle and apply
109
+ * the corresponding GitHub API update.
110
+ */
111
+ export async function verifyApproval({
112
+ api,
113
+ owner,
114
+ repo,
115
+ prNumber,
116
+ actor,
117
+ commentBody,
118
+ context = DEFAULT_CONTEXT,
119
+ approvalLabel = DEFAULT_APPROVAL_LABEL,
120
+ action = 'approve',
121
+ workflowFile = 'ci.yml',
122
+ jobName = 'storybook',
123
+ serverUrl = process.env.GITHUB_SERVER_URL || 'https://github.com'
124
+ }) {
125
+ const parsed = parseApprovalComment(commentBody, { context, action });
126
+ if (!parsed.ok) {
127
+ return { status: 'ignored', reason: parsed.reason };
128
+ }
129
+
130
+ const pull = await api('GET', `/pulls/${prNumber}`, PullSchema);
131
+ if (parsed.commentSha !== pull.head.sha.toLowerCase()) {
132
+ return {
133
+ status: 'ignored',
134
+ reason: 'stale-sha',
135
+ commentSha: parsed.commentSha,
136
+ headSha: pull.head.sha
137
+ };
138
+ }
139
+
140
+ const perm = await api(
141
+ 'GET',
142
+ `/collaborators/${encodeURIComponent(actor)}/permission`,
143
+ PermissionSchema
144
+ );
145
+ if (!ALLOWED_PERMISSIONS.has(perm.permission)) {
146
+ return {
147
+ status: 'denied',
148
+ reason: 'insufficient-permission',
149
+ permission: perm.permission,
150
+ actor
151
+ };
152
+ }
153
+
154
+ if (action === 'rerun') {
155
+ const runs = await api(
156
+ 'GET',
157
+ `/actions/workflows/${encodeURIComponent(workflowFile)}/runs?head_sha=${pull.head.sha}&event=pull_request&per_page=1`,
158
+ WorkflowRunsSchema
159
+ );
160
+ const run = runs.workflow_runs[0];
161
+ if (!run) {
162
+ return { status: 'error', reason: 'no-workflow-run', headSha: pull.head.sha };
163
+ }
164
+ const jobs = await api('GET', `/actions/runs/${run.id}/jobs?per_page=100`, JobsSchema);
165
+ const job = [...jobs.jobs].reverse().find((candidate) => candidate.name === jobName);
166
+ if (!job) {
167
+ return { status: 'error', reason: 'no-matching-job', runId: run.id, jobName };
168
+ }
169
+ await api('POST', `/actions/jobs/${job.id}/rerun`, null, {});
170
+ return { status: 'rerun', headSha: pull.head.sha, runId: run.id, jobId: job.id };
171
+ }
172
+
173
+ await api('POST', `/statuses/${pull.head.sha}`, null, {
174
+ state: 'success',
175
+ context,
176
+ description: `approved by @${actor} via checkbox`,
177
+ target_url: `${serverUrl.replace(/\/+$/, '')}/${owner}/${repo}/pull/${prNumber}`
178
+ });
179
+
180
+ try {
181
+ await api('DELETE', `/issues/${prNumber}/labels/${encodeURIComponent(approvalLabel)}`, null);
182
+ } catch (error) {
183
+ if (!String(error?.message || '').includes('404')) throw error;
184
+ }
185
+
186
+ const labels = await api('GET', `/issues/${prNumber}/labels`, LabelsSchema);
187
+ const remainingVisual = labels.some(
188
+ (label) => label.name !== approvalLabel && label.name.startsWith('visual: ')
189
+ );
190
+ if (!remainingVisual) {
191
+ try {
192
+ await api('DELETE', `/issues/${prNumber}/labels/visual`, null);
193
+ } catch (error) {
194
+ if (!String(error?.message || '').includes('404')) throw error;
195
+ }
196
+ }
197
+
198
+ return {
199
+ status: 'approved',
200
+ headSha: pull.head.sha,
201
+ context,
202
+ actor
203
+ };
204
+ }