@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/package.json CHANGED
@@ -1,6 +1,88 @@
1
1
  {
2
2
  "name": "@benchcutlogic/reg-notify-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.1",
4
+ "description": "reg-suit notifier plugin that posts a SHA-bound approval comment and commit status on GitHub pull requests, plus a CLI for approvals, baseline waits, and a Storybook visual catalog.",
5
+ "license": "Apache-2.0",
6
+ "type": "commonjs",
7
+ "main": "./index.js",
8
+ "types": "./index.d.ts",
9
+ "bin": {
10
+ "bench-reg": "./bin/bench-reg.mjs"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./index.d.ts",
15
+ "default": "./index.js"
16
+ },
17
+ "./approval": {
18
+ "types": "./approval.d.mts",
19
+ "import": "./approval.mjs"
20
+ },
21
+ "./wait": {
22
+ "types": "./wait.d.mts",
23
+ "import": "./wait.mjs"
24
+ },
25
+ "./catalog": {
26
+ "types": "./catalog.d.mts",
27
+ "import": "./catalog.mjs"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "index.js",
33
+ "index.d.ts",
34
+ "design-notification-markers.js",
35
+ "approval.mjs",
36
+ "approval.d.mts",
37
+ "wait.mjs",
38
+ "wait.d.mts",
39
+ "catalog.mjs",
40
+ "catalog.d.mts",
41
+ "bin/bench-reg.mjs",
42
+ "README.md",
43
+ "LICENSE"
44
+ ],
45
+ "engines": {
46
+ "node": ">=20"
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/benchcutlogic/bench.git",
51
+ "directory": "packages/reg-notify-plugin"
52
+ },
53
+ "homepage": "https://github.com/benchcutlogic/bench/tree/main/packages/reg-notify-plugin",
54
+ "bugs": {
55
+ "url": "https://github.com/benchcutlogic/bench/issues"
56
+ },
57
+ "keywords": [
58
+ "reg-suit",
59
+ "reg-suit-plugin",
60
+ "visual-regression",
61
+ "storybook",
62
+ "github-actions"
63
+ ],
64
+ "publishConfig": {
65
+ "registry": "https://registry.npmjs.org",
66
+ "access": "public",
67
+ "provenance": false
68
+ },
69
+ "dependencies": {
70
+ "zod": "^4.5.4"
71
+ },
72
+ "devDependencies": {
73
+ "@types/node": "^22.20.7",
74
+ "reg-suit": "^0.14.5",
75
+ "typescript": "^5.9.3",
76
+ "vitest": "^4.1.11"
77
+ },
78
+ "regSuitPlugin": {
79
+ "recommended": false
80
+ },
81
+ "scripts": {
82
+ "check": "prettier --check .",
83
+ "typecheck": "tsc --noEmit",
84
+ "package": "node -e \"console.log('@benchcutlogic/reg-notify-plugin ready')\"",
85
+ "build": "pnpm run package",
86
+ "test": "vitest run"
87
+ }
6
88
  }
