@samebase/alchemy-convex 0.16.0 → 0.18.0

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,307 @@
1
+ // The command `alchemy-convex stack-comment`: one comment on a pull request with the stacks of the
2
+ // repository, read from the state store after the deploys.
3
+ //
4
+ // A stack sees only itself, so a comment that a stack declares cannot show the other stacks of the
5
+ // repository. This command runs as a step after them and reads each stack named `owner/name` or
6
+ // `owner/name/<folder>` that has the stage `pr-<number>`. A stack without that stage has no card. A
7
+ // run replaces the whole body, so the last run shows the newest state.
8
+ //
9
+ // It reads only the fields of the rows below, because Alchemy state holds secrets in clear text.
10
+ //
11
+ // GitHub keeps a fixed set of HTML in a comment and removes `style` and `class`, so every choice of
12
+ // the markup is a fact about the sanitizer or the CSS of github.com:
13
+ // - A table has `display: block` and `width: max-content`, so a `width` on it does nothing. The
14
+ // spacer, a floated image one pixel high in a block of its own, gives every card one width, and
15
+ // it shrinks on a narrow page.
16
+ // - The CSS colors the even rows of a group, so each row has its own `tbody`.
17
+ // - An HTML block ends at a blank line, so a table has none and is not indented.
18
+ // - A bare image links to its raw file, and one link around an image and text underlines the space
19
+ // between them, so the icon and the name are two links to one place.
20
+ // - An image with `height` gets a gray background, so each icon is square and has only `width`.
21
+ // - `align="middle"` is `-webkit-baseline-middle` in Chrome, which is below the text.
22
+ // `align="absmiddle"` is the CSS value `middle`.
23
+ import { State } from "alchemy/State";
24
+ import * as Effect from "effect/Effect";
25
+ import * as Schema from "effect/Schema";
26
+ import { RUN_RECORD_KEY, runRecord } from "./RunRecord.ts";
27
+
28
+ /** The first text of the comment, which finds it again. */
29
+ const MARKER = "<!-- samebase-stacks -->";
30
+
31
+ /** GitHub does not proxy this host, so a new icon needs no purge of its image cache. */
32
+ const ICONS = "https://raw.githubusercontent.com/samebase/alchemy-convex/main/assets/stack-comment";
33
+
34
+ const GITHUB_API = "https://api.github.com";
35
+
36
+ /** The resources that a card shows. A row of any other type, or without `attr` from an interrupted deploy, is left out. */
37
+ const Resource = Schema.Union([
38
+ Schema.Struct({
39
+ resourceType: Schema.Literal("Convex.Deployment"),
40
+ attr: Schema.Struct({ name: Schema.String, siteUrl: Schema.String }),
41
+ }),
42
+ Schema.Struct({
43
+ resourceType: Schema.Literal("Cloudflare.Worker"),
44
+ attr: Schema.Struct({ workerName: Schema.String, url: Schema.optional(Schema.String) }),
45
+ }),
46
+ Schema.Struct({
47
+ resourceType: Schema.Literal("Cloudflare.R2.Bucket"),
48
+ attr: Schema.Struct({
49
+ bucketName: Schema.String,
50
+ accountId: Schema.String,
51
+ jurisdiction: Schema.String,
52
+ }),
53
+ }),
54
+ ]);
55
+ type Resource = typeof Resource.Type;
56
+
57
+ /** The fields of the run record that a card shows. */
58
+ const StageOutput = Schema.Struct({
59
+ [RUN_RECORD_KEY]: Schema.Struct({
60
+ headCommit: Schema.String,
61
+ runUrl: Schema.NullOr(Schema.String),
62
+ recordedAt: Schema.String,
63
+ }),
64
+ });
65
+
66
+ export interface StackCard {
67
+ readonly name: string;
68
+ readonly stage: string;
69
+ readonly resources: readonly Resource[];
70
+ readonly run: typeof StageOutput.Type | null;
71
+ }
72
+
73
+ export class StackCommentError extends Schema.TaggedError<StackCommentError>()(
74
+ "StackCommentError",
75
+ { reason: Schema.String },
76
+ ) {
77
+ override get message() {
78
+ return `The stack comment cannot be updated: ${this.reason}`;
79
+ }
80
+ }
81
+
82
+ /** The cards of the stacks of `repository` that have `stage`, in name order. */
83
+ export const readStackCards = ({ repository, stage }: { repository: string; stage: string }) =>
84
+ Effect.gen(function* () {
85
+ const state = yield* yield* State;
86
+ const names = (yield* state.listStacks()).filter(
87
+ (name) => name === repository || name.startsWith(`${repository}/`),
88
+ );
89
+ const cards: StackCard[] = [];
90
+ for (const name of names) {
91
+ if (!(yield* state.listStages(name)).includes(stage)) {
92
+ continue;
93
+ }
94
+ const request = { stack: name, stage };
95
+ const rows = yield* Effect.forEach(yield* state.list(request), (fqn) =>
96
+ state.get({ ...request, fqn }),
97
+ );
98
+ const output = yield* state.getOutput(request);
99
+ cards.push({
100
+ name,
101
+ stage,
102
+ resources: rows.filter(Schema.is(Resource)),
103
+ run: Schema.is(StageOutput)(output) ? output : null,
104
+ });
105
+ }
106
+ return cards;
107
+ });
108
+
109
+ /** A stack can create a deployment in one resource and push to it in another: a card shows it once. */
110
+ const withoutRepeats = (resources: readonly Resource[]) => {
111
+ const deployments = new Set<string>();
112
+ return resources.filter((resource) => {
113
+ if (resource.resourceType !== "Convex.Deployment") {
114
+ return true;
115
+ }
116
+ const repeated = deployments.has(resource.attr.name);
117
+ deployments.add(resource.attr.name);
118
+ return !repeated;
119
+ });
120
+ };
121
+
122
+ const escapeHtml = (text: string) =>
123
+ text
124
+ .replaceAll("&", "&amp;")
125
+ .replaceAll("<", "&lt;")
126
+ .replaceAll(">", "&gt;")
127
+ .replaceAll('"', "&quot;");
128
+
129
+ const link = (href: string, text: string) => `<a href="${escapeHtml(href)}">${text}</a>`;
130
+
131
+ const named = (href: string, icon: string, alt: string, name: string) => {
132
+ const image = `<img src="${ICONS}/${icon}.svg" width="16" align="absmiddle" alt="${alt}">`;
133
+ return `${link(href, image)} ${link(href, escapeHtml(name))}`;
134
+ };
135
+
136
+ const hostOf = (url: string) => escapeHtml(new URL(url).host);
137
+
138
+ /** Where a stack serves: its Convex deployment, else its first Worker with a URL. */
139
+ const addressOf = (resources: readonly Resource[]) => {
140
+ for (const resource of resources) {
141
+ if (resource.resourceType === "Convex.Deployment") {
142
+ return resource.attr.siteUrl;
143
+ }
144
+ }
145
+ for (const resource of resources) {
146
+ if (resource.resourceType === "Cloudflare.Worker" && resource.attr.url !== undefined) {
147
+ return resource.attr.url;
148
+ }
149
+ }
150
+ return null;
151
+ };
152
+
153
+ const resourceRow = (resource: Resource, address: string | null) => {
154
+ switch (resource.resourceType) {
155
+ case "Convex.Deployment": {
156
+ const { name } = resource.attr;
157
+ return named(
158
+ `https://dashboard.convex.dev/d/${encodeURIComponent(name)}`,
159
+ "convex",
160
+ "Convex",
161
+ name,
162
+ );
163
+ }
164
+ case "Cloudflare.Worker": {
165
+ const { url, workerName } = resource.attr;
166
+ const row = named(
167
+ `https://dash.cloudflare.com/?to=/:account/workers/services/view/${encodeURIComponent(workerName)}`,
168
+ "worker",
169
+ "Worker",
170
+ workerName,
171
+ );
172
+ return url === undefined || url === address
173
+ ? row
174
+ : `${row}<br><sub>${link(url, hostOf(url))}</sub>`;
175
+ }
176
+ case "Cloudflare.R2.Bucket": {
177
+ const { accountId, bucketName, jurisdiction } = resource.attr;
178
+ return named(
179
+ `https://dash.cloudflare.com/${encodeURIComponent(accountId)}/r2/${encodeURIComponent(jurisdiction)}/buckets/${encodeURIComponent(bucketName)}`,
180
+ "r2",
181
+ "R2 bucket",
182
+ bucketName,
183
+ );
184
+ }
185
+ }
186
+ };
187
+
188
+ const runLine = ({ run }: StackCard) => {
189
+ if (run === null) {
190
+ return "";
191
+ }
192
+ const { headCommit, recordedAt, runUrl } = run[RUN_RECORD_KEY];
193
+ const commit = escapeHtml(headCommit.slice(0, 7));
194
+ const time = `${recordedAt.slice(0, 16).replace("T", " ")} UTC`;
195
+ return `<br><sub>${runUrl === null ? commit : link(runUrl, commit)} ${escapeHtml(time)}</sub>`;
196
+ };
197
+
198
+ const SPACER = `<div><img src="${ICONS}/spacer.svg" width="460" align="left" alt=""></div>`;
199
+
200
+ /** `alone`: the one card of the repository. A card at the root then has no folder, as on the repository page. */
201
+ const renderCard = (card: StackCard, repository: string, alone: boolean) => {
202
+ const folder = card.name.slice(repository.length + 1);
203
+ const heading = [
204
+ folder === "" && alone ? "" : `<b>${escapeHtml(folder || "/")}</b> `,
205
+ `<sub>${escapeHtml(card.stage)}</sub>`,
206
+ ].join("");
207
+ const resources = withoutRepeats(card.resources);
208
+ const address = addressOf(resources);
209
+ const addressLine = address === null ? "" : `<br>${link(address, hostOf(address))}`;
210
+ const rows = resources
211
+ .map((resource) => `<tbody><tr><td>${resourceRow(resource, address)}</td></tr></tbody>`)
212
+ .join("\n");
213
+ return `<table>
214
+ <tbody><tr><td>${SPACER}${heading}${addressLine}${runLine(card)}</td></tr></tbody>
215
+ ${rows}
216
+ </table>`;
217
+ };
218
+
219
+ export const renderStackComment = (cards: readonly StackCard[], repository: string) => `${MARKER}
220
+ ${cards.map((card) => renderCard(card, repository, cards.length === 1)).join("\n\n")}
221
+ `;
222
+
223
+ const Comments = Schema.Array(Schema.Struct({ id: Schema.Number, body: Schema.String }));
224
+ const SavedComment = Schema.Struct({ html_url: Schema.String });
225
+
226
+ const github = (token: string, path: string, init: { method: string; body?: string }) =>
227
+ Effect.tryPromise({
228
+ try: async (): Promise<unknown> => {
229
+ const response = await fetch(`${GITHUB_API}${path}`, {
230
+ ...init,
231
+ headers: {
232
+ Accept: "application/vnd.github+json",
233
+ Authorization: `Bearer ${token}`,
234
+ "Content-Type": "application/json",
235
+ "X-GitHub-Api-Version": "2022-11-28",
236
+ },
237
+ });
238
+ if (!response.ok) {
239
+ throw new Error(`HTTP ${response.status}`);
240
+ }
241
+ return await response.json();
242
+ },
243
+ catch: (error) =>
244
+ new StackCommentError({
245
+ reason: `GitHub ${init.method} ${path} failed (${error instanceof Error ? error.message : String(error)})`,
246
+ }),
247
+ });
248
+
249
+ const decode =
250
+ <S extends Schema.Codec<unknown, unknown>>(schema: S, what: string) =>
251
+ (value: unknown) =>
252
+ Schema.decodeUnknownEffect(schema)(value).pipe(
253
+ Effect.mapError(() => new StackCommentError({ reason: `GitHub gave a bad ${what}` })),
254
+ );
255
+
256
+ const findComment = (token: string, path: string) =>
257
+ Effect.gen(function* () {
258
+ for (let page = 1; ; page += 1) {
259
+ const comments = yield* github(token, `${path}?per_page=100&page=${page}`, {
260
+ method: "GET",
261
+ }).pipe(Effect.flatMap(decode(Comments, "comment list")));
262
+ const comment = comments.find(({ body }) => body.startsWith(MARKER));
263
+ if (comment !== undefined || comments.length < 100) {
264
+ return comment;
265
+ }
266
+ }
267
+ });
268
+
269
+ /** Replaces the body of the comment of this command, or posts it on the first run, and gives its URL. */
270
+ export const saveStackComment = (args: {
271
+ readonly token: string;
272
+ readonly repository: string;
273
+ readonly pullRequest: number;
274
+ readonly body: string;
275
+ }) =>
276
+ Effect.gen(function* () {
277
+ const { body, pullRequest, repository, token } = args;
278
+ const comments = `/repos/${repository}/issues/${pullRequest}/comments`;
279
+ const comment = yield* findComment(token, comments);
280
+ const reply = yield* comment === undefined
281
+ ? github(token, comments, { method: "POST", body: JSON.stringify({ body }) })
282
+ : github(token, `/repos/${repository}/issues/comments/${comment.id}`, {
283
+ method: "PATCH",
284
+ body: JSON.stringify({ body }),
285
+ });
286
+ const saved = yield* decode(SavedComment, "comment")(reply);
287
+ return saved.html_url;
288
+ });
289
+
290
+ /** The step of a workflow: the run record names the repository and the pull request of the run. */
291
+ export const updateStackComment = Effect.gen(function* () {
292
+ const { pullRequest, repository } = yield* runRecord({ cwd: process.cwd(), env: process.env });
293
+ if (pullRequest === null) {
294
+ return yield* new StackCommentError({ reason: "this run has no pull request" });
295
+ }
296
+ const token = process.env["GITHUB_TOKEN"];
297
+ if (token === undefined || token === "") {
298
+ return yield* new StackCommentError({ reason: "GITHUB_TOKEN is not set" });
299
+ }
300
+ const cards = yield* readStackCards({ repository, stage: `pr-${pullRequest}` });
301
+ return yield* saveStackComment({
302
+ token,
303
+ repository,
304
+ pullRequest,
305
+ body: renderStackComment(cards, repository),
306
+ });
307
+ });
package/src/cli.ts CHANGED
@@ -1,19 +1,25 @@
1
1
  #!/usr/bin/env node
