@samebase/alchemy-convex 0.43.0 → 0.44.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.
package/README.md CHANGED
@@ -239,22 +239,24 @@ Alchemy state holds no time, commit, branch, or run. `Convex.withRunRecord(state
239
239
  stage output of any state layer, `Convex.state()` or `Cloudflare.state()`: the document that
240
240
  `setOutput` stores is the stack's output plus the key `samebase.run`. Samebase shows a stage only
241
241
  when its output has this record. On GitHub Actions the record comes from the run's variables and the
242
- event payload; on a development machine from git, which needs a branch and an `origin` remote. It
243
- holds no secret. The function comes from `@samebase/alchemy-kit/run-record` and works over any state
244
- layer.
242
+ event payload; on a development machine from git, which needs a branch and a github.com `origin`
243
+ remote, and from one GitHub API request for the repository ids. It holds no secret. The function
244
+ comes from `@samebase/alchemy-kit/run-record` and works over any state layer.
245
245
 
246
246
  ```json
247
247
  {
248
248
  "convexUrl": "https://modest-guanaco-252.convex.cloud",
249
249
  "samebase.run": {
250
- "version": 1,
251
- "repository": "samebase/base-alchemy",
250
+ "version": 2,
251
+ "source": "github-actions",
252
+ "repositoryId": "123456789",
253
+ "repositoryOwnerId": "987654321",
254
+ "repositoryName": "samebase/base-alchemy",
252
255
  "stackFile": "alchemy.run.ts",
253
256
  "branch": "feature",
254
257
  "pullRequest": 42,
255
258
  "headCommit": "8af3c5b7932c528939cbc7aa0597b1fc36c8dc83",
256
259
  "runUrl": "https://github.com/samebase/base-alchemy/actions/runs/12345678901/attempts/1",
257
- "source": "github-actions",
258
260
  "recordedAt": "2026-10-21T10:00:00.000Z"
259
261
  }
260
262
  }
@@ -490,8 +492,11 @@ steps:
490
492
  GITHUB_TOKEN: ${{ github.token }}
491
493
  ```
492
494
 
493
- A stack named `owner/name`, or `owner/name/<folder>` for a stack in a folder, belongs to the
494
- repository `owner/name`. A stack without the stage of the pull request has no card.
495
+ A stage whose version 2 run record has the repository id of the run belongs to the repository, under
496
+ any stack name. A stage with another repository id does not. A stage without a version 2 record
497
+ belongs to the repository `owner/name` when its stack is named `owner/name`, or
498
+ `owner/name/<folder>` for a stack in a folder. A stack without the stage of the pull request has no
499
+ card.
495
500
 
496
501
  ## Data safety
497
502
 
package/lib/cli.js CHANGED
@@ -3,6 +3,7 @@ import { n as state } from "./State-Bp7iSx8T.js";
3
3
  import * as Effect from "effect/Effect";
4
4
  import * as Schema from "effect/Schema";
5
5
  import * as Layer from "effect/Layer";
6
+ import * as Option from "effect/Option";
6
7
  import { parseArgs } from "node:util";
7
8
  import { State } from "alchemy/State";
8
9
  import { RUN_RECORD_KEY, runRecord } from "@samebase/alchemy-kit/run-record";
@@ -21,22 +22,35 @@ const StageOutput = Schema.Struct({ [RUN_RECORD_KEY]: Schema.Struct({
21
22
  runUrl: Schema.NullOr(Schema.String),
22
23
  recordedAt: Schema.String
23
24
  }) });
25
+ /** The part of a stage output that says which repository deployed it. */
26
+ const RepositoryOfOutput = Schema.Struct({ [RUN_RECORD_KEY]: Schema.Struct({
27
+ version: Schema.Literal(2),
28
+ repositoryId: Schema.String,
29
+ stackFile: Schema.String
30
+ }) });
24
31
  var StackCommentError = class extends Schema.TaggedError()("StackCommentError", { reason: Schema.String }) {
25
32
  get message() {
26
33
  return `The stack comment cannot be updated: ${this.reason}`;
27
34
  }
28
35
  };
29
- /** The cards of the stacks of `repository` that have `stage`, in name order. */
30
- const readStackCards = ({ repository, stage }) => Effect.gen(function* () {
36
+ /**
37
+ * The cards of the stacks of the repository that have `stage`, in name order. A stage with a version
38
+ * 2 record belongs to the repository of its `repositoryId`, under any stack name; any other stage
39
+ * belongs to the stacks named `repository` or `repository/<folder>`.
40
+ */
41
+ const readStackCards = ({ repository, repositoryId, stage }) => Effect.gen(function* () {
31
42
  const state = yield* yield* State;
32
- const names = (yield* state.listStacks()).filter((name) => name === repository || name.startsWith(`${repository}/`));
33
43
  const cards = [];
34
- for (const name of names) {
44
+ for (const name of yield* state.listStacks()) {
35
45
  if (!(yield* state.listStages(name)).includes(stage)) continue;
36
46
  const request = {
37
47
  stack: name,
38
48
  stage
39
49
  };
50
+ const output = yield* state.getOutput(request);
51
+ const underName = name === repository || name.startsWith(`${repository}/`);
52
+ const record = Option.map(Schema.decodeUnknownOption(RepositoryOfOutput)(output), (decoded) => decoded[RUN_RECORD_KEY]);
53
+ if (Option.isSome(record) ? record.value.repositoryId !== repositoryId : !underName) continue;
40
54
  const rows = yield* Effect.forEach(yield* state.list(request), (fqn) => state.get({
41
55
  ...request,
42
56
  fqn
@@ -44,9 +58,9 @@ const readStackCards = ({ repository, stage }) => Effect.gen(function* () {
44
58
  fqn,
45
59
  state: row
46
60
  }))));
47
- const output = yield* state.getOutput(request);
48
61
  cards.push({
49
62
  name,
63
+ folder: underName || Option.isNone(record) ? name.slice(repository.length + 1) : record.value.stackFile.split("/").slice(0, -1).join("/"),
50
64
  stage,
51
65
  diagram: stageDiagram(rows),
52
66
  run: Schema.is(StageOutput)(output) ? output : null
@@ -101,8 +115,8 @@ const runLine = ({ run }) => {
101
115
  };
102
116
  const SPACER = `<div><img src="${ICONS}/spacer.svg" width="460" align="left" alt=""></div>`;
103
117
  /** `alone`: the one card of the repository. A card at the root then has no folder, as on the repository page. */
104
- const renderCard = (card, repository, alone) => {
105
- const folder = card.name.slice(repository.length + 1);
118
+ const renderCard = (card, alone) => {
119
+ const { folder } = card;
106
120
  const heading = [folder === "" && alone ? "" : `<b>${escapeHtml(folder || "/")}</b> `, `<sub>${escapeHtml(card.stage)}</sub>`].join("");
107
121
  const address = addressOf(card.diagram);
108
122
  const addressLine = address === null ? "" : `<br>${link(address, hostOf(address))}`;
@@ -112,8 +126,8 @@ const renderCard = (card, repository, alone) => {
112
126
  ${rows}
113
127
  </table>`;
