@samebase/alchemy-convex 0.42.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
  }
@@ -467,9 +469,11 @@ deletes the development client and keeps the deployment.
467
469
  ## Pull request comment
468
470
 
469
471
  `alchemy-convex stack-comment` keeps one comment on a pull request. The comment has a card for each
470
- stack of the repository at the stage `pr-<number>`: the folder, the address, the last run, the
471
- Convex deployments, Workers, and R2 buckets, and the sign-in status and connectors of a
472
- `IdentityHub.Client`. A stack sees only itself, so a comment that a stack declares cannot show this.
472
+ stack of the repository at the stage `pr-<number>`: the folder, the address, the last run, and a row
473
+ for each main resource, with its type, its link and its schedule, each under the resource that uses
474
+ it. The rows come from `stageDiagram` of `@samebase/alchemy-kit/stack`, the same model as Samebase's
475
+ stack diagram, so a project or a hub client shows under its deployment and not as a row of its own.
476
+ A stack sees only itself, so a comment that a stack declares cannot show this.
473
477
 
474
478
  Run it after every deploy of the workflow. The run record gives the repository and the pull request,
475
479
  so the command needs no argument with a team access token:
@@ -488,8 +492,11 @@ steps:
488
492
  GITHUB_TOKEN: ${{ github.token }}
