@tahminator/pipeline 1.0.100 → 1.0.101

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/README.md CHANGED
@@ -126,7 +126,7 @@ Choose one command source: a hardcoded list or a Bun script.
126
126
  | Source | Default-branch workflow configuration. | Script from the authorized PR head. |
127
127
  | Best for | A fixed list of commands. | Computing the list from repository code or data. |
128
128
 
129
- Both use the same permission checks and dispatch to repository-owned command workflows.
129
+ Both use the same permission checks and dispatch to repository-owned command workflows. Set `ALLOWED_TEAMS` to also require membership in one of the listed organization teams; see [access control](./actions/commands/README.md#access-control).
130
130
 
131
131
  ### Examples
132
132
 
@@ -331,10 +331,29 @@ await client.updateK8sTagWithPR({
331
331
  mergeAttempts: 10,
332
332
  });
333
333
 
334
+ // posts a new comment and returns it; keep `id` to edit it later
335
+ const comment = await client.sendPrMessage({
336
+ owner: "tahminator",
337
+ repository: "pipeline",
338
+ prId: 123,
339
+ message: "Deploying...",
340
+ });
341
+
342
+ // replaces the body of an existing PR comment
343
+ await client.editPrMessage({
344
+ owner: "tahminator",
345
+ repository: "pipeline",
346
+ commentId: comment.id,
347
+ message: "Deployed and healthy.",
348
+ });
349
+
350
+ // with `key`, the first run creates the comment and later runs on the same PR update it in place
351
+ // instead of posting a new one each time
334
352
  await client.sendPrMessage({
335
353
  owner: "tahminator",
336
354
  repository: "pipeline",
337
355
  prId: 123,
356
+ key: "deploy-status",
338
357
  message: "Deployed and healthy.",
339
358
  });
340
359
 
@@ -83,7 +83,52 @@ export declare class GitHubClient {
83
83
  * ```
84
84
  */
85
85
  updateK8sTagWithPR(...args: Parameters<GitHubPRManager["updateK8sTagWithPR"]>): Promise<void>;
86
- sendPrMessage(...args: Parameters<GitHubPRManager["sendPrMessage"]>): Promise<void>;
86
+ /**
87
+ * Posts a comment on a PR and returns it.
88
+ *
89
+ * Pass `key` to upsert instead: the first call creates the comment, and later calls with the
90
+ * same `key` on the same PR edit it in place. Useful for CI reports that re-run on every push.
91
+ * The key is stored as a hidden HTML marker at the top of the comment, and only comments posted
92
+ * by a bot account are matched.
93
+ */
94
+ sendPrMessage(...args: Parameters<GitHubPRManager["sendPrMessage"]>): Promise<{
95
+ id: number;
96
+ node_id: string;
97
+ url: string;
98
+ body?: string;
99
+ body_text?: string;
100
+ body_html?: string;
101
+ html_url: string;
102
+ user: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
103
+ created_at: string;
104
+ updated_at: string;
105
+ issue_url: string;
106
+ author_association: import("@octokit/openapi-types").components["schemas"]["author-association"];
107
+ performed_via_github_app?: import("@octokit/openapi-types").components["schemas"]["nullable-integration"];
108
+ reactions?: import("@octokit/openapi-types").components["schemas"]["reaction-rollup"];
109
+ }>;
110
+ /**
111
+ * Replaces the body of an existing PR comment, e.g. one returned by `sendPrMessage`.
112
+ *
113
+ * @note GitHub Apps can only edit comments they created unless they have `Issues: write`
114
+ * or `Pull requests: write` on the repository.
115
+ */
116
+ editPrMessage(...args: Parameters<GitHubPRManager["editPrMessage"]>): Promise<{
117
+ id: number;
118
+ node_id: string;
119
+ url: string;
120
+ body?: string;
121
+ body_text?: string;
122
+ body_html?: string;
123
+ html_url: string;
124
+ user: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
125
+ created_at: string;
126
+ updated_at: string;
127
+ issue_url: string;
128
+ author_association: import("@octokit/openapi-types").components["schemas"]["author-association"];
129
+ performed_via_github_app?: import("@octokit/openapi-types").components["schemas"]["nullable-integration"];
130
+ reactions?: import("@octokit/openapi-types").components["schemas"]["reaction-rollup"];
131
+ }>;
87
132
  /**
88
133
  * Uploads files as an artifact of the current workflow run and returns its download URL.
89
134
  *
package/dist/gh/client.js CHANGED
@@ -112,9 +112,26 @@ export class GitHubClient {
112
112
  updateK8sTagWithPR(...args) {
113
113
  return this.prManager.updateK8sTagWithPR(...args);
114
114
  }
115
+ /**
116
+ * Posts a comment on a PR and returns it.
117
+ *
118
+ * Pass `key` to upsert instead: the first call creates the comment, and later calls with the
119
+ * same `key` on the same PR edit it in place. Useful for CI reports that re-run on every push.
120
+ * The key is stored as a hidden HTML marker at the top of the comment, and only comments posted
121
+ * by a bot account are matched.
122
+ */
115
123
  sendPrMessage(...args) {
116
124
  return this.prManager.sendPrMessage(...args);
117
125
  }
126
+ /**
127
+ * Replaces the body of an existing PR comment, e.g. one returned by `sendPrMessage`.
128
+ *
129
+ * @note GitHub Apps can only edit comments they created unless they have `Issues: write`
130
+ * or `Pull requests: write` on the repository.
131
+ */
132
+ editPrMessage(...args) {
133
+ return this.prManager.editPrMessage(...args);
134
+ }
118
135
  /**
119
136
  * Uploads files as an artifact of the current workflow run and returns its download URL.
120
137
  *
@@ -98,12 +98,53 @@ export declare class GitHubPRManager {
98
98
  pull_requests: import("@octokit/openapi-types").components["schemas"]["pull-request-minimal"][];
99
99
  deployment?: import("@octokit/openapi-types").components["schemas"]["deployment-simple"];
100
100
  } | null>;
101
- sendPrMessage({ prId, owner, repository, message, }: {
101
+ sendPrMessage({ prId, owner, repository, message, key, }: {
102
102
  prId: number;
103
103
  owner: string;
104
104
  repository: string;
105
105
  message: string;
106
- }): Promise<void>;
106
+ /**
107
+ * When set, updates the bot comment previously sent with the same `key` on this PR
108
+ * instead of posting a new one, and creates it if none exists yet.
109
+ */
110
+ key?: string;
111
+ }): Promise<{
112
+ id: number;
113
+ node_id: string;
114
+ url: string;
115
+ body?: string;
116
+ body_text?: string;
117
+ body_html?: string;
118
+ html_url: string;
119
+ user: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
120
+ created_at: string;
121
+ updated_at: string;
122
+ issue_url: string;
123
+ author_association: import("@octokit/openapi-types").components["schemas"]["author-association"];
124
+ performed_via_github_app?: import("@octokit/openapi-types").components["schemas"]["nullable-integration"];
125
+ reactions?: import("@octokit/openapi-types").components["schemas"]["reaction-rollup"];
126
+ }>;
127
+ editPrMessage({ commentId, owner, repository, message, }: {
128
+ commentId: number;
129
+ owner: string;
130
+ repository: string;
131
+ message: string;
132
+ }): Promise<{
133
+ id: number;
134
+ node_id: string;
135
+ url: string;
136
+ body?: string;
137
+ body_text?: string;
138
+ body_html?: string;
139
+ html_url: string;
140
+ user: import("@octokit/openapi-types").components["schemas"]["nullable-simple-user"];
141
+ created_at: string;
142
+ updated_at: string;
143
+ issue_url: string;
144
+ author_association: import("@octokit/openapi-types").components["schemas"]["author-association"];
145
+ performed_via_github_app?: import("@octokit/openapi-types").components["schemas"]["nullable-integration"];
146
+ reactions?: import("@octokit/openapi-types").components["schemas"]["reaction-rollup"];
147
+ }>;
107
148
  private createDirectoryTree;
108
149
  private createDirectoryBlobEntries;
109
150
  private getDirectoryPathPrefix;
@@ -184,13 +184,49 @@ export class GitHubPRManager {
184
184
  }
185
185
  }
186
186
  }
187
- async sendPrMessage({ prId, owner, repository, message, }) {
188
- await this.client.rest.issues.createComment({
187
+ async sendPrMessage({ prId, owner, repository, message, key, }) {
188
+ if (key === undefined) {
189
+ const { data } = await this.client.rest.issues.createComment({
190
+ issue_number: prId,
191
+ owner,
192
+ repo: repository,
193
+ body: message,
194
+ });
195
+ return data;
196
+ }
197
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/.test(key)) {
198
+ throw new Error("key must start with a letter or digit and contain only letters, digits, '_', '.', ':' or '-'");
199
+ }
200
+ const marker = `<!-- pipeline-pr-message:${key} -->`;
201
+ const body = `${marker}\n${message}`;
202
+ for await (const { data: comments } of this.client.paginate.iterator(this.client.rest.issues.listComments, { owner, repo: repository, issue_number: prId, per_page: 100 })) {
203
+ const existing = comments.find((comment) => comment.user?.type === "Bot" &&
204
+ comment.body?.startsWith(`${marker}\n`));
205
+ if (existing) {
206
+ return this.editPrMessage({
207
+ commentId: existing.id,
208
+ owner,
209
+ repository,
210
+ message: body,
211
+ });
212
+ }
213
+ }
214
+ const { data } = await this.client.rest.issues.createComment({
189
215
  issue_number: prId,
190
216
  owner,
191
217
  repo: repository,
218
+ body,
219
+ });
220
+ return data;
221
+ }
222
+ async editPrMessage({ commentId, owner, repository, message, }) {
223
+ const { data } = await this.client.rest.issues.updateComment({
224
+ comment_id: commentId,
225
+ owner,
226
+ repo: repository,
192
227
  body: message,
193
228
  });
229
+ return data;
194
230
  }
195
231
  async createDirectoryTree({ owner, repository, sourceDirectory, directory, baseTreeSha, }) {
196
232
  const pathPrefix = this.getDirectoryPathPrefix(directory);
@@ -3,5 +3,18 @@ export declare function parseCommands(input: string, file: string): {
3
3
  commands: string;
4
4
  file: string;
5
5
  };
6
+ /** Empty input means no team restriction. */
7
+ export declare function parseTeams(input: string): string[];
8
+ /**
9
+ * Uses the REST API directly because this action runs with `--no-install` and
10
+ * consumers only provide `yargs`. Pending invitations are not membership.
11
+ */
12
+ export declare function isActiveMemberOfAnyTeam({ teams, org, username, token, apiUrl, }: {
13
+ teams: string[];
14
+ org: string;
15
+ username: string;
16
+ token: string;
17
+ apiUrl: string;
18
+ }): Promise<boolean>;
6
19
  /** Runs only after the action has checked write permission and rejected fork heads. */
7
20
  export declare function loadCommands(file: string, workspace: string): Promise<string>;
@@ -1,5 +1,6 @@
1
1
  import { realpath, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
+ const NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
3
4
  /** Exactly one source: inline names or a repository-owned Bun loader. */
4
5
  export function parseCommands(input, file) {
5
6
  if (Boolean(input.trim()) === Boolean(file.trim())) {
@@ -14,12 +15,43 @@ export function parseCommands(input, file) {
14
15
  return { commands: "", file };
15
16
  }
16
17
  const commands = input.split(/[\s,]+/).filter(Boolean);
17
- if (!commands.length ||
18
- commands.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(name))) {
18
+ if (!commands.length || commands.some((name) => !NAME_PATTERN.test(name))) {
19
19
  throw new Error("COMMANDS must contain command names separated by commas or newlines");
20
20
  }
21
21
  return { commands: commands.join("\n"), file: "" };
22
22
  }
23
+ /** Empty input means no team restriction. */
24
+ export function parseTeams(input) {
25
+ const teams = input.split(/[\s,]+/).filter(Boolean);
26
+ if (teams.some((slug) => !NAME_PATTERN.test(slug))) {
27
+ throw new Error("ALLOWED_TEAMS must contain team slugs separated by commas or newlines");
28
+ }
29
+ return teams;
30
+ }
31
+ /**
32
+ * Uses the REST API directly because this action runs with `--no-install` and
33
+ * consumers only provide `yargs`. Pending invitations are not membership.
34
+ */
35
+ export async function isActiveMemberOfAnyTeam({ teams, org, username, token, apiUrl, }) {
36
+ for (const team of teams) {
37
+ const response = await fetch(`${apiUrl}/orgs/${encodeURIComponent(org)}/teams/${team}/memberships/${encodeURIComponent(username)}`, {
38
+ headers: {
39
+ Accept: "application/vnd.github+json",
40
+ Authorization: `Bearer ${token}`,
41
+ "X-GitHub-Api-Version": "2022-11-28",
42
+ },
43
+ });
44
+ if (response.status === 404)
45
+ continue;
46
+ if (!response.ok) {
47
+ throw new Error(`Membership lookup for team ${team} failed with ${response.status}: ${await response.text()}`);
48
+ }
49
+ const { state } = (await response.json());
50
+ if (state === "active")
51
+ return true;
52
+ }
53
+ return false;
54
+ }
23
55
  /** Runs only after the action has checked write permission and rejected fork heads. */
24
56
  export async function loadCommands(file, workspace) {
25
57
  const root = await realpath(workspace);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,45 @@
1
+ import { appendFile } from "node:fs/promises";
2
+ import yargs from "yargs";
3
+ import { isActiveMemberOfAnyTeam, parseTeams } from "./helper";
4
+ const { allowedTeams, org, username } = await yargs(process.argv.slice(2))
5
+ .option("allowedTeams", {
6
+ type: "string",
7
+ default: "",
8
+ describe: "Team slugs separated by commas or newlines; empty allows all",
9
+ })
10
+ .option("org", {
11
+ type: "string",
12
+ demandOption: true,
13
+ describe: "Organization that owns the teams",
14
+ })
15
+ .option("username", {
16
+ type: "string",
17
+ demandOption: true,
18
+ describe: "Commenter to check",
19
+ })
20
+ .strict()
21
+ .parse();
22
+ async function main() {
23
+ const output = process.env.GITHUB_OUTPUT;
24
+ if (!output)
25
+ throw new Error("GITHUB_OUTPUT is required");
26
+ const teams = parseTeams(allowedTeams);
27
+ if (teams.length) {
28
+ const token = process.env.GITHUB_TOKEN;
29
+ if (!token)
30
+ throw new Error("GITHUB_TOKEN is required");
31
+ const allowed = await isActiveMemberOfAnyTeam({
32
+ teams,
33
+ org,
34
+ username,
35
+ token,
36
+ apiUrl: process.env.GITHUB_API_URL ?? "https://api.github.com",
37
+ });
38
+ if (!allowed) {
39
+ console.log(`::notice::Slash commands require active membership in one of: ${teams.join(", ")}.`);
40
+ return;
41
+ }
42
+ }
43
+ await appendFile(output, "allowed=true\n");
44
+ }
45
+ await main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tahminator/pipeline",
3
- "version": "1.0.100",
3
+ "version": "1.0.101",
4
4
  "description": "A collection of Bun shell scripts that can be re-used in various CICD pipelines.",
5
5
  "author": "Tahmid Ahmed",
6
6
  "repository": {