114
128
  };
115
- const renderStackComment = (cards, repository) => `${MARKER}
116
- ${cards.map((card) => renderCard(card, repository, cards.length === 1)).join("\n\n")}
129
+ const renderStackComment = (cards) => `${MARKER}
130
+ ${cards.map((card) => renderCard(card, cards.length === 1)).join("\n\n")}
117
131
  `;
118
132
  const Comments = Schema.Array(Schema.Struct({
119
133
  id: Schema.Number,
@@ -160,7 +174,7 @@ const saveStackComment = (args) => Effect.gen(function* () {
160
174
  });
161
175
  /** The step of a workflow: the run record names the repository and the pull request of the run. */
162
176
  const updateStackComment = Effect.gen(function* () {
163
- const { pullRequest, repository } = yield* runRecord({
177
+ const { pullRequest, repositoryId, repositoryName: repository } = yield* runRecord({
164
178
  cwd: process.cwd(),
165
179
  env: process.env
166
180
  });
@@ -169,13 +183,14 @@ const updateStackComment = Effect.gen(function* () {
169
183
  if (token === void 0 || token === "") return yield* new StackCommentError({ reason: "GITHUB_TOKEN is not set" });
170
184
  const cards = yield* readStackCards({
171
185
  repository,
186
+ repositoryId,
172
187
  stage: `pr-${pullRequest}`
173
188
  });
174
189
  return yield* saveStackComment({
175
190
  token,
176
191
  repository,
177
192
  pullRequest,
178
- body: renderStackComment(cards, repository)
193
+ body: renderStackComment(cards)
179
194
  });
180
195
  });
181
196
  //#endregion
package/lib/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/StackComment.ts","../src/cli.ts"],"sourcesContent":["// The command `alchemy-convex stack-comment`: one comment on a pull request with the stacks of the\n// repository, read from the state store after the deploys.\n//\n// A stack sees only itself, so a comment that a stack declares cannot show the other stacks of the\n// repository. This command runs as a step after them and reads each stack named `owner/name` or\n// `owner/name/<folder>` that has the stage `pr-<number>`. A stack without that stage has no card. A\n// run replaces the whole body, so the last run shows the newest state.\n//\n// The rows of a card are the boxes of `stageDiagram` from `@samebase/alchemy-kit/stack`, the model\n// of Samebase's stack diagram. Alchemy state holds secrets in clear text, and that model keeps no\n// secret of a row.\n//\n// GitHub keeps a fixed set of HTML in a comment and removes `style` and `class`, so every choice of\n// the markup is a fact about the sanitizer or the CSS of github.com:\n// - A table has `display: block` and `width: max-content`, so a `width` on it does nothing. The\n// spacer, a floated image one pixel high in a block of its own, gives every card one width, and\n// it shrinks on a narrow page.\n// - The CSS colors the even rows of a group, so each row has its own `tbody`.\n// - An HTML block ends at a blank line, so a table has none and is not indented.\n// - A bare image links to its raw file, and one link around an image and text underlines the space\n// between them, so the icon and the name are two links to one place.\n// - An image with `height` gets a gray background, so each icon is square and has only `width`.\n// - `align=\"middle\"` is `-webkit-baseline-middle` in Chrome, which is below the text.\n// `align=\"absmiddle\"` is the CSS value `middle`.\nimport { State } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport { RUN_RECORD_KEY, runRecord } from \"@samebase/alchemy-kit/run-record\";\nimport {\n boxSubtitle,\n stageDiagram,\n stageTree,\n type DiagramBox,\n type StageDiagram,\n type StageTreeNode,\n} from \"@samebase/alchemy-kit/stack\";\nimport { resourceTypeUI } from \"@samebase/alchemy-kit/ui\";\n\n/** The first text of the comment, which finds it again. */\nconst MARKER = \"<!-- samebase-stacks -->\";\n\n/** GitHub does not proxy this host, so a new icon needs no purge of its image cache. */\nconst ICONS =\n \"https://raw.githubusercontent.com/samebase/samebase/main/packages/alchemy-convex/assets/stack-comment\";\n\nconst GITHUB_API = \"https://api.github.com\";\n\n/** The fields of the run record that a card shows. */\nconst StageOutput = Schema.Struct({\n [RUN_RECORD_KEY]: Schema.Struct({\n headCommit: Schema.String,\n runUrl: Schema.NullOr(Schema.String),\n recordedAt: Schema.String,\n }),\n});\n\nexport interface StackCard {\n readonly name: string;\n readonly stage: string;\n readonly diagram: StageDiagram;\n readonly run: typeof StageOutput.Type | null;\n}\n\nexport class StackCommentError extends Schema.TaggedError<StackCommentError>()(\n \"StackCommentError\",\n { reason: Schema.String },\n) {\n override get message() {\n return `The stack comment cannot be updated: ${this.reason}`;\n }\n}\n\n/** The cards of the stacks of `repository` that have `stage`, in name order. */\nexport const readStackCards = ({ repository, stage }: { repository: string; stage: string }) =>\n Effect.gen(function* () {\n const state = yield* yield* State;\n const names = (yield* state.listStacks()).filter(\n (name) => name === repository || name.startsWith(`${repository}/`),\n );\n const cards: StackCard[] = [];\n for (const name of names) {\n if (!(yield* state.listStages(name)).includes(stage)) {\n continue;\n }\n const request = { stack: name, stage };\n const rows = yield* Effect.forEach(yield* state.list(request), (fqn) =>\n state.get({ ...request, fqn }).pipe(Effect.map((row) => ({ fqn, state: row }))),\n );\n const output = yield* state.getOutput(request);\n cards.push({\n name,\n stage,\n diagram: stageDiagram(rows),\n run: Schema.is(StageOutput)(output) ? output : null,\n });\n }\n return cards;\n });\n\nconst escapeHtml = (text: string) =>\n text\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\");\n\nconst link = (href: string, text: string) => `<a href=\"${escapeHtml(href)}\">${text}</a>`;\n\nconst hostOf = (url: string) => escapeHtml(new URL(url).host);\n\n/** The icon file of a resource type, in `ICONS`. A box of any other type has no icon. */\nconst ICON_FILES = new Map([\n [\"Convex.Deployment\", \"convex\"],\n [\"Cloudflare.Worker\", \"worker\"],\n [\"Cloudflare.R2.Bucket\", \"r2\"],\n]);\n\n/** The name of a box, as a link to its dashboard page when it has one. */\nconst boxName = ({ name, resourceType, rows: [first] }: DiagramBox) => {\n const icon = ICON_FILES.get(resourceType);\n const image =\n icon === undefined\n ? null\n : `<img src=\"${ICONS}/${icon}.svg\" width=\"16\" align=\"absmiddle\" alt=\"\">`;\n const text = escapeHtml(name);\n const href = first.dashboard?.href;\n if (href === undefined) {\n return image === null ? text : `${image} ${text}`;\n }\n return image === null ? link(href, text) : `${link(href, image)} ${link(href, text)}`;\n};\n\n/**\nA box of the tree: its name with the labels of its line as code, its type and schedule, and its link\non the next line unless the link is the stage address. Below it, in a list: the boxes that it uses, the rows folded into it, and\nthe boxes that share a resource with it. A repeated box has only its name.\n*/\nconst treeNode = (node: StageTreeNode, address: string | null): string => {\n const { box, labels, repeated } = node;\n const title = `${boxName(box)}${labels.map((label) => ` <code>${escapeHtml(label)}</code>`).join(\"\")}`;\n if (repeated) {\n return title;\n }\n const linkLine =\n box.link === null || box.link === address\n ? \"\"\n : `<br><sub>${link(box.link, hostOf(box.link))}</sub>`;\n const below = [\n ...node.children.map((child) => treeNode(child, address)),\n ...box.folded.map(\n (row) =>\n `<sub>${escapeHtml(`${row.logicalId}, ${resourceTypeUI(row.resourceType).name}`)}</sub>`,\n ),\n ...node.shared.map((text) => `<sub>${escapeHtml(text)}</sub>`),\n ];\n const list =\n below.length === 0 ? \"\" : `<ul>${below.map((item) => `<li>${item}</li>`).join(\"\")}</ul>`;\n return `${title} <sub>${escapeHtml(boxSubtitle(box))}</sub>${linkLine}${list}`;\n};\n\n/** Where a stage serves: its Convex app, else the first box with a link. */\nconst addressOf = ({ boxes }: StageDiagram) =>\n (boxes.find((box) => box.resourceType === \"Convex.Deployment\") ?? boxes.find((box) => box.link))\n ?.link ?? null;\n\nconst runLine = ({ run }: StackCard) => {\n if (run === null) {\n return \"\";\n }\n const { headCommit, recordedAt, runUrl } = run[RUN_RECORD_KEY];\n const commit = escapeHtml(headCommit.slice(0, 7));\n const time = `${recordedAt.slice(0, 16).replace(\"T\", \" \")} UTC`;\n return `<br><sub>${runUrl === null ? commit : link(runUrl, commit)} ${escapeHtml(time)}</sub>`;\n};\n\nconst SPACER = `<div><img src=\"${ICONS}/spacer.svg\" width=\"460\" align=\"left\" alt=\"\"></div>`;\n\n/** `alone`: the one card of the repository. A card at the root then has no folder, as on the repository page. */\nconst renderCard = (card: StackCard, repository: string, alone: boolean) => {\n const folder = card.name.slice(repository.length + 1);\n const heading = [\n folder === \"\" && alone ? \"\" : `<b>${escapeHtml(folder || \"/\")}</b> `,\n `<sub>${escapeHtml(card.stage)}</sub>`,\n ].join(\"\");\n const address = addressOf(card.diagram);\n const addressLine = address === null ? \"\" : `<br>${link(address, hostOf(address))}`;\n const rows = stageTree(card.diagram)\n .map((node) => `<tbody><tr><td>${treeNode(node, address)}</td></tr></tbody>`)\n .join(\"\\n\");\n return `<table>\n<tbody><tr><td>${SPACER}${heading}${addressLine}${runLine(card)}</td></tr></tbody>\n${rows}\n</table>`;\n};\n\nexport const renderStackComment = (cards: readonly StackCard[], repository: string) => `${MARKER}\n${cards.map((card) => renderCard(card, repository, cards.length === 1)).join(\"\\n\\n\")}\n`;\n\nconst Comments = Schema.Array(Schema.Struct({ id: Schema.Number, body: Schema.String }));\nconst SavedComment = Schema.Struct({ html_url: Schema.String });\n\nconst github = (token: string, path: string, init: { method: string; body?: string }) =>\n Effect.tryPromise({\n try: async (): Promise<unknown> => {\n const response = await fetch(`${GITHUB_API}${path}`, {\n ...init,\n headers: {\n Accept: \"application/vnd.github+json\",\n Authorization: `Bearer ${token}`,\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n });\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n return await response.json();\n },\n catch: (error) =>\n new StackCommentError({\n reason: `GitHub ${init.method} ${path} failed (${error instanceof Error ? error.message : String(error)})`,\n }),\n });\n\nconst decode =\n <S extends Schema.Codec<unknown, unknown>>(schema: S, what: string) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => new StackCommentError({ reason: `GitHub gave a bad ${what}` })),\n );\n\nconst findComment = (token: string, path: string) =>\n Effect.gen(function* () {\n for (let page = 1; ; page += 1) {\n const comments = yield* github(token, `${path}?per_page=100&page=${page}`, {\n method: \"GET\",\n }).pipe(Effect.flatMap(decode(Comments, \"comment list\")));\n const comment = comments.find(({ body }) => body.startsWith(MARKER));\n if (comment !== undefined || comments.length < 100) {\n return comment;\n }\n }\n });\n\n/** Replaces the body of the comment of this command, or posts it on the first run, and gives its URL. */\nexport const saveStackComment = (args: {\n readonly token: string;\n readonly repository: string;\n readonly pullRequest: number;\n readonly body: string;\n}) =>\n Effect.gen(function* () {\n const { body, pullRequest, repository, token } = args;\n const comments = `/repos/${repository}/issues/${pullRequest}/comments`;\n const comment = yield* findComment(token, comments);\n const reply = yield* comment === undefined\n ? github(token, comments, { method: \"POST\", body: JSON.stringify({ body }) })\n : github(token, `/repos/${repository}/issues/comments/${comment.id}`, {\n method: \"PATCH\",\n body: JSON.stringify({ body }),\n });\n const saved = yield* decode(SavedComment, \"comment\")(reply);\n return saved.html_url;\n });\n\n/** The step of a workflow: the run record names the repository and the pull request of the run. */\nexport const updateStackComment = Effect.gen(function* () {\n const { pullRequest, repository } = yield* runRecord({ cwd: process.cwd(), env: process.env });\n if (pullRequest === null) {\n return yield* new StackCommentError({ reason: \"this run has no pull request\" });\n }\n const token = process.env[\"GITHUB_TOKEN\"];\n if (token === undefined || token === \"\") {\n return yield* new StackCommentError({ reason: \"GITHUB_TOKEN is not set\" });\n }\n const cards = yield* readStackCards({ repository, stage: `pr-${pullRequest}` });\n return yield* saveStackComment({\n token,\n repository,\n pullRequest,\n body: renderStackComment(cards, repository),\n });\n});\n","#!/usr/bin/env node\n// The command of the package:\n//\n// alchemy-convex stack-comment\n//\n// stack-comment runs as a step of a pull request workflow after the deploys, and keeps one comment\n// with the stacks of the repository: see src/StackComment.ts. It needs GITHUB_TOKEN, and reads the\n// store of the team of CONVEX_ACCESS_TOKEN or of the Convex CLI login.\nimport { parseArgs } from \"node:util\";\nimport * as NodeServices from \"@effect/platform-node/NodeServices\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { updateStackComment } from \"./StackComment.ts\";\nimport { state } from \"./State.ts\";\n\nconst { positionals } = parseArgs({ allowPositionals: true, options: {} });\nconst USAGE = `Usage:\n alchemy-convex stack-comment`;\n\nconst stackComment = updateStackComment.pipe(\n Effect.tap((url) => Effect.sync(() => console.log(url))),\n Effect.provide(state().pipe(Layer.provide(NodeServices.layer))),\n);\n\nif (positionals.join(\" \") !== \"stack-comment\") {\n console.error(USAGE);\n process.exit(1);\n}\n\nawait Effect.runPromise(stackComment).catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;AAuCA,MAAM,SAAS;;A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kB;CAAM,SAAS,CAAC;AAAE,CAAC;AACzE,MAAM,QAAQ;;AAGd,MAAM,eAAe,mBAAmB,KACtC,OAAO,KAAK,QAAQ,OAAO,WAAW,QAAQ,IAAI,GAAG,CAAC,CAAC,GACvD,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,MAAM,QAAQ,aAAa,KAAK,CAAC,CAAC,CAChE;AAEA,IAAI,YAAY,KAAK,GAAG,MAAM,iBAAiB;CAC7C,QAAQ,MAAM,KAAK;CACnB,QAAQ,KAAK,CAAC;AAChB;AAEA,MAAM,OAAO,WAAW,YAAY,CAAC,CAAC,OAAO,UAAmB;CAC9D,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;CACpE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/StackComment.ts","../src/cli.ts"],"sourcesContent":["// The command `alchemy-convex stack-comment`: one comment on a pull request with the stacks of the\n// repository, read from the state store after the deploys.\n//\n// A stack sees only itself, so a comment that a stack declares cannot show the other stacks of the\n// repository. This command runs as a step after them and reads each stack of the repository that\n// has the stage `pr-<number>`: by the repository id of the stage's run record, or, for a stage\n// without a version 2 record, by the name `owner/name` or `owner/name/<folder>`. A stack without\n// that stage has no card. A run replaces the whole body, so the last run shows the newest state.\n//\n// The rows of a card are the boxes of `stageDiagram` from `@samebase/alchemy-kit/stack`, the model\n// of Samebase's stack diagram. Alchemy state holds secrets in clear text, and that model keeps no\n// secret of a row.\n//\n// GitHub keeps a fixed set of HTML in a comment and removes `style` and `class`, so every choice of\n// the markup is a fact about the sanitizer or the CSS of github.com:\n// - A table has `display: block` and `width: max-content`, so a `width` on it does nothing. The\n// spacer, a floated image one pixel high in a block of its own, gives every card one width, and\n// it shrinks on a narrow page.\n// - The CSS colors the even rows of a group, so each row has its own `tbody`.\n// - An HTML block ends at a blank line, so a table has none and is not indented.\n// - A bare image links to its raw file, and one link around an image and text underlines the space\n// between them, so the icon and the name are two links to one place.\n// - An image with `height` gets a gray background, so each icon is square and has only `width`.\n// - `align=\"middle\"` is `-webkit-baseline-middle` in Chrome, which is below the text.\n// `align=\"absmiddle\"` is the CSS value `middle`.\nimport { State } from \"alchemy/State\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { RUN_RECORD_KEY, runRecord } from \"@samebase/alchemy-kit/run-record\";\nimport {\n boxSubtitle,\n stageDiagram,\n stageTree,\n type DiagramBox,\n type StageDiagram,\n type StageTreeNode,\n} from \"@samebase/alchemy-kit/stack\";\nimport { resourceTypeUI } from \"@samebase/alchemy-kit/ui\";\n\n/** The first text of the comment, which finds it again. */\nconst MARKER = \"<!-- samebase-stacks -->\";\n\n/** GitHub does not proxy this host, so a new icon needs no purge of its image cache. */\nconst ICONS =\n \"https://raw.githubusercontent.com/samebase/samebase/main/packages/alchemy-convex/assets/stack-comment\";\n\nconst GITHUB_API = \"https://api.github.com\";\n\n/** The fields of the run record that a card shows. */\nconst StageOutput = Schema.Struct({\n [RUN_RECORD_KEY]: Schema.Struct({\n headCommit: Schema.String,\n runUrl: Schema.NullOr(Schema.String),\n recordedAt: Schema.String,\n }),\n});\n\n/** The part of a stage output that says which repository deployed it. */\nconst RepositoryOfOutput = Schema.Struct({\n [RUN_RECORD_KEY]: Schema.Struct({\n version: Schema.Literal(2),\n repositoryId: Schema.String,\n stackFile: Schema.String,\n }),\n});\n\nexport interface StackCard {\n readonly name: string;\n /** The folder of the stack file in the repository, \"\" at the root. */\n readonly folder: string;\n readonly stage: string;\n readonly diagram: StageDiagram;\n readonly run: typeof StageOutput.Type | null;\n}\n\nexport class StackCommentError extends Schema.TaggedError<StackCommentError>()(\n \"StackCommentError\",\n { reason: Schema.String },\n) {\n override get message() {\n return `The stack comment cannot be updated: ${this.reason}`;\n }\n}\n\n/**\n * The cards of the stacks of the repository that have `stage`, in name order. A stage with a version\n * 2 record belongs to the repository of its `repositoryId`, under any stack name; any other stage\n * belongs to the stacks named `repository` or `repository/<folder>`.\n */\nexport const readStackCards = ({\n repository,\n repositoryId,\n stage,\n}: {\n repository: string;\n repositoryId: string;\n stage: string;\n}) =>\n Effect.gen(function* () {\n const state = yield* yield* State;\n const cards: StackCard[] = [];\n for (const name of yield* state.listStacks()) {\n if (!(yield* state.listStages(name)).includes(stage)) {\n continue;\n }\n const request = { stack: name, stage };\n const output = yield* state.getOutput(request);\n const underName = name === repository || name.startsWith(`${repository}/`);\n const record = Option.map(\n Schema.decodeUnknownOption(RepositoryOfOutput)(output),\n (decoded) => decoded[RUN_RECORD_KEY],\n );\n if (Option.isSome(record) ? record.value.repositoryId !== repositoryId : !underName) {\n continue;\n }\n const rows = yield* Effect.forEach(yield* state.list(request), (fqn) =>\n state.get({ ...request, fqn }).pipe(Effect.map((row) => ({ fqn, state: row }))),\n );\n cards.push({\n name,\n folder:\n underName || Option.isNone(record)\n ? name.slice(repository.length + 1)\n : record.value.stackFile.split(\"/\").slice(0, -1).join(\"/\"),\n stage,\n diagram: stageDiagram(rows),\n run: Schema.is(StageOutput)(output) ? output : null,\n });\n }\n return cards;\n });\n\nconst escapeHtml = (text: string) =>\n text\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\");\n\nconst link = (href: string, text: string) => `<a href=\"${escapeHtml(href)}\">${text}</a>`;\n\nconst hostOf = (url: string) => escapeHtml(new URL(url).host);\n\n/** The icon file of a resource type, in `ICONS`. A box of any other type has no icon. */\nconst ICON_FILES = new Map([\n [\"Convex.Deployment\", \"convex\"],\n [\"Cloudflare.Worker\", \"worker\"],\n [\"Cloudflare.R2.Bucket\", \"r2\"],\n]);\n\n/** The name of a box, as a link to its dashboard page when it has one. */\nconst boxName = ({ name, resourceType, rows: [first] }: DiagramBox) => {\n const icon = ICON_FILES.get(resourceType);\n const image =\n icon === undefined\n ? null\n : `<img src=\"${ICONS}/${icon}.svg\" width=\"16\" align=\"absmiddle\" alt=\"\">`;\n const text = escapeHtml(name);\n const href = first.dashboard?.href;\n if (href === undefined) {\n return image === null ? text : `${image} ${text}`;\n }\n return image === null ? link(href, text) : `${link(href, image)} ${link(href, text)}`;\n};\n\n/**\nA box of the tree: its name with the labels of its line as code, its type and schedule, and its link\non the next line unless the link is the stage address. Below it, in a list: the boxes that it uses, the rows folded into it, and\nthe boxes that share a resource with it. A repeated box has only its name.\n*/\nconst treeNode = (node: StageTreeNode, address: string | null): string => {\n const { box, labels, repeated } = node;\n const title = `${boxName(box)}${labels.map((label) => ` <code>${escapeHtml(label)}</code>`).join(\"\")}`;\n if (repeated) {\n return title;\n }\n const linkLine =\n box.link === null || box.link === address\n ? \"\"\n : `<br><sub>${link(box.link, hostOf(box.link))}</sub>`;\n const below = [\n ...node.children.map((child) => treeNode(child, address)),\n ...box.folded.map(\n (row) =>\n `<sub>${escapeHtml(`${row.logicalId}, ${resourceTypeUI(row.resourceType).name}`)}</sub>`,\n ),\n ...node.shared.map((text) => `<sub>${escapeHtml(text)}</sub>`),\n ];\n const list =\n below.length === 0 ? \"\" : `<ul>${below.map((item) => `<li>${item}</li>`).join(\"\")}</ul>`;\n return `${title} <sub>${escapeHtml(boxSubtitle(box))}</sub>${linkLine}${list}`;\n};\n\n/** Where a stage serves: its Convex app, else the first box with a link. */\nconst addressOf = ({ boxes }: StageDiagram) =>\n (boxes.find((box) => box.resourceType === \"Convex.Deployment\") ?? boxes.find((box) => box.link))\n ?.link ?? null;\n\nconst runLine = ({ run }: StackCard) => {\n if (run === null) {\n return \"\";\n }\n const { headCommit, recordedAt, runUrl } = run[RUN_RECORD_KEY];\n const commit = escapeHtml(headCommit.slice(0, 7));\n const time = `${recordedAt.slice(0, 16).replace(\"T\", \" \")} UTC`;\n return `<br><sub>${runUrl === null ? commit : link(runUrl, commit)} ${escapeHtml(time)}</sub>`;\n};\n\nconst SPACER = `<div><img src=\"${ICONS}/spacer.svg\" width=\"460\" align=\"left\" alt=\"\"></div>`;\n\n/** `alone`: the one card of the repository. A card at the root then has no folder, as on the repository page. */\nconst renderCard = (card: StackCard, alone: boolean) => {\n const { folder } = card;\n const heading = [\n folder === \"\" && alone ? \"\" : `<b>${escapeHtml(folder || \"/\")}</b> `,\n `<sub>${escapeHtml(card.stage)}</sub>`,\n ].join(\"\");\n const address = addressOf(card.diagram);\n const addressLine = address === null ? \"\" : `<br>${link(address, hostOf(address))}`;\n const rows = stageTree(card.diagram)\n .map((node) => `<tbody><tr><td>${treeNode(node, address)}</td></tr></tbody>`)\n .join(\"\\n\");\n return `<table>\n<tbody><tr><td>${SPACER}${heading}${addressLine}${runLine(card)}</td></tr></tbody>\n${rows}\n</table>`;\n};\n\nexport const renderStackComment = (cards: readonly StackCard[]) => `${MARKER}\n${cards.map((card) => renderCard(card, cards.length === 1)).join(\"\\n\\n\")}\n`;\n\nconst Comments = Schema.Array(Schema.Struct({ id: Schema.Number, body: Schema.String }));\nconst SavedComment = Schema.Struct({ html_url: Schema.String });\n\nconst github = (token: string, path: string, init: { method: string; body?: string }) =>\n Effect.tryPromise({\n try: async (): Promise<unknown> => {\n const response = await fetch(`${GITHUB_API}${path}`, {\n ...init,\n headers: {\n Accept: \"application/vnd.github+json\",\n Authorization: `Bearer ${token}`,\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n },\n });\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`);\n }\n return await response.json();\n },\n catch: (error) =>\n new StackCommentError({\n reason: `GitHub ${init.method} ${path} failed (${error instanceof Error ? error.message : String(error)})`,\n }),\n });\n\nconst decode =\n <S extends Schema.Codec<unknown, unknown>>(schema: S, what: string) =>\n (value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => new StackCommentError({ reason: `GitHub gave a bad ${what}` })),\n );\n\nconst findComment = (token: string, path: string) =>\n Effect.gen(function* () {\n for (let page = 1; ; page += 1) {\n const comments = yield* github(token, `${path}?per_page=100&page=${page}`, {\n method: \"GET\",\n }).pipe(Effect.flatMap(decode(Comments, \"comment list\")));\n const comment = comments.find(({ body }) => body.startsWith(MARKER));\n if (comment !== undefined || comments.length < 100) {\n return comment;\n }\n }\n });\n\n/** Replaces the body of the comment of this command, or posts it on the first run, and gives its URL. */\nexport const saveStackComment = (args: {\n readonly token: string;\n readonly repository: string;\n readonly pullRequest: number;\n readonly body: string;\n}) =>\n Effect.gen(function* () {\n const { body, pullRequest, repository, token } = args;\n const comments = `/repos/${repository}/issues/${pullRequest}/comments`;\n const comment = yield* findComment(token, comments);\n const reply = yield* comment === undefined\n ? github(token, comments, { method: \"POST\", body: JSON.stringify({ body }) })\n : github(token, `/repos/${repository}/issues/comments/${comment.id}`, {\n method: \"PATCH\",\n body: JSON.stringify({ body }),\n });\n const saved = yield* decode(SavedComment, \"comment\")(reply);\n return saved.html_url;\n });\n\n/** The step of a workflow: the run record names the repository and the pull request of the run. */\nexport const updateStackComment = Effect.gen(function* () {\n const {\n pullRequest,\n repositoryId,\n repositoryName: repository,\n } = yield* runRecord({ cwd: process.cwd(), env: process.env });\n if (pullRequest === null) {\n return yield* new StackCommentError({ reason: \"this run has no pull request\" });\n }\n const token = process.env[\"GITHUB_TOKEN\"];\n if (token === undefined || token === \"\") {\n return yield* new StackCommentError({ reason: \"GITHUB_TOKEN is not set\" });\n }\n const cards = yield* readStackCards({ repository, repositoryId, stage: `pr-${pullRequest}` });\n return yield* saveStackComment({\n token,\n repository,\n pullRequest,\n body: renderStackComment(cards),\n });\n});\n","#!/usr/bin/env node\n// The command of the package:\n//\n// alchemy-convex stack-comment\n//\n// stack-comment runs as a step of a pull request workflow after the deploys, and keeps one comment\n// with the stacks of the repository: see src/StackComment.ts. It needs GITHUB_TOKEN, and reads the\n// store of the team of CONVEX_ACCESS_TOKEN or of the Convex CLI login.\nimport { parseArgs } from \"node:util\";\nimport * as NodeServices from \"@effect/platform-node/NodeServices\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { updateStackComment } from \"./StackComment.ts\";\nimport { state } from \"./State.ts\";\n\nconst { positionals } = parseArgs({ allowPositionals: true, options: {} });\nconst USAGE = `Usage:\n alchemy-convex stack-comment`;\n\nconst stackComment = updateStackComment.pipe(\n Effect.tap((url) => Effect.sync(() => console.log(url))),\n Effect.provide(state().pipe(Layer.provide(NodeServices.layer))),\n);\n\nif (positionals.join(\" \") !== \"stack-comment\") {\n console.error(USAGE);\n process.exit(1);\n}\n\nawait Effect.runPromise(stackComment).catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;AAyCA,MAAM,SAAS;;AAGf,MAAM,QACJ;AAEF,MAAM,aAAa;;AAGnB,MAAM,cAAc,OAAO,OAAO,GAC/B,iBAAiB,OAAO,OAAO;CAC9B,YAAY,OAAO;CACnB,QAAQ,OAAO,OAAO,OAAO,MAAM;CACnC,YAAY,OAAO;AACrB,CAAC,EACH,CAAC;;AAGD,MAAM,qBAAqB,OAAO,OAAO,GACtC,iBAAiB,OAAO,OAAO;CAC9B,SAAS,OAAO,QAAQ,CAAC;CACzB,cAAc,OAAO;CACrB,WAAW,OAAO;AACpB,CAAC,EACH,CAAC;AAWD,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EAAE,QAAQ,OAAO,OAAO,CAC1B,CAAC,CAAC;CACA,IAAa,UAAU;EACrB,OAAO,wCAAwC,KAAK;CACtD;AACF;;;;;;AAOA,MAAa,kBAAkB,EAC7B,YACA,cACA,YAMA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,OAAO;CAC5B,MAAM,QAAqB,CAAC;CAC5B,KAAK,MAAM,QAAQ,OAAO,MAAM,WAAW,GAAG;EAC5C,IAAI,EAAE,OAAO,MAAM,WAAW,IAAI,EAAA,CAAG,SAAS,KAAK,GACjD;EAEF,MAAM,UAAU;GAAE,OAAO;GAAM;EA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Y,CAAC,CAAC,OAAO,UAAmB;CAC9D,QAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;CACpE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@samebase/alchemy-convex",
3
- "version": "0.43.0",
3
+ "version": "0.44.0",
4
4
  "description": "The Convex plane for Alchemy v2: projects, deployments, environment variables, and the push of the functions",
5
5
  "keywords": [
6
6
  "alchemy",
@@ -50,7 +50,7 @@
50
50
  },
51
51
  "dependencies": {
52
52
  "@convex-dev/platform": "0.1.11",
53
- "@samebase/alchemy-kit": "^0.5.0"
53
+ "@samebase/alchemy-kit": "^0.6.0"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@alchemy.run/cloudflare": "2.0.0-beta.87",
@@ -2,9 +2,10 @@
2
2
  // repository, read from the state store after the deploys.
3
3
  //
4
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.
5
+ // repository. This command runs as a step after them and reads each stack of the repository that
6
+ // has the stage `pr-<number>`: by the repository id of the stage's run record, or, for a stage
7
+ // without a version 2 record, by the name `owner/name` or `owner/name/<folder>`. A stack without
8
+ // that stage has no card. A run replaces the whole body, so the last run shows the newest state.
8
9
  //
9
10
  // The rows of a card are the boxes of `stageDiagram` from `@samebase/alchemy-kit/stack`, the model
10
11
  // of Samebase's stack diagram. Alchemy state holds secrets in clear text, and that model keeps no
@@ -24,6 +25,7 @@
24
25
  // `align="absmiddle"` is the CSS value `middle`.
25
26
  import { State } from "alchemy/State";
26
27
  import * as Effect from "effect/Effect";
28
+ import * as Option from "effect/Option";
27
29
  import * as Schema from "effect/Schema";
28
30
  import { RUN_RECORD_KEY, runRecord } from "@samebase/alchemy-kit/run-record";
29
31
  import {
@@ -54,8 +56,19 @@ const StageOutput = Schema.Struct({
54
56
  }),
55
57
  });
56
58
 
59
+ /** The part of a stage output that says which repository deployed it. */
60
+ const RepositoryOfOutput = Schema.Struct({
61
+ [RUN_RECORD_KEY]: Schema.Struct({
62
+ version: Schema.Literal(2),
63
+ repositoryId: Schema.String,
64
+ stackFile: Schema.String,
65
+ }),
66
+ });
67
+
57
68
  export interface StackCard {
58
69
  readonly name: string;
70
+ /** The folder of the stack file in the repository, "" at the root. */
71
+ readonly folder: string;
59
72
  readonly stage: string;
60
73
  readonly diagram: StageDiagram;
61
74
  readonly run: typeof StageOutput.Type | null;
@@ -70,25 +83,46 @@ export class StackCommentError extends Schema.TaggedError<StackCommentError>()(
70
83
  }
71
84
  }
72
85
 
73
- /** The cards of the stacks of `repository` that have `stage`, in name order. */
74
- export const readStackCards = ({ repository, stage }: { repository: string; stage: string }) =>
86
+ /**
87
+ * The cards of the stacks of the repository that have `stage`, in name order. A stage with a version
88
+ * 2 record belongs to the repository of its `repositoryId`, under any stack name; any other stage
89
+ * belongs to the stacks named `repository` or `repository/<folder>`.
90
+ */
91
+ export const readStackCards = ({
92
+ repository,
93
+ repositoryId,
94
+ stage,
95
+ }: {
96
+ repository: string;
97
+ repositoryId: string;
98
+ stage: string;
99
+ }) =>
75
100
  Effect.gen(function* () {
76
101
  const state = yield* yield* State;
77
- const names = (yield* state.listStacks()).filter(
78
- (name) => name === repository || name.startsWith(`${repository}/`),
79
- );
80
102
  const cards: StackCard[] = [];
81
- for (const name of names) {
103
+ for (const name of yield* state.listStacks()) {
82
104
  if (!(yield* state.listStages(name)).includes(stage)) {
83
105
  continue;
84
106
  }
85
107
  const request = { stack: name, stage };
108
+ const output = yield* state.getOutput(request);
109
+ const underName = name === repository || name.startsWith(`${repository}/`);
110
+ const record = Option.map(
111
+ Schema.decodeUnknownOption(RepositoryOfOutput)(output),
112
+ (decoded) => decoded[RUN_RECORD_KEY],
113
+ );
114
+ if (Option.isSome(record) ? record.value.repositoryId !== repositoryId : !underName) {
115
+ continue;
116
+ }
86
117
  const rows = yield* Effect.forEach(yield* state.list(request), (fqn) =>
87
118
  state.get({ ...request, fqn }).pipe(Effect.map((row) => ({ fqn, state: row }))),
88
119
  );
89
- const output = yield* state.getOutput(request);
90
120
  cards.push({
91
121
  name,
122
+ folder:
123
+ underName || Option.isNone(record)
124
+ ? name.slice(repository.length + 1)
125
+ : record.value.stackFile.split("/").slice(0, -1).join("/"),
92
126
  stage,
93
127
  diagram: stageDiagram(rows),
94
128
  run: Schema.is(StageOutput)(output) ? output : null,
@@ -176,8 +210,8 @@ const runLine = ({ run }: StackCard) => {
176
210
  const SPACER = `<div><img src="${ICONS}/spacer.svg" width="460" align="left" alt=""></div>`;
177
211
 
178
212
  /** `alone`: the one card of the repository. A card at the root then has no folder, as on the repository page. */
179
- const renderCard = (card: StackCard, repository: string, alone: boolean) => {
180
- const folder = card.name.slice(repository.length + 1);
213
+ const renderCard = (card: StackCard, alone: boolean) => {
214
+ const { folder } = card;
181
215
  const heading = [
182
216
  folder === "" && alone ? "" : `<b>${escapeHtml(folder || "/")}</b> `,
183
217
  `<sub>${escapeHtml(card.stage)}</sub>`,
@@ -193,8 +227,8 @@ ${rows}
193
227
  </table>`;
194
228
  };
195
229
 
196
- export const renderStackComment = (cards: readonly StackCard[], repository: string) => `${MARKER}
197
- ${cards.map((card) => renderCard(card, repository, cards.length === 1)).join("\n\n")}
230
+ export const renderStackComment = (cards: readonly StackCard[]) => `${MARKER}
231
+ ${cards.map((card) => renderCard(card, cards.length === 1)).join("\n\n")}
198
232
  `;
199
233
 
200
234
  const Comments = Schema.Array(Schema.Struct({ id: Schema.Number, body: Schema.String }));
@@ -266,7 +300,11 @@ export const saveStackComment = (args: {
266
300
 
267
301
  /** The step of a workflow: the run record names the repository and the pull request of the run. */
268
302
  export const updateStackComment = Effect.gen(function* () {
269
- const { pullRequest, repository } = yield* runRecord({ cwd: process.cwd(), env: process.env });
303
+ const {
304
+ pullRequest,
305
+ repositoryId,
306
+ repositoryName: repository,
307
+ } = yield* runRecord({ cwd: process.cwd(), env: process.env });
270
308
  if (pullRequest === null) {
271
309
  return yield* new StackCommentError({ reason: "this run has no pull request" });
272
310
  }
@@ -274,11 +312,11 @@ export const updateStackComment = Effect.gen(function* () {
274
312
  if (token === undefined || token === "") {
275
313
  return yield* new StackCommentError({ reason: "GITHUB_TOKEN is not set" });
276
314
  }
277
- const cards = yield* readStackCards({ repository, stage: `pr-${pullRequest}` });
315
+ const cards = yield* readStackCards({ repository, repositoryId, stage: `pr-${pullRequest}` });
278
316
  return yield* saveStackComment({
279
317
  token,
280
318
  repository,
281
319
  pullRequest,
282
- body: renderStackComment(cards, repository),
320
+ body: renderStackComment(cards),
283
321
  });
284
322
  });