489
493
  ```
490
494
 
491
- A stack named `owner/name`, or `owner/name/<folder>` for a stack in a folder, belongs to the
492
- 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.
493
500
 
494
501
  ## Data safety
495
502
 
package/lib/cli.js CHANGED
@@ -3,133 +3,109 @@ 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";
9
10
  import * as NodeServices from "@effect/platform-node/NodeServices";
11
+ import { boxSubtitle, stageDiagram, stageTree } from "@samebase/alchemy-kit/stack";
12
+ import { resourceTypeUI } from "@samebase/alchemy-kit/ui";
10
13
  //#region src/StackComment.ts
11
14
  /** The first text of the comment, which finds it again. */
12
15
  const MARKER = "<!-- samebase-stacks -->";
13
16
  /** GitHub does not proxy this host, so a new icon needs no purge of its image cache. */
14
17
  const ICONS = "https://raw.githubusercontent.com/samebase/samebase/main/packages/alchemy-convex/assets/stack-comment";
15
18
  const GITHUB_API = "https://api.github.com";
16
- /** The resources that a card shows. A row of any other type, or without `attr` from an interrupted deploy, is left out. */
17
- const Resource = Schema.Union([
18
- Schema.Struct({
19
- resourceType: Schema.Literal("Convex.Deployment"),
20
- attr: Schema.Struct({
21
- name: Schema.String,
22
- siteUrl: Schema.String
23
- })
24
- }),
25
- Schema.Struct({
26
- resourceType: Schema.Literal("Cloudflare.Worker"),
27
- attr: Schema.Struct({
28
- workerName: Schema.String,
29
- url: Schema.optional(Schema.String)
30
- })
31
- }),
32
- Schema.Struct({
33
- resourceType: Schema.Literal("Cloudflare.R2.Bucket"),
34
- attr: Schema.Struct({
35
- bucketName: Schema.String,
36
- accountId: Schema.String,
37
- jurisdiction: Schema.String
38
- })
39
- }),
40
- Schema.Struct({
41
- resourceType: Schema.Literals(["IdentityHub.Client", "IdentityHub.SharedClient"]),
42
- attr: Schema.Struct({
43
- status: Schema.Literals([
44
- "on",
45
- "off",
46
- "suspended"
47
- ]),
48
- connectors: Schema.Array(Schema.String)
49
- })
50
- })
51
- ]);
52
19
  /** The fields of the run record that a card shows. */
53
20
  const StageOutput = Schema.Struct({ [RUN_RECORD_KEY]: Schema.Struct({
54
21
  headCommit: Schema.String,
55
22
  runUrl: Schema.NullOr(Schema.String),
56
23
  recordedAt: Schema.String
57
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
+ }) });
58
31
  var StackCommentError = class extends Schema.TaggedError()("StackCommentError", { reason: Schema.String }) {
59
32
  get message() {
60
33
  return `The stack comment cannot be updated: ${this.reason}`;
61
34
  }
62
35
  };
63
- /** The cards of the stacks of `repository` that have `stage`, in name order. */
64
- 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* () {
65
42
  const state = yield* yield* State;
66
- const names = (yield* state.listStacks()).filter((name) => name === repository || name.startsWith(`${repository}/`));
67
43
  const cards = [];
68
- for (const name of names) {
44
+ for (const name of yield* state.listStacks()) {
69
45
  if (!(yield* state.listStages(name)).includes(stage)) continue;
70
46
  const request = {
71
47
  stack: name,
72
48
  stage
73
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;
74
54
  const rows = yield* Effect.forEach(yield* state.list(request), (fqn) => state.get({
75
55
  ...request,
76
56
  fqn
77
- }));
78
- const output = yield* state.getOutput(request);
57
+ }).pipe(Effect.map((row) => ({
58
+ fqn,
59
+ state: row
60
+ }))));
79
61
  cards.push({
80
62
  name,
63
+ folder: underName || Option.isNone(record) ? name.slice(repository.length + 1) : record.value.stackFile.split("/").slice(0, -1).join("/"),
81
64
  stage,
82
- resources: rows.filter(Schema.is(Resource)),
65
+ diagram: stageDiagram(rows),
83
66
  run: Schema.is(StageOutput)(output) ? output : null
84
67
  });
85
68
  }
86
69
  return cards;
87
70
  });
88
- /** A stack can create a deployment in one resource and push to it in another: a card shows it once. */
89
- const withoutRepeats = (resources) => {
90
- const deployments = /* @__PURE__ */ new Set();
91
- return resources.filter((resource) => {
92
- if (resource.resourceType !== "Convex.Deployment") return true;
93
- const repeated = deployments.has(resource.attr.name);
94
- deployments.add(resource.attr.name);
95
- return !repeated;
96
- });
97
- };
98
71
  const escapeHtml = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
99
72
  const link = (href, text) => `<a href="${escapeHtml(href)}">${text}</a>`;
100
- const named = (href, icon, alt, name) => {
101
- const image = `<img src="${ICONS}/${icon}.svg" width="16" align="absmiddle" alt="${alt}">`;
102
- return `${link(href, image)} ${link(href, escapeHtml(name))}`;
103
- };
104
73
  const hostOf = (url) => escapeHtml(new URL(url).host);
105
- /** Where a stack serves: its Convex deployment, else its first Worker with a URL. */
106
- const addressOf = (resources) => {
107
- for (const resource of resources) if (resource.resourceType === "Convex.Deployment") return resource.attr.siteUrl;
108
- for (const resource of resources) if (resource.resourceType === "Cloudflare.Worker" && resource.attr.url !== void 0) return resource.attr.url;
109
- return null;
74
+ /** The icon file of a resource type, in `ICONS`. A box of any other type has no icon. */
75
+ const ICON_FILES = /* @__PURE__ */ new Map([
76
+ ["Convex.Deployment", "convex"],
77
+ ["Cloudflare.Worker", "worker"],
78
+ ["Cloudflare.R2.Bucket", "r2"]
79
+ ]);
80
+ /** The name of a box, as a link to its dashboard page when it has one. */
81
+ const boxName = ({ name, resourceType, rows: [first] }) => {
82
+ const icon = ICON_FILES.get(resourceType);
83
+ const image = icon === void 0 ? null : `<img src="${ICONS}/${icon}.svg" width="16" align="absmiddle" alt="">`;
84
+ const text = escapeHtml(name);
85
+ const href = first.dashboard?.href;
86
+ if (href === void 0) return image === null ? text : `${image} ${text}`;
87
+ return image === null ? link(href, text) : `${link(href, image)} ${link(href, text)}`;
110
88
  };
111
- const resourceRow = (resource, address) => {
112
- switch (resource.resourceType) {
113
- case "Convex.Deployment": {
114
- const { name } = resource.attr;
115
- return named(`https://dashboard.convex.dev/d/${encodeURIComponent(name)}`, "convex", "Convex", name);
116
- }
117
- case "Cloudflare.Worker": {
118
- const { url, workerName } = resource.attr;
119
- const row = named(`https://dash.cloudflare.com/?to=/:account/workers/services/view/${encodeURIComponent(workerName)}`, "worker", "Worker", workerName);
120
- return url === void 0 || url === address ? row : `${row}<br><sub>${link(url, hostOf(url))}</sub>`;
121
- }
122
- case "Cloudflare.R2.Bucket": {
123
- const { accountId, bucketName, jurisdiction } = resource.attr;
124
- return named(`https://dash.cloudflare.com/${encodeURIComponent(accountId)}/r2/${encodeURIComponent(jurisdiction)}/buckets/${encodeURIComponent(bucketName)}`, "r2", "R2 bucket", bucketName);
125
- }
126
- case "IdentityHub.Client":
127
- case "IdentityHub.SharedClient": {
128
- const { status, connectors } = resource.attr;
129
- return status === "off" ? "Sign-in: not set up" : `Sign-in with ${connectors.join(", ")}: ${status}`;
130
- }
131
- }
89
+ /**
90
+ A box of the tree: its name with the labels of its line as code, its type and schedule, and its link
91
+ on 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
92
+ the boxes that share a resource with it. A repeated box has only its name.
93
+ */
94
+ const treeNode = (node, address) => {
95
+ const { box, labels, repeated } = node;
96
+ const title = `${boxName(box)}${labels.map((label) => ` <code>${escapeHtml(label)}</code>`).join("")}`;
97
+ if (repeated) return title;
98
+ const linkLine = box.link === null || box.link === address ? "" : `<br><sub>${link(box.link, hostOf(box.link))}</sub>`;
99
+ const below = [
100
+ ...node.children.map((child) => treeNode(child, address)),
101
+ ...box.folded.map((row) => `<sub>${escapeHtml(`${row.logicalId}, ${resourceTypeUI(row.resourceType).name}`)}</sub>`),
102
+ ...node.shared.map((text) => `<sub>${escapeHtml(text)}</sub>`)
103
+ ];
104
+ const list = below.length === 0 ? "" : `<ul>${below.map((item) => `<li>${item}</li>`).join("")}</ul>`;
105
+ return `${title} <sub>${escapeHtml(boxSubtitle(box))}</sub>${linkLine}${list}`;
132
106
  };