2
- // The command of the package:
2
+ // The commands of the package:
3
3
  //
4
4
  // alchemy-convex hub-client --team <team> --app <app> --callback-path <path>
5
+ // alchemy-convex stack-comment [--team <team>]
5
6
  //
6
- // It runs in the directory of a Convex app, and gives the development deployment of that directory
7
- // a client of the identity hub of the team: see registerDevelopmentClient. It uses
8
- // CONVEX_ACCESS_TOKEN or the Convex CLI login.
7
+ // hub-client runs in the directory of a Convex app, and gives the development deployment of that
8
+ // directory a client of the identity hub of the team: see registerDevelopmentClient. stack-comment
9
+ // runs as a step of a pull request workflow after the deploys, and keeps one comment with the stacks
10
+ // of the repository: see src/StackComment.ts. It needs GITHUB_TOKEN and, with a team access token,
11
+ // no --team. Both use CONVEX_ACCESS_TOKEN or the Convex CLI login.
9
12
  import { execFileSync } from "node:child_process";
10
13
  import { parseArgs } from "node:util";
14
+ import * as NodeServices from "@effect/platform-node/NodeServices";
11
15
  import * as Effect from "effect/Effect";
12
16
  import * as Layer from "effect/Layer";
13
17
  import { fromConfig } from "./Credentials.ts";
