@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.
@@ -0,0 +1,200 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { z } from 'zod';
6
+ import {
7
+ createGitHubApi,
8
+ DEFAULT_APPROVAL_LABEL,
9
+ DEFAULT_CONTEXT,
10
+ verifyApproval
11
+ } from '../approval.mjs';
12
+ import { createS3Publisher, markWaiting, resumeWaiters, WaitRecordSchema } from '../wait.mjs';
13
+ import { generateVisualCatalog } from '../catalog.mjs';
14
+
15
+ const USAGE = `Usage: bench-reg <command> [flags]
16
+
17
+ Commands:
18
+ verify-approval Check an approval or re-run checkbox and apply it.
19
+ Env: GITHUB_TOKEN (or GH_TOKEN), GITHUB_REPOSITORY (or REPO), PR, ACTOR, COMMENT_BODY.
20
+ Flags: --action approve|rerun, --context <status>, --label <label>,
21
+ --job <job name>, --workflow <workflow file>.
22
+ mark-waiter Mark a PR as waiting for its base baseline to publish.
23
+ Env: GITHUB_TOKEN, GITHUB_REPOSITORY, GITHUB_SERVER_URL, GITHUB_RUN_ID, CONTEXT,
24
+ PATH_PREFIX, EXPECTED_SHA, SHA, BASE_REF, JOB_NAME, PR_NUMBER.
25
+ resume-waiters Re-run waiting comparisons once a baseline is published.
26
+ Env: GITHUB_TOKEN, GITHUB_REPOSITORY, COMPLETED_SHA, COMPLETED_BRANCH,
27
+ COMPLETED_RUN_ID, REG_S3_BUCKET_NAME, optional REG_S3_ENDPOINT and
28
+ AWS_REGION or REG_S3_REGION.
29
+ catalog Write the Storybook visual catalog JSON.
30
+ Flags: --root <dir>, --out <file>, --check.
31
+
32
+ mark-waiter, resume-waiters and verify-approval also read WORKFLOW_FILE (default ci.yml).
33
+ `;
34
+
35
+ function requiredEnv(name, env = process.env) {
36
+ const value = env[name];
37
+ if (!value) throw new Error(`${name} is required`);
38
+ return value;
39
+ }
40
+
41
+ function parseRepository(repoSpec) {
42
+ const [owner, repo, extra] = String(repoSpec || '').split('/');
43
+ if (!owner || !repo || extra) {
44
+ throw new Error(`Invalid repository '${repoSpec}'; expected 'owner/repo'`);
45
+ }
46
+ return { owner, repo };
47
+ }
48
+
49
+ function parseArgs(argv) {
50
+ const [command, ...rest] = argv;
51
+ const flags = {};
52
+ for (let i = 0; i < rest.length; i += 1) {
53
+ const token = rest[i];
54
+ if (!token.startsWith('--')) continue;
55
+ const key = token.slice(2);
56
+ const next = rest[i + 1];
57
+ if (next === undefined || next.startsWith('--')) {
58
+ flags[key] = true;
59
+ } else {
60
+ flags[key] = next;
61
+ i += 1;
62
+ }
63
+ }
64
+ return { command, flags };
65
+ }
66
+
67
+ export async function runCli(argv = process.argv.slice(2), env = process.env) {
68
+ const { command, flags } = parseArgs(argv);
69
+ const workflowFile = String(flags.workflow || env.WORKFLOW_FILE || 'ci.yml');
70
+
71
+ if (command === 'help' || command === '--help' || command === '-h') {
72
+ process.stdout.write(USAGE);
73
+ return 0;
74
+ }
75
+
76
+ if (command === 'verify-approval') {
77
+ const token = env.GH_TOKEN || requiredEnv('GITHUB_TOKEN', env);
78
+ const { owner, repo } = parseRepository(env.REPO || requiredEnv('GITHUB_REPOSITORY', env));
79
+ const prNumber = z.coerce.number().int().positive().parse(requiredEnv('PR', env));
80
+ const actor = requiredEnv('ACTOR', env);
81
+ const commentBody = requiredEnv('COMMENT_BODY', env);
82
+ const context = flags.context || env.CONTEXT || env.REG_SUIT_STATUS_CONTEXT || DEFAULT_CONTEXT;
83
+ const approvalLabel = flags.label || env.APPROVAL_LABEL || DEFAULT_APPROVAL_LABEL;
84
+ const action = flags.action || env.ACTION || 'approve';
85
+ const jobName = flags.job || env.JOB_NAME || 'storybook';
86
+
87
+ const api = createGitHubApi(token, owner, repo);
88
+ const result = await verifyApproval({
89
+ api,
90
+ owner,
91
+ repo,
92
+ prNumber,
93
+ actor,
94
+ commentBody,
95
+ context,
96
+ approvalLabel,
97
+ action,
98
+ jobName,
99
+ workflowFile
100
+ });
101
+ console.log(JSON.stringify(result));
102
+ if (result.status === 'denied' || result.status === 'error') {
103
+ return 1;
104
+ }
105
+ return 0;
106
+ }
107
+
108
+ if (command === 'resume-waiters') {
109
+ const token = env.GITHUB_TOKEN || requiredEnv('GH_TOKEN', env);
110
+ const { owner, repo } = parseRepository(requiredEnv('GITHUB_REPOSITORY', env));
111
+ const api = createGitHubApi(token, owner, repo);
112
+ const results = await resumeWaiters({
113
+ api,
114
+ owner,
115
+ completedSha: z
116
+ .string()
117
+ .regex(/^[a-f0-9]{40}$/)
118
+ .parse(requiredEnv('COMPLETED_SHA', env)),
119
+ completedBranch: requiredEnv('COMPLETED_BRANCH', env),
120
+ completedRunId: z.coerce
121
+ .number()
122
+ .int()
123
+ .positive()
124
+ .parse(requiredEnv('COMPLETED_RUN_ID', env)),
125
+ isPublished: createS3Publisher({
126
+ bucket: requiredEnv('REG_S3_BUCKET_NAME', env),
127
+ endpoint: env.REG_S3_ENDPOINT || undefined,
128
+ region: env.AWS_REGION || env.REG_S3_REGION || undefined
129
+ }),
130
+ workflowFile
131
+ });
132
+ console.log(JSON.stringify(results));
133
+ return results.some((r) => r.result === 'error') ? 1 : 0;
134
+ }
135
+
136
+ if (command === 'mark-waiter') {
137
+ const token = env.GITHUB_TOKEN || requiredEnv('GH_TOKEN', env);
138
+ const { owner, repo } = parseRepository(requiredEnv('GITHUB_REPOSITORY', env));
139
+ const api = createGitHubApi(token, owner, repo);
140
+ const record = WaitRecordSchema.parse({
141
+ context: requiredEnv('CONTEXT', env),
142
+ prefix: requiredEnv('PATH_PREFIX', env),
143
+ expected_sha: requiredEnv('EXPECTED_SHA', env),
144
+ head_sha: requiredEnv('SHA', env),
145
+ base_ref: requiredEnv('BASE_REF', env),
146
+ run_id: Number(requiredEnv('GITHUB_RUN_ID', env)),
147
+ job_name: requiredEnv('JOB_NAME', env)
148
+ });
149
+ const state = await markWaiting({
150
+ api,
151
+ record,
152
+ prNumber: Number(requiredEnv('PR_NUMBER', env)),
153
+ runUrl: `${requiredEnv('GITHUB_SERVER_URL', env)}/${owner}/${repo}/actions/runs/${record.run_id}`,
154
+ workflowFile
155
+ });
156
+ console.log(JSON.stringify({ state, record }));
157
+ return 0;
158
+ }
159
+
160
+ if (command === 'catalog') {
161
+ const rootDir = path.resolve(String(flags.root || process.cwd()));
162
+ const catalog = generateVisualCatalog(rootDir);
163
+ const serialized = `${JSON.stringify(catalog, null, '\t')}\n`;
164
+ if (flags.out) {
165
+ const outPath = path.resolve(String(flags.out));
166
+ if (flags.check) {
167
+ const existing = fs.existsSync(outPath) ? fs.readFileSync(outPath, 'utf8') : '';
168
+ if (existing !== serialized) {
169
+ console.error(`Visual catalog out of date: ${outPath}`);
170
+ return 1;
171
+ }
172
+ return 0;
173
+ }
174
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
175
+ fs.writeFileSync(outPath, serialized, 'utf8');
176
+ } else {
177
+ process.stdout.write(serialized);
178
+ }
179
+ return 0;
180
+ }
181
+
182
+ process.stderr.write(USAGE);
183
+ return 1;
184
+ }
185
+
186
+ export function isDirectEntryPoint(metaUrl, argv1) {
187
+ if (typeof argv1 !== 'string' || argv1.length === 0) {
188
+ return false;
189
+ }
190
+ try {
191
+ return fs.realpathSync(fileURLToPath(metaUrl)) === fs.realpathSync(argv1);
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+
197
+ if (isDirectEntryPoint(import.meta.url, process.argv[1])) {
198
+ const code = await runCli(process.argv.slice(2));
199
+ process.exitCode = code;
200
+ }
package/catalog.d.mts ADDED
@@ -0,0 +1,24 @@
1
+ export interface StoryCatalogEntry {
2
+ file: string;
3
+ title: string;
4
+ tags: string[];
5
+ stories: string[];
6
+ visual: boolean;
7
+ }
8
+
9
+ export interface VisualCatalog {
10
+ version: 1;
11
+ totalFiles: number;
12
+ visualEntries: StoryCatalogEntry[];
13
+ excluded: StoryCatalogEntry[];
14
+ }
15
+
16
+ export declare function discoverStoryFiles(
17
+ rootDir: string,
18
+ options?: { ignoreDirs?: string[] }
19
+ ): string[];
20
+ export declare function parseStoryMeta(source: string, relativePath: string): StoryCatalogEntry;
21
+ export declare function generateVisualCatalog(
22
+ rootDir: string,
23
+ options?: { ignoreDirs?: string[] }
24
+ ): VisualCatalog;
package/catalog.mjs ADDED
@@ -0,0 +1,106 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ const DEFAULT_IGNORED_DIRS = new Set([
5
+ 'node_modules',
6
+ '.git',
7
+ 'dist',
8
+ 'build',
9
+ '.svelte-kit',
10
+ '.turbo',
11
+ 'storybook-static',
12
+ 'coverage'
13
+ ]);
14
+
15
+ const STORY_FILE_RE = /\.stories\.(svelte|ts|tsx|js|mjs)$/;
16
+
17
+ function toPosix(filePath) {
18
+ return filePath.split(path.sep).join('/');
19
+ }
20
+
21
+ /**
22
+ * Recursively discover Storybook story files in deterministic POSIX-sorted order.
23
+ */
24
+ export function discoverStoryFiles(rootDir, options = {}) {
25
+ const ignored = new Set([...DEFAULT_IGNORED_DIRS, ...(options.ignoreDirs || [])]);
26
+ const found = [];
27
+
28
+ function walk(currentDir) {
29
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
30
+ for (const entry of entries) {
31
+ if (entry.isDirectory()) {
32
+ if (ignored.has(entry.name)) continue;
33
+ walk(path.join(currentDir, entry.name));
34
+ } else if (entry.isFile() && STORY_FILE_RE.test(entry.name)) {
35
+ const abs = path.join(currentDir, entry.name);
36
+ found.push(toPosix(path.relative(rootDir, abs)));
37
+ }
38
+ }
39
+ }
40
+
41
+ if (fs.existsSync(rootDir)) {
42
+ walk(rootDir);
43
+ }
44
+ return found.sort();
45
+ }
46
+
47
+ /**
48
+ * Extract Storybook title, tags, and named stories from a `.stories.svelte` or CSF file.
49
+ */
50
+ export function parseStoryMeta(source, relativePath) {
51
+ const titleMatch = source.match(/\btitle\s*:\s*['"`]([^'"`]+)['"`]/);
52
+ const title =
53
+ titleMatch?.[1] ||
54
+ relativePath.replace(STORY_FILE_RE, '').split('/').filter(Boolean).pop() ||
55
+ relativePath;
56
+
57
+ const tagsMatch = source.match(/\btags\s*:\s*\[([^\]]*)\]/);
58
+ const tags = [];
59
+ if (tagsMatch) {
60
+ for (const m of tagsMatch[1].matchAll(/['"`]([^'"`]+)['"`]/g)) {
61
+ tags.push(m[1]);
62
+ }
63
+ }
64
+
65
+ const stories = [];
66
+ for (const m of source.matchAll(/<Story\b[^>]*\bname\s*=\s*['"`]([^'"`]+)['"`]/g)) {
67
+ stories.push(m[1]);
68
+ }
69
+ if (stories.length === 0) {
70
+ for (const m of source.matchAll(/export\s+const\s+([A-Za-z0-9_]+)\s*[:=]/g)) {
71
+ if (m[1] !== 'default' && m[1] !== 'meta' && m[1] !== 'Story') {
72
+ stories.push(m[1]);
73
+ }
74
+ }
75
+ }
76
+
77
+ const visual = !tags.includes('!visual');
78
+ return {
79
+ file: relativePath,
80
+ title,
81
+ tags,
82
+ stories,
83
+ visual
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Auto-discover all Storybook stories under `rootDir` and build a deterministic
89
+ * visual regression catalog. Stories tagged with `'!visual'` are excluded from
90
+ * `visualEntries` while remaining recorded in `excluded`.
91
+ */
92
+ export function generateVisualCatalog(rootDir, options = {}) {
93
+ const files = discoverStoryFiles(rootDir, options);
94
+ const entries = files.map((relPath) => {
95
+ const absPath = path.join(rootDir, ...relPath.split('/'));
96
+ const source = fs.readFileSync(absPath, 'utf8');
97
+ return parseStoryMeta(source, relPath);
98
+ });
99
+
100
+ return {
101
+ version: 1,
102
+ totalFiles: entries.length,
103
+ visualEntries: entries.filter((entry) => entry.visual),
104
+ excluded: entries.filter((entry) => !entry.visual)
105
+ };
106
+ }
@@ -0,0 +1,11 @@
1
+ 'use strict';
2
+
3
+ function designNotificationMarker(context) {
4
+ return `<!-- slack-design-review-open: ${context} -->`;
5
+ }
6
+
7
+ function hasDesignNotificationMarker(body, context) {
8
+ return String(body || '').includes(designNotificationMarker(context));
9
+ }
10
+
11
+ module.exports = { designNotificationMarker, hasDesignNotificationMarker };
package/index.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ declare namespace pluginFactory {
2
+ interface ComparisonResult {
3
+ failedItems: string[];
4
+ newItems: string[];
5
+ deletedItems: string[];
6
+ passedItems: string[];
7
+ }
8
+
9
+ interface NotifyParams {
10
+ comparisonResult: ComparisonResult;
11
+ reportUrl?: string;
12
+ }
13
+
14
+ interface PluginOptions {
15
+ /** Commit status context and sticky-comment marker. Defaults to `DEFAULT_CONTEXT`. */
16
+ statusContext?: string;
17
+ /** Public host that serves the published reports; falls back to `REG_S3_CUSTOM_DOMAIN`. */
18
+ customDomain?: string;
19
+ /** Report path prefix under `customDomain`. `pages` switches labels and headings to pages. */
20
+ pathPrefix?: string;
21
+ /** Thumbnails shown per section of the PR comment. Defaults to 5. */
22
+ sampleCap?: number;
23
+ /** GitHub login to Slack user ID, used to mention the PR author. */
24
+ slackUserMap?: Record<string, string>;
25
+ /** JSON file holding `slackUserMap`, resolved against the working directory. */
26
+ slackUserMapPath?: string;
27
+ }
28
+
29
+ interface Logger {
30
+ info(msg: string): void;
31
+ warn(msg: string): void;
32
+ error(msg: string): void;
33
+ }
34
+
35
+ class ForgeNotifier {
36
+ init(config: {
37
+ coreConfig: unknown;
38
+ workingDirs: unknown;
39
+ logger: Logger;
40
+ options?: PluginOptions;
41
+ }): void;
42
+ notify(params: NotifyParams): Promise<void>;
43
+ }
44
+
45
+ function markerFor(context: string): string;
46
+ const DEFAULT_CONTEXT: string;
47
+ const VISUAL_APPROVAL_LABEL: string;
48
+ function visualApprovalLabelFor(pathPrefix: string): string;
49
+ function parseSlackUserMap(raw: unknown): Record<string, string>;
50
+ function designNotificationMarker(context: string): string;
51
+ function hasDesignNotificationMarker(body: string, context: string): boolean;
52
+ }
53
+
54
+ declare function pluginFactory(): { notifier: pluginFactory.ForgeNotifier };
55
+
56
+ export = pluginFactory;