107
+ /** Where a stage serves: its Convex app, else the first box with a link. */
108
+ const addressOf = ({ boxes }) => (boxes.find((box) => box.resourceType === "Convex.Deployment") ?? boxes.find((box) => box.link))?.link ?? null;
133
109
  const runLine = ({ run }) => {
134
110
  if (run === null) return "";
135
111
  const { headCommit, recordedAt, runUrl } = run[RUN_RECORD_KEY];
@@ -139,20 +115,19 @@ const runLine = ({ run }) => {
139
115
  };
140
116
  const SPACER = `<div><img src="${ICONS}/spacer.svg" width="460" align="left" alt=""></div>`;
141
117
  /** `alone`: the one card of the repository. A card at the root then has no folder, as on the repository page. */
142
- const renderCard = (card, repository, alone) => {
143
- const folder = card.name.slice(repository.length + 1);
118
+ const renderCard = (card, alone) => {
119
+ const { folder } = card;
144
120
  const heading = [folder === "" && alone ? "" : `<b>${escapeHtml(folder || "/")}</b> `, `<sub>${escapeHtml(card.stage)}</sub>`].join("");
145
- const resources = withoutRepeats(card.resources);
146
- const address = addressOf(resources);
121
+ const address = addressOf(card.diagram);
147
122
  const addressLine = address === null ? "" : `<br>${link(address, hostOf(address))}`;
148
- const rows = resources.map((resource) => `<tbody><tr><td>${resourceRow(resource, address)}</td></tr></tbody>`).join("\n");
123
+ const rows = stageTree(card.diagram).map((node) => `<tbody><tr><td>${treeNode(node, address)}</td></tr></tbody>`).join("\n");
149
124
  return `<table>
150
125
  <tbody><tr><td>${SPACER}${heading}${addressLine}${runLine(card)}</td></tr></tbody>
151
126
  ${rows}
152
127
  </table>`;
153
128
  };
154
- const renderStackComment = (cards, repository) => `${MARKER}
155
- ${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")}
156
131
  `;
157
132
  const Comments = Schema.Array(Schema.Struct({
158
133
  id: Schema.Number,
@@ -199,7 +174,7 @@ const saveStackComment = (args) => Effect.gen(function* () {
199
174
  });
200
175
  /** The step of a workflow: the run record names the repository and the pull request of the run. */
201
176
  const updateStackComment = Effect.gen(function* () {
202
- const { pullRequest, repository } = yield* runRecord({
177
+ const { pullRequest, repositoryId, repositoryName: repository } = yield* runRecord({
203
178
  cwd: process.cwd(),
204
179
  env: process.env
205
180
  });
@@ -208,13 +183,14 @@ const updateStackComment = Effect.gen(function* () {
208
183
  if (token === void 0 || token === "") return yield* new StackCommentError({ reason: "GITHUB_TOKEN is not set" });
209
184
  const cards = yield* readStackCards({
210
185
  repository,
186
+ repositoryId,
211
187
  stage: `pr-${pullRequest}`
212
188
  });
213
189
  return yield* saveStackComment({
214
190
  token,
215
191
  repository,
216
192
  pullRequest,
217
- body: renderStackComment(cards, repository)
193
+ body: renderStackComment(cards)
218
194
  });
219
195
  });
220
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// It reads only the fields of the rows below, because Alchemy state holds secrets in clear text.\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\";\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 resources that a card shows. A row of any other type, or without `attr` from an interrupted deploy, is left out. */\nconst Resource = Schema.Union([\n Schema.Struct({\n resourceType: Schema.Literal(\"Convex.Deployment\"),\n attr: Schema.Struct({ name: Schema.String, siteUrl: Schema.String }),\n }),\n Schema.Struct({\n resourceType: Schema.Literal(\"Cloudflare.Worker\"),\n attr: Schema.Struct({ workerName: Schema.String, url: Schema.optional(Schema.String) }),\n }),\n Schema.Struct({\n resourceType: Schema.Literal(\"Cloudflare.R2.Bucket\"),\n attr: Schema.Struct({\n bucketName: Schema.String,\n accountId: Schema.String,\n jurisdiction: Schema.String,\n }),\n }),\n Schema.Struct({\n // A row keeps the type before 0.37.0 until its next write. Remove the old type once no saved\n // row has it.\n resourceType: Schema.Literals([\"IdentityHub.Client\", \"IdentityHub.SharedClient\"]),\n attr: Schema.Struct({\n status: Schema.Literals([\"on\", \"off\", \"suspended\"]),\n connectors: Schema.Array(Schema.String),\n }),\n }),\n]);\ntype Resource = typeof Resource.Type;\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 resources: readonly Resource[];\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 }),\n );\n const output = yield* state.getOutput(request);\n cards.push({\n name,\n stage,\n resources: rows.filter(Schema.is(Resource)),\n run: Schema.is(StageOutput)(output) ? output : null,\n });\n }\n return cards;\n });\n\n/** A stack can create a deployment in one resource and push to it in another: a card shows it once. */\nconst withoutRepeats = (resources: readonly Resource[]) => {\n const deployments = new Set<string>();\n return resources.filter((resource) => {\n if (resource.resourceType !== \"Convex.Deployment\") {\n return true;\n }\n const repeated = deployments.has(resource.attr.name);\n deployments.add(resource.attr.name);\n return !repeated;\n });\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 named = (href: string, icon: string, alt: string, name: string) => {\n const image = `<img src=\"${ICONS}/${icon}.svg\" width=\"16\" align=\"absmiddle\" alt=\"${alt}\">`;\n return `${link(href, image)} ${link(href, escapeHtml(name))}`;\n};\n\nconst hostOf = (url: string) => escapeHtml(new URL(url).host);\n\n/** Where a stack serves: its Convex deployment, else its first Worker with a URL. */\nconst addressOf = (resources: readonly Resource[]) => {\n for (const resource of resources) {\n if (resource.resourceType === \"Convex.Deployment\") {\n return resource.attr.siteUrl;\n }\n }\n for (const resource of resources) {\n if (resource.resourceType === \"Cloudflare.Worker\" && resource.attr.url !== undefined) {\n return resource.attr.url;\n }\n }\n return null;\n};\n\nconst resourceRow = (resource: Resource, address: string | null) => {\n switch (resource.resourceType) {\n case \"Convex.Deployment\": {\n const { name } = resource.attr;\n return named(\n `https://dashboard.convex.dev/d/${encodeURIComponent(name)}`,\n \"convex\",\n \"Convex\",\n name,\n );\n }\n case \"Cloudflare.Worker\": {\n const { url, workerName } = resource.attr;\n const row = named(\n `https://dash.cloudflare.com/?to=/:account/workers/services/view/${encodeURIComponent(workerName)}`,\n \"worker\",\n \"Worker\",\n workerName,\n );\n return url === undefined || url === address\n ? row\n : `${row}<br><sub>${link(url, hostOf(url))}</sub>`;\n }\n case \"Cloudflare.R2.Bucket\": {\n const { accountId, bucketName, jurisdiction } = resource.attr;\n return named(\n `https://dash.cloudflare.com/${encodeURIComponent(accountId)}/r2/${encodeURIComponent(jurisdiction)}/buckets/${encodeURIComponent(bucketName)}`,\n \"r2\",\n \"R2 bucket\",\n bucketName,\n );\n }\n case \"IdentityHub.Client\":\n case \"IdentityHub.SharedClient\": {\n const { status, connectors } = resource.attr;\n return status === \"off\"\n ? \"Sign-in: not set up\"\n : `Sign-in with ${connectors.join(\", \")}: ${status}`;\n }\n }\n};\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 resources = withoutRepeats(card.resources);\n const address = addressOf(resources);\n const addressLine = address === null ? \"\" : `<br>${link(address, hostOf(address))}`;\n const rows = resources\n .map((resource) => `<tbody><tr><td>${resourceRow(resource, 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":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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;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ACnC,OAAO,OAAO,IAAI,kBAAkB,EAAE,QAAQ,0BAA0B,CAAC;CAE3E,MAAM,QAAQ,OAAO,eAAe;EAAE;EAAY;EAAc,OAAO,MAAM;CAAc,CAAC;CAC5F,OAAO,OAAO,iBAAiB;EAC7B;EACA;EACA;EACA,MAAM,mBAAmB,KAAK;CAChC,CAAC;AACH,CAAC;;;AClTD,MAAM,EAAE,gBAAgB,UAAU;CAAE,kBAAkB;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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@samebase/alchemy-convex",
3
- "version": "0.42.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.3.0"
53
+ "@samebase/alchemy-kit": "^0.6.0"
54
54
  },
55
55
  "devDependencies": {
56
56
  "@alchemy.run/cloudflare": "2.0.0-beta.87",
@@ -2,11 +2,14 @@
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
- // It reads only the fields of the rows below, because Alchemy state holds secrets in clear text.
10
+ // The rows of a card are the boxes of `stageDiagram` from `@samebase/alchemy-kit/stack`, the model
11
+ // of Samebase's stack diagram. Alchemy state holds secrets in clear text, and that model keeps no
12
+ // secret of a row.
10
13
  //
11
14
  // GitHub keeps a fixed set of HTML in a comment and removes `style` and `class`, so every choice of
12
15
  // the markup is a fact about the sanitizer or the CSS of github.com:
@@ -22,8 +25,18 @@
22
25
  // `align="absmiddle"` is the CSS value `middle`.
23
26
  import { State } from "alchemy/State";
24
27
  import * as Effect from "effect/Effect";
28
+ import * as Option from "effect/Option";
25
29
  import * as Schema from "effect/Schema";
26
30
  import { RUN_RECORD_KEY, runRecord } from "@samebase/alchemy-kit/run-record";
31
+ import {
32
+ boxSubtitle,
33
+ stageDiagram,
34
+ stageTree,
35
+ type DiagramBox,
36
+ type StageDiagram,
37
+ type StageTreeNode,
38
+ } from "@samebase/alchemy-kit/stack";
39
+ import { resourceTypeUI } from "@samebase/alchemy-kit/ui";
27
40
 
28
41
  /** The first text of the comment, which finds it again. */
29
42
  const MARKER = "<!-- samebase-stacks -->";
@@ -34,36 +47,6 @@ const ICONS =
34
47
 
35
48
  const GITHUB_API = "https://api.github.com";
36
49
 
37
- /** The resources that a card shows. A row of any other type, or without `attr` from an interrupted deploy, is left out. */
38
- const Resource = Schema.Union([
39
- Schema.Struct({
40
- resourceType: Schema.Literal("Convex.Deployment"),
41
- attr: Schema.Struct({ name: Schema.String, siteUrl: Schema.String }),
42
- }),
43
- Schema.Struct({
44
- resourceType: Schema.Literal("Cloudflare.Worker"),
45
- attr: Schema.Struct({ workerName: Schema.String, url: Schema.optional(Schema.String) }),
46
- }),
47
- Schema.Struct({
48
- resourceType: Schema.Literal("Cloudflare.R2.Bucket"),
49
- attr: Schema.Struct({
50
- bucketName: Schema.String,
51
- accountId: Schema.String,
52
- jurisdiction: Schema.String,
53
- }),
54
- }),
55
- Schema.Struct({
56
- // A row keeps the type before 0.37.0 until its next write. Remove the old type once no saved
57
- // row has it.
58
- resourceType: Schema.Literals(["IdentityHub.Client", "IdentityHub.SharedClient"]),
59
- attr: Schema.Struct({
60
- status: Schema.Literals(["on", "off", "suspended"]),
61
- connectors: Schema.Array(Schema.String),
62
- }),
63
- }),
64
- ]);
65
- type Resource = typeof Resource.Type;
66
-
67
50
  /** The fields of the run record that a card shows. */
68
51
  const StageOutput = Schema.Struct({
69
52
  [RUN_RECORD_KEY]: Schema.Struct({
@@ -73,10 +56,21 @@ const StageOutput = Schema.Struct({
73
56
  }),
74
57
  });
75
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
+
76
68
  export interface StackCard {
77
69
  readonly name: string;
70
+ /** The folder of the stack file in the repository, "" at the root. */
71
+ readonly folder: string;
78
72
  readonly stage: string;
79
- readonly resources: readonly Resource[];
73
+ readonly diagram: StageDiagram;
80
74
  readonly run: typeof StageOutput.Type | null;
81
75
  }
82
76
 
@@ -89,46 +83,54 @@ export class StackCommentError extends Schema.TaggedError<StackCommentError>()(
89
83
  }
90
84
  }
91
85
 
92
- /** The cards of the stacks of `repository` that have `stage`, in name order. */
93
- 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
+ }) =>
94
100
  Effect.gen(function* () {
95
101
  const state = yield* yield* State;
96
- const names = (yield* state.listStacks()).filter(
97
- (name) => name === repository || name.startsWith(`${repository}/`),
98
- );
99
102
  const cards: StackCard[] = [];
100
- for (const name of names) {
103
+ for (const name of yield* state.listStacks()) {
101
104
  if (!(yield* state.listStages(name)).includes(stage)) {
102
105
  continue;
103
106
  }
104
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
+ }
105
117
  const rows = yield* Effect.forEach(yield* state.list(request), (fqn) =>
106
- state.get({ ...request, fqn }),
118
+ state.get({ ...request, fqn }).pipe(Effect.map((row) => ({ fqn, state: row }))),
107
119
  );
108
- const output = yield* state.getOutput(request);
109
120
  cards.push({
110
121
  name,
122
+ folder:
123
+ underName || Option.isNone(record)
124
+ ? name.slice(repository.length + 1)
125
+ : record.value.stackFile.split("/").slice(0, -1).join("/"),
111
126
  stage,
112
- resources: rows.filter(Schema.is(Resource)),
127
+ diagram: stageDiagram(rows),
113
128
  run: Schema.is(StageOutput)(output) ? output : null,
114
129
  });
115
130
  }
116
131
  return cards;
117
132
  });
118
133
 
119
- /** A stack can create a deployment in one resource and push to it in another: a card shows it once. */
120
- const withoutRepeats = (resources: readonly Resource[]) => {
121
- const deployments = new Set<string>();
122
- return resources.filter((resource) => {
123
- if (resource.resourceType !== "Convex.Deployment") {
124
- return true;
125
- }
126
- const repeated = deployments.has(resource.attr.name);
127
- deployments.add(resource.attr.name);
128
- return !repeated;
129
- });
130
- };
131
-
132
134
  const escapeHtml = (text: string) =>
133
135
  text
134
136
  .replaceAll("&", "&amp;")
@@ -138,70 +140,63 @@ const escapeHtml = (text: string) =>
138
140
 
139
141
  const link = (href: string, text: string) => `<a href="${escapeHtml(href)}">${text}</a>`;
140
142
 
141
- const named = (href: string, icon: string, alt: string, name: string) => {
142
- const image = `<img src="${ICONS}/${icon}.svg" width="16" align="absmiddle" alt="${alt}">`;
143
- return `${link(href, image)} ${link(href, escapeHtml(name))}`;
144
- };
145
-
146
143
  const hostOf = (url: string) => escapeHtml(new URL(url).host);
147
144
 
148
- /** Where a stack serves: its Convex deployment, else its first Worker with a URL. */
149
- const addressOf = (resources: readonly Resource[]) => {
150
- for (const resource of resources) {
151
- if (resource.resourceType === "Convex.Deployment") {
152
- return resource.attr.siteUrl;
153
- }
154
- }
155
- for (const resource of resources) {
156
- if (resource.resourceType === "Cloudflare.Worker" && resource.attr.url !== undefined) {
157
- return resource.attr.url;
158
- }
145
+ /** The icon file of a resource type, in `ICONS`. A box of any other type has no icon. */
146
+ const ICON_FILES = new Map([
147
+ ["Convex.Deployment", "convex"],
148
+ ["Cloudflare.Worker", "worker"],
149
+ ["Cloudflare.R2.Bucket", "r2"],
150
+ ]);
151
+
152
+ /** The name of a box, as a link to its dashboard page when it has one. */
153
+ const boxName = ({ name, resourceType, rows: [first] }: DiagramBox) => {
154
+ const icon = ICON_FILES.get(resourceType);
155
+ const image =
156
+ icon === undefined
157
+ ? null
158
+ : `<img src="${ICONS}/${icon}.svg" width="16" align="absmiddle" alt="">`;
159
+ const text = escapeHtml(name);
160
+ const href = first.dashboard?.href;
161
+ if (href === undefined) {
162
+ return image === null ? text : `${image} ${text}`;
159
163
  }
160
- return null;
164
+ return image === null ? link(href, text) : `${link(href, image)} ${link(href, text)}`;
161
165
  };
162
166
 
163
- const resourceRow = (resource: Resource, address: string | null) => {
164
- switch (resource.resourceType) {
165
- case "Convex.Deployment": {
166
- const { name } = resource.attr;
167
- return named(
168
- `https://dashboard.convex.dev/d/${encodeURIComponent(name)}`,
169
- "convex",
170
- "Convex",
171
- name,
172
- );
173
- }
174
- case "Cloudflare.Worker": {
175
- const { url, workerName } = resource.attr;
176
- const row = named(
177
- `https://dash.cloudflare.com/?to=/:account/workers/services/view/${encodeURIComponent(workerName)}`,
178
- "worker",
179
- "Worker",
180
- workerName,
181
- );
182
- return url === undefined || url === address
183
- ? row
184
- : `${row}<br><sub>${link(url, hostOf(url))}</sub>`;
185
- }
186
- case "Cloudflare.R2.Bucket": {
187
- const { accountId, bucketName, jurisdiction } = resource.attr;
188
- return named(
189
- `https://dash.cloudflare.com/${encodeURIComponent(accountId)}/r2/${encodeURIComponent(jurisdiction)}/buckets/${encodeURIComponent(bucketName)}`,
190
- "r2",
191
- "R2 bucket",
192
- bucketName,
193
- );
194
- }
195
- case "IdentityHub.Client":
196
- case "IdentityHub.SharedClient": {
197
- const { status, connectors } = resource.attr;
198
- return status === "off"
199
- ? "Sign-in: not set up"
200
- : `Sign-in with ${connectors.join(", ")}: ${status}`;
201
- }
167
+ /**
168
+ A box of the tree: its name with the labels of its line as code, its type and schedule, and its link
169
+ on 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
170
+ the boxes that share a resource with it. A repeated box has only its name.
171
+ */
172
+ const treeNode = (node: StageTreeNode, address: string | null): string => {
173
+ const { box, labels, repeated } = node;
174
+ const title = `${boxName(box)}${labels.map((label) => ` <code>${escapeHtml(label)}</code>`).join("")}`;
175
+ if (repeated) {
176
+ return title;
202
177
  }
178
+ const linkLine =
179
+ box.link === null || box.link === address
180
+ ? ""
181
+ : `<br><sub>${link(box.link, hostOf(box.link))}</sub>`;
182
+ const below = [
183
+ ...node.children.map((child) => treeNode(child, address)),
184
+ ...box.folded.map(
185
+ (row) =>
186
+ `<sub>${escapeHtml(`${row.logicalId}, ${resourceTypeUI(row.resourceType).name}`)}</sub>`,
187
+ ),
188
+ ...node.shared.map((text) => `<sub>${escapeHtml(text)}</sub>`),
189
+ ];
190
+ const list =
191
+ below.length === 0 ? "" : `<ul>${below.map((item) => `<li>${item}</li>`).join("")}</ul>`;
192
+ return `${title} <sub>${escapeHtml(boxSubtitle(box))}</sub>${linkLine}${list}`;
203
193
  };
204
194
 
195
+ /** Where a stage serves: its Convex app, else the first box with a link. */
196
+ const addressOf = ({ boxes }: StageDiagram) =>
197
+ (boxes.find((box) => box.resourceType === "Convex.Deployment") ?? boxes.find((box) => box.link))
198
+ ?.link ?? null;
199
+
205
200
  const runLine = ({ run }: StackCard) => {
206
201
  if (run === null) {
207
202
  return "";
@@ -215,17 +210,16 @@ const runLine = ({ run }: StackCard) => {
215
210
  const SPACER = `<div><img src="${ICONS}/spacer.svg" width="460" align="left" alt=""></div>`;
216
211
 
217
212
  /** `alone`: the one card of the repository. A card at the root then has no folder, as on the repository page. */
218
- const renderCard = (card: StackCard, repository: string, alone: boolean) => {
219
- const folder = card.name.slice(repository.length + 1);
213
+ const renderCard = (card: StackCard, alone: boolean) => {
214
+ const { folder } = card;
220
215
  const heading = [
221
216
  folder === "" && alone ? "" : `<b>${escapeHtml(folder || "/")}</b> `,
222
217
  `<sub>${escapeHtml(card.stage)}</sub>`,
223
218
  ].join("");
224
- const resources = withoutRepeats(card.resources);
225
- const address = addressOf(resources);
219
+ const address = addressOf(card.diagram);
226
220
  const addressLine = address === null ? "" : `<br>${link(address, hostOf(address))}`;
227
- const rows = resources
228
- .map((resource) => `<tbody><tr><td>${resourceRow(resource, address)}</td></tr></tbody>`)
221
+ const rows = stageTree(card.diagram)
222
+ .map((node) => `<tbody><tr><td>${treeNode(node, address)}</td></tr></tbody>`)
229
223
  .join("\n");
230
224
  return `<table>
231
225
  <tbody><tr><td>${SPACER}${heading}${addressLine}${runLine(card)}</td></tr></tbody>
@@ -233,8 +227,8 @@ ${rows}
233
227
  </table>`;
234
228
  };
235
229
 
236
- export const renderStackComment = (cards: readonly StackCard[], repository: string) => `${MARKER}
237
- ${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")}
238
232
  `;
239
233
 
240
234
  const Comments = Schema.Array(Schema.Struct({ id: Schema.Number, body: Schema.String }));
@@ -306,7 +300,11 @@ export const saveStackComment = (args: {
306
300
 
307
301
  /** The step of a workflow: the run record names the repository and the pull request of the run. */
308
302
  export const updateStackComment = Effect.gen(function* () {
309
- 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 });
310
308
  if (pullRequest === null) {
311
309
  return yield* new StackCommentError({ reason: "this run has no pull request" });
312
310
  }
@@ -314,11 +312,11 @@ export const updateStackComment = Effect.gen(function* () {
314
312
  if (token === undefined || token === "") {
315
313
  return yield* new StackCommentError({ reason: "GITHUB_TOKEN is not set" });
316
314
  }
317
- const cards = yield* readStackCards({ repository, stage: `pr-${pullRequest}` });
315
+ const cards = yield* readStackCards({ repository, repositoryId, stage: `pr-${pullRequest}` });
318
316
  return yield* saveStackComment({
319
317
  token,
320
318
  repository,
321
319
  pullRequest,
322
- body: renderStackComment(cards, repository),
320
+ body: renderStackComment(cards),
323
321
  });
324
322
  });