14
18
  import { registerDevelopmentClient } from "./HubClient.ts";
15
19
  import { ManagementApiLive } from "./ManagementApi.ts";
16
20
  import { installedCli } from "./Push.ts";
21
+ import { updateStackComment } from "./StackComment.ts";
22
+ import { state } from "./State.ts";
17
23
 
18
24
  const { positionals, values } = parseArgs({
19
25
  allowPositionals: true,
@@ -24,38 +30,50 @@ const { positionals, values } = parseArgs({
24
30
  },
25
31
  });
26
32
  const { team, app, "callback-path": callbackPath } = values;
27
- if (
28
- positionals.join(" ") !== "hub-client" ||
29
- team === undefined ||
30
- app === undefined ||
31
- callbackPath === undefined
32
- ) {
33
- console.error(
34
- "Usage: alchemy-convex hub-client --team <team> --app <app> --callback-path <path>",
33
+ const USAGE = `Usage:
34
+ alchemy-convex hub-client --team <team> --app <app> --callback-path <path>
35
+ alchemy-convex stack-comment [--team <team>]`;
36
+
37
+ const hubClient = (hub: { team: string; app: string; callbackPath: string }) =>
38
+ Effect.gen(function* () {
39
+ const [command, ...prefix] = yield* installedCli(process.cwd());
40
+ const callbackUrl = yield* registerDevelopmentClient({
41
+ ...hub,
42
+ convex: (args, input) =>
43
+ execFileSync(command, [...prefix, ...args], {
44
+ encoding: "utf8",
45
+ input,
46
+ stdio: ["pipe", "pipe", "inherit"],
47
+ }).trim(),
48
+ });
49
+ console.log(
50
+ callbackUrl === undefined
51
+ ? "Hub client already registered."
52
+ : `Hub client registered for ${callbackUrl}.`,
53
+ );
54
+ }).pipe(Effect.provide(ManagementApiLive().pipe(Layer.provide(fromConfig()))));
55
+
56
+ const stackComment = (options: { team?: string }) =>
57
+ updateStackComment.pipe(
58
+ Effect.tap((url) => Effect.sync(() => console.log(url))),
59
+ Effect.provide(state(options).pipe(Layer.provide(NodeServices.layer))),
35
60
  );
61
+
62
+ const subcommand = positionals.join(" ");
63
+ const program: Effect.Effect<unknown, unknown> | undefined =
64
+ subcommand === "stack-comment"
65
+ ? stackComment(team === undefined ? {} : { team })
66
+ : subcommand === "hub-client" &&
67
+ team !== undefined &&
68
+ app !== undefined &&
69
+ callbackPath !== undefined
70
+ ? hubClient({ team, app, callbackPath })
71
+ : undefined;
72
+ if (program === undefined) {
73
+ console.error(USAGE);
36
74
  process.exit(1);
37
75
  }
38
76
 
39
- const program = Effect.gen(function* () {
40
- const [command, ...prefix] = yield* installedCli(process.cwd());
41
- const callbackUrl = yield* registerDevelopmentClient({
42
- team,
43
- app,
44
- callbackPath,
45
- convex: (args, input) =>
46
- execFileSync(command, [...prefix, ...args], {
47
- encoding: "utf8",
48
- input,
49
- stdio: ["pipe", "pipe", "inherit"],
50
- }).trim(),
51
- });
52
- console.log(
53
- callbackUrl === undefined
54
- ? "Hub client already registered."
55
- : `Hub client registered for ${callbackUrl}.`,
56
- );
57
- }).pipe(Effect.provide(ManagementApiLive().pipe(Layer.provide(fromConfig()))));
58
-
59
77
  await Effect.runPromise(program).catch((error: unknown) => {
60
78
  console.error(error instanceof Error ? error.message : String(error));
61
79
  process.exit(1);