package/wait.d.mts ADDED
@@ -0,0 +1,44 @@
1
+ import type { createGitHubApi } from './approval.mjs';
2
+
3
+ export interface WaitRecord {
4
+ context: string;
5
+ prefix: string;
6
+ expected_sha: string;
7
+ head_sha: string;
8
+ base_ref: string;
9
+ run_id: number;
10
+ job_name: string;
11
+ }
12
+
13
+ export declare function parseWaitRecord(body: string | null | undefined): WaitRecord | null;
14
+ export declare function waitingDescription(record: WaitRecord): string;
15
+ export declare function unavailableDescription(record: WaitRecord): string;
16
+ export declare function buildWaitComment(
17
+ record: WaitRecord,
18
+ state: 'waiting' | 'queued' | 'unavailable'
19
+ ): string;
20
+ export declare function markWaiting(params: {
21
+ api: ReturnType<typeof createGitHubApi>;
22
+ record: WaitRecord;
23
+ prNumber: number;
24
+ runUrl: string;
25
+ workflowFile?: string;
26
+ }): Promise<'waiting' | 'unavailable'>;
27
+ export declare function resumeWaiters(params: {
28
+ api: ReturnType<typeof createGitHubApi>;
29
+ owner: string;
30
+ completedSha: string;
31
+ completedBranch: string;
32
+ completedRunId: number;
33
+ isPublished: (prefix: string, sha: string) => Promise<boolean>;
34
+ workflowFile?: string;
35
+ }): Promise<Array<{ pr: number; context?: string; result: string; message?: string }>>;
36
+ export declare const WaitRecordSchema: { parse(input: unknown): WaitRecord };
37
+ export declare function createS3Publisher(config: {
38
+ bucket: string;
39
+ /** Endpoint URL for S3-compatible providers other than AWS. */
40
+ endpoint?: string;
41
+ /** Region passed to the AWS CLI; omitted means the CLI's own configuration. */
42
+ region?: string;
43
+ }): (prefix: string, sha: string) => Promise<boolean>;
44
+ export { createGitHubApi } from './approval.mjs';
package/wait.mjs ADDED
@@ -0,0 +1,382 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { z } from 'zod';
4
+ import { createGitHubApi, markerFor, normalizeLineEndings } from './approval.mjs';
5
+
6
+ const SHA = z.string().regex(/^[a-f0-9]{40}$/);
7
+
8
+ export const WaitRecordSchema = z
9
+ .object({
10
+ context: z.string().min(1),
11
+ prefix: z.string().min(1),
12
+ expected_sha: SHA,
13
+ head_sha: SHA,
14
+ base_ref: z.string().min(1),
15
+ run_id: z.number().int().positive(),
16
+ job_name: z.string().min(1)
17
+ })
18
+ .strict();
19
+
20
+ const WorkflowRuns = z.object({
21
+ workflow_runs: z.array(
22
+ z
23
+ .object({
24
+ id: z.number().int().positive(),
25
+ head_sha: SHA,
26
+ status: z.string().min(1)
27
+ })
28
+ .passthrough()
29
+ )
30
+ });
31
+
32
+ const Pulls = z.array(
33
+ z
34
+ .object({
35
+ number: z.number().int().positive(),
36
+ head: z.object({ sha: SHA }),
37
+ base: z.object({ ref: z.string().min(1), sha: SHA })
38
+ })
39
+ .passthrough()
40
+ );
41
+
42
+ const Comments = z.array(
43
+ z
44
+ .object({
45
+ id: z.number().int().positive(),
46
+ body: z.string().nullable(),
47
+ author_association: z.string().min(1),
48
+ user: z
49
+ .object({ login: z.string().min(1) })
50
+ .nullable()
51
+ .optional()
52
+ })
53
+ .passthrough()
54
+ );
55
+
56
+ const CombinedStatus = z.object({
57
+ statuses: z.array(
58
+ z
59
+ .object({
60
+ context: z.string(),
61
+ state: z.enum(['error', 'failure', 'pending', 'success']),
62
+ description: z.string().nullable().optional()
63
+ })
64
+ .passthrough()
65
+ )
66
+ });
67
+
68
+ const Jobs = z.object({
69
+ jobs: z.array(
70
+ z
71
+ .object({ id: z.number().int().positive(), name: z.string(), status: z.string() })
72
+ .passthrough()
73
+ )
74
+ });
75
+
76
+ const WorkflowRun = z
77
+ .object({ id: z.number().int().positive(), status: z.string().min(1) })
78
+ .passthrough();
79
+
80
+ const KeyCount = z.coerce.number().int().nonnegative();
81
+ const WAIT_MARKER = /<!-- visual-baseline-wait:\s*(\{[^\n]+\})\s*-->/;
82
+
83
+ function isManagedComment(comment) {
84
+ return comment.user?.login === 'github-actions[bot]' && comment.author_association === 'NONE';
85
+ }
86
+
87
+ export function parseWaitRecord(body) {
88
+ const normalized = normalizeLineEndings(body);
89
+ const encoded = normalized.match(WAIT_MARKER)?.[1];
90
+ if (!encoded) return null;
91
+ try {
92
+ return WaitRecordSchema.parse(JSON.parse(encoded));
93
+ } catch {
94
+ return null;
95
+ }
96
+ }
97
+
98
+ export function waitingDescription(record) {
99
+ return `waiting for ${record.prefix} baseline ${record.expected_sha.slice(0, 7)}`;
100
+ }
101
+
102
+ export function unavailableDescription(record) {
103
+ return `base ${record.prefix} baseline ${record.expected_sha.slice(0, 7)} was not published`;
104
+ }
105
+
106
+ export function buildWaitComment(record, state) {
107
+ const expected = record.expected_sha.slice(0, 7);
108
+ const head = record.head_sha.slice(0, 7);
109
+ const marker = `<!-- visual-baseline-wait: ${JSON.stringify(record)} -->`;
110
+ if (state === 'queued') {
111
+ return [
112
+ markerFor(record.context),
113
+ `<!-- sha: ${record.head_sha} -->`,
114
+ marker,
115
+ '### Storybook visual comparison — queued',
116
+ '',
117
+ `The base snapshots for \`${expected}\` are published. The comparison for \`${head}\` has been queued and will replace this message.`
118
+ ].join('\n');
119
+ }
120
+ if (state === 'unavailable') {
121
+ return [
122
+ markerFor(record.context),
123
+ `<!-- sha: ${record.head_sha} -->`,
124
+ marker,
125
+ '### Storybook visual comparison — base snapshots unavailable',
126
+ '',
127
+ `The base CI run completed without publishing the required \`${record.prefix}/${expected}\` snapshots. No screenshots were classified as new. Rebase or restack onto a commit with a published baseline.`
128
+ ].join('\n');
129
+ }
130
+ return [
131
+ markerFor(record.context),
132
+ `<!-- sha: ${record.head_sha} -->`,
133
+ marker,
134
+ '### Storybook visual comparison — waiting for base snapshots',
135
+ '',
136
+ `The safe baseline is \`${record.prefix}/${expected}\`. Its CI run is still publishing, so screenshots for \`${head}\` were not classified as new. The comparison will resume automatically after publication.`
137
+ ].join('\n');
138
+ }
139
+
140
+ async function currentStatus(api, sha, context) {
141
+ const combined = await api('GET', `/commits/${sha}/status`, CombinedStatus);
142
+ return combined.statuses.find((status) => status.context === context) ?? null;
143
+ }
144
+
145
+ async function allPages(api, apiPath, schema) {
146
+ const items = [];
147
+ for (let page = 1; page <= 100; page += 1) {
148
+ const separator = apiPath.includes('?') ? '&' : '?';
149
+ const batch = await api('GET', `${apiPath}${separator}per_page=100&page=${page}`, schema);
150
+ items.push(...batch);
151
+ if (batch.length < 100) return items;
152
+ }
153
+ throw new Error(`pagination limit exceeded for ${apiPath}`);
154
+ }
155
+
156
+ async function listComments(api, prNumber) {
157
+ return allPages(api, `/issues/${prNumber}/comments`, Comments);
158
+ }
159
+
160
+ async function upsertComment(api, prNumber, context, body) {
161
+ const comments = await listComments(api, prNumber);
162
+ const existing = comments.find(
163
+ (comment) => isManagedComment(comment) && comment.body?.includes(markerFor(context))
164
+ );
165
+ if (existing) {
166
+ await api('PATCH', `/issues/comments/${existing.id}`, null, { body });
167
+ return existing.id;
168
+ }
169
+ const created = await api(
170
+ 'POST',
171
+ `/issues/${prNumber}/comments`,
172
+ z.object({ id: z.number().int().positive() }),
173
+ { body }
174
+ );
175
+ return created.id;
176
+ }
177
+
178
+ async function publisherStillWaiting(api, sha, context) {
179
+ const status = await currentStatus(api, sha, context);
180
+ return status?.state === 'pending' && status.description?.startsWith('waiting for ');
181
+ }
182
+
183
+ export async function markWaiting({ api, record, prNumber, runUrl, workflowFile = 'ci.yml' }) {
184
+ const runs = await api(
185
+ 'GET',
186
+ `/actions/workflows/${encodeURIComponent(workflowFile)}/runs?head_sha=${record.expected_sha}&per_page=20`,
187
+ WorkflowRuns
188
+ );
189
+ const active = runs.workflow_runs.some(
190
+ (run) => run.head_sha === record.expected_sha && run.status !== 'completed'
191
+ );
192
+ const upstreamWaiting = active
193
+ ? false
194
+ : await publisherStillWaiting(api, record.expected_sha, record.context);
195
+ const waiting = active || upstreamWaiting;
196
+ await api('POST', `/statuses/${record.head_sha}`, null, {
197
+ state: waiting ? 'pending' : 'failure',
198
+ context: record.context,
199
+ description: waiting ? waitingDescription(record) : unavailableDescription(record),
200
+ target_url: runUrl
201
+ });
202
+ await upsertComment(
203
+ api,
204
+ prNumber,
205
+ record.context,
206
+ buildWaitComment(record, waiting ? 'waiting' : 'unavailable')
207
+ );
208
+ return waiting ? 'waiting' : 'unavailable';
209
+ }
210
+
211
+ async function latestRunForHead(api, headSha, workflowFile = 'ci.yml') {
212
+ const runs = await api(
213
+ 'GET',
214
+ `/actions/workflows/${encodeURIComponent(workflowFile)}/runs?head_sha=${headSha}&event=pull_request&per_page=1`,
215
+ WorkflowRuns
216
+ );
217
+ return runs.workflow_runs[0] ?? null;
218
+ }
219
+
220
+ export async function resumeWaiters({
221
+ api,
222
+ owner,
223
+ completedSha,
224
+ completedBranch,
225
+ completedRunId,
226
+ isPublished,
227
+ workflowFile = 'ci.yml'
228
+ }) {
229
+ const basePulls = await allPages(
230
+ api,
231
+ `/pulls?state=open&base=${encodeURIComponent(completedBranch)}`,
232
+ Pulls
233
+ );
234
+ const headPulls = await allPages(
235
+ api,
236
+ `/pulls?state=open&head=${encodeURIComponent(`${owner}:${completedBranch}`)}`,
237
+ Pulls
238
+ );
239
+ const pulls = [...new Map([...basePulls, ...headPulls].map((pr) => [pr.number, pr])).values()];
240
+ const results = [];
241
+ for (const pr of pulls) {
242
+ let comments;
243
+ try {
244
+ comments = await listComments(api, pr.number);
245
+ } catch (error) {
246
+ results.push({
247
+ pr: pr.number,
248
+ result: 'error',
249
+ message: error instanceof Error ? error.message : String(error)
250
+ });
251
+ continue;
252
+ }
253
+ for (const comment of comments) {
254
+ if (!isManagedComment(comment)) continue;
255
+ try {
256
+ const record = parseWaitRecord(comment.body);
257
+ if (!record) continue;
258
+ const publisherCompleted =
259
+ record.expected_sha === completedSha && record.base_ref === completedBranch;
260
+ const originCompleted =
261
+ record.run_id === completedRunId && record.head_sha === completedSha;
262
+ if (!publisherCompleted && !originCompleted) continue;
263
+ if (record.head_sha !== pr.head.sha || record.base_ref !== pr.base.ref) {
264
+ results.push({ pr: pr.number, context: record.context, result: 'stale' });
265
+ continue;
266
+ }
267
+ const published = await isPublished(record.prefix, record.expected_sha);
268
+ const status = await currentStatus(api, record.head_sha, record.context);
269
+ const isWaiting =
270
+ status?.state === 'pending' && status.description === waitingDescription(record);
271
+ const isRecoverableFailure =
272
+ published &&
273
+ status?.state === 'failure' &&
274
+ status.description === unavailableDescription(record);
275
+ if (!isWaiting && !isRecoverableFailure) {
276
+ results.push({ pr: pr.number, context: record.context, result: 'superseded' });
277
+ continue;
278
+ }
279
+ const latestRun = await latestRunForHead(api, record.head_sha, workflowFile);
280
+ if (!latestRun || latestRun.id !== record.run_id) {
281
+ results.push({ pr: pr.number, context: record.context, result: 'superseded' });
282
+ continue;
283
+ }
284
+ if (!published) {
285
+ if (await publisherStillWaiting(api, record.expected_sha, record.context)) {
286
+ results.push({ pr: pr.number, context: record.context, result: 'upstream-waiting' });
287
+ continue;
288
+ }
289
+ await api('POST', `/statuses/${record.head_sha}`, null, {
290
+ state: 'failure',
291
+ context: record.context,
292
+ description: unavailableDescription(record)
293
+ });
294
+ await api('PATCH', `/issues/comments/${comment.id}`, null, {
295
+ body: buildWaitComment(record, 'unavailable')
296
+ });
297
+ results.push({ pr: pr.number, context: record.context, result: 'unavailable' });
298
+ continue;
299
+ }
300
+ const run = await api('GET', `/actions/runs/${record.run_id}`, WorkflowRun);
301
+ if (run.status !== 'completed') {
302
+ results.push({ pr: pr.number, context: record.context, result: 'run-active' });
303
+ continue;
304
+ }
305
+ const jobs = await api(
306
+ 'GET',
307
+ `/actions/runs/${record.run_id}/jobs?filter=latest&per_page=100`,
308
+ Jobs
309
+ );
310
+ const job = [...jobs.jobs]
311
+ .reverse()
312
+ .find((candidate) => candidate.name === record.job_name);
313
+ if (!job || job.status !== 'completed') {
314
+ results.push({ pr: pr.number, context: record.context, result: 'job-unavailable' });
315
+ continue;
316
+ }
317
+ await api('POST', `/actions/jobs/${job.id}/rerun`, null, {});
318
+ await api('POST', `/statuses/${record.head_sha}`, null, {
319
+ state: 'pending',
320
+ context: record.context,
321
+ description: `${record.prefix} baseline published; comparison queued`
322
+ });
323
+ await api('PATCH', `/issues/comments/${comment.id}`, null, {
324
+ body: buildWaitComment(record, 'queued')
325
+ });
326
+ results.push({ pr: pr.number, context: record.context, result: 'queued' });
327
+ } catch (error) {
328
+ results.push({
329
+ pr: pr.number,
330
+ result: 'error',
331
+ message: error instanceof Error ? error.message : String(error)
332
+ });
333
+ }
334
+ }
335
+ }
336
+ return results;
337
+ }
338
+
339
+ /**
340
+ * Build an `isPublished(prefix, sha)` check that asks the AWS CLI whether any
341
+ * object exists under `<prefix>/<sha>/` in an S3-compatible bucket. `endpoint`
342
+ * is needed only for non-AWS providers; `region` falls back to the CLI's own
343
+ * configuration when omitted.
344
+ */
345
+ export function createS3Publisher({ bucket, endpoint, region }) {
346
+ const exec = promisify(execFile);
347
+ const cache = new Map();
348
+ return async (prefix, sha) => {
349
+ const key = `${prefix}/${sha}`;
350
+ if (!cache.has(key)) {
351
+ const args = [
352
+ 's3api',
353
+ 'list-objects-v2',
354
+ '--bucket',
355
+ bucket,
356
+ '--prefix',
357
+ `${prefix}/${sha}/`,
358
+ '--max-keys',
359
+ '1',
360
+ ...(endpoint ? ['--endpoint-url', endpoint] : []),
361
+ ...(region ? ['--region', region] : []),
362
+ '--cli-connect-timeout',
363
+ '10',
364
+ '--cli-read-timeout',
365
+ '30',
366
+ '--query',
367
+ 'KeyCount',
368
+ '--output',
369
+ 'text'
370
+ ];
371
+ cache.set(
372
+ key,
373
+ exec('aws', args, { env: process.env, timeout: 40_000 }).then(
374
+ ({ stdout }) => KeyCount.parse(stdout.trim()) > 0
375
+ )
376
+ );
377
+ }
378
+ return cache.get(key);
379
+ };
380
+ }
381
+
382
+ export { createGitHubApi };