@samebase/alchemy-convex 0.42.0 → 0.43.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 +5 -3
- package/lib/cli.js +42 -81
- package/lib/cli.js.map +1 -1
- package/package.json +2 -2
- package/src/StackComment.ts +67 -107
package/README.md
CHANGED
|
@@ -467,9 +467,11 @@ deletes the development client and keeps the deployment.
|
|
|
467
467
|
## Pull request comment
|
|
468
468
|
|
|
469
469
|
`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,
|
|
471
|
-
|
|
472
|
-
|
|
470
|
+
stack of the repository at the stage `pr-<number>`: the folder, the address, the last run, and a row
|
|
471
|
+
for each main resource, with its type, its link and its schedule, each under the resource that uses
|
|
472
|
+
it. The rows come from `stageDiagram` of `@samebase/alchemy-kit/stack`, the same model as Samebase's
|
|
473
|
+
stack diagram, so a project or a hub client shows under its deployment and not as a row of its own.
|
|
474
|
+
A stack sees only itself, so a comment that a stack declares cannot show this.
|
|
473
475
|
|
|
474
476
|
Run it after every deploy of the workflow. The run record gives the repository and the pull request,
|
|
475
477
|
so the command needs no argument with a team access token:
|
package/lib/cli.js
CHANGED
|
@@ -7,48 +7,14 @@ import { parseArgs } from "node:util";
|
|
|
7
7
|
import { State } from "alchemy/State";
|
|
8
8
|
import { RUN_RECORD_KEY, runRecord } from "@samebase/alchemy-kit/run-record";
|
|
9
9
|
import * as NodeServices from "@effect/platform-node/NodeServices";
|
|
10
|
+
import { boxSubtitle, stageDiagram, stageTree } from "@samebase/alchemy-kit/stack";
|
|
11
|
+
import { resourceTypeUI } from "@samebase/alchemy-kit/ui";
|
|
10
12
|
//#region src/StackComment.ts
|
|
11
13
|
/** The first text of the comment, which finds it again. */
|
|
12
14
|
const MARKER = "<!-- samebase-stacks -->";
|
|
13
15
|
/** GitHub does not proxy this host, so a new icon needs no purge of its image cache. */
|
|
14
16
|
const ICONS = "https://raw.githubusercontent.com/samebase/samebase/main/packages/alchemy-convex/assets/stack-comment";
|
|
15
17
|
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
18
|
/** The fields of the run record that a card shows. */
|
|
53
19
|
const StageOutput = Schema.Struct({ [RUN_RECORD_KEY]: Schema.Struct({
|
|
54
20
|
headCommit: Schema.String,
|
|
@@ -74,62 +40,58 @@ const readStackCards = ({ repository, stage }) => Effect.gen(function* () {
|
|
|
74
40
|
const rows = yield* Effect.forEach(yield* state.list(request), (fqn) => state.get({
|
|
75
41
|
...request,
|
|
76
42
|
fqn
|
|
77
|
-
}))
|
|
43
|
+
}).pipe(Effect.map((row) => ({
|
|
44
|
+
fqn,
|
|
45
|
+
state: row
|
|
46
|
+
}))));
|
|
78
47
|
const output = yield* state.getOutput(request);
|
|
79
48
|
cards.push({
|
|
80
49
|
name,
|
|
81
50
|
stage,
|
|
82
|
-
|
|
51
|
+
diagram: stageDiagram(rows),
|
|
83
52
|
run: Schema.is(StageOutput)(output) ? output : null
|
|
84
53
|
});
|
|
85
54
|
}
|
|
86
55
|
return cards;
|
|
87
56
|
});
|
|
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
57
|
const escapeHtml = (text) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);
|
|
99
58
|
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
59
|
const hostOf = (url) => escapeHtml(new URL(url).host);
|
|
105
|
-
/**
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
60
|
+
/** The icon file of a resource type, in `ICONS`. A box of any other type has no icon. */
|
|
61
|
+
const ICON_FILES = /* @__PURE__ */ new Map([
|
|
62
|
+
["Convex.Deployment", "convex"],
|
|
63
|
+
["Cloudflare.Worker", "worker"],
|
|
64
|
+
["Cloudflare.R2.Bucket", "r2"]
|
|
65
|
+
]);
|
|
66
|
+
/** The name of a box, as a link to its dashboard page when it has one. */
|
|
67
|
+
const boxName = ({ name, resourceType, rows: [first] }) => {
|
|
68
|
+
const icon = ICON_FILES.get(resourceType);
|
|
69
|
+
const image = icon === void 0 ? null : `<img src="${ICONS}/${icon}.svg" width="16" align="absmiddle" alt="">`;
|
|
70
|
+
const text = escapeHtml(name);
|
|
71
|
+
const href = first.dashboard?.href;
|
|
72
|
+
if (href === void 0) return image === null ? text : `${image} ${text}`;
|
|
73
|
+
return image === null ? link(href, text) : `${link(href, image)} ${link(href, text)}`;
|
|
110
74
|
};
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const { status, connectors } = resource.attr;
|
|
129
|
-
return status === "off" ? "Sign-in: not set up" : `Sign-in with ${connectors.join(", ")}: ${status}`;
|
|
130
|
-
}
|
|
131
|
-
}
|
|
75
|
+
/**
|
|
76
|
+
A box of the tree: its name with the labels of its line as code, its type and schedule, and its link
|
|
77
|
+
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
|
|
78
|
+
the boxes that share a resource with it. A repeated box has only its name.
|
|
79
|
+
*/
|
|
80
|
+
const treeNode = (node, address) => {
|
|
81
|
+
const { box, labels, repeated } = node;
|
|
82
|
+
const title = `${boxName(box)}${labels.map((label) => ` <code>${escapeHtml(label)}</code>`).join("")}`;
|
|
83
|
+
if (repeated) return title;
|
|
84
|
+
const linkLine = box.link === null || box.link === address ? "" : `<br><sub>${link(box.link, hostOf(box.link))}</sub>`;
|
|
85
|
+
const below = [
|
|
86
|
+
...node.children.map((child) => treeNode(child, address)),
|
|
87
|
+
...box.folded.map((row) => `<sub>${escapeHtml(`${row.logicalId}, ${resourceTypeUI(row.resourceType).name}`)}</sub>`),
|
|
88
|
+
...node.shared.map((text) => `<sub>${escapeHtml(text)}</sub>`)
|
|
89
|
+
];
|
|
90
|
+
const list = below.length === 0 ? "" : `<ul>${below.map((item) => `<li>${item}</li>`).join("")}</ul>`;
|
|
91
|
+
return `${title} <sub>${escapeHtml(boxSubtitle(box))}</sub>${linkLine}${list}`;
|
|
132
92
|
};
|
|
93
|
+
/** Where a stage serves: its Convex app, else the first box with a link. */
|
|
94
|
+
const addressOf = ({ boxes }) => (boxes.find((box) => box.resourceType === "Convex.Deployment") ?? boxes.find((box) => box.link))?.link ?? null;
|
|
133
95
|
const runLine = ({ run }) => {
|
|
134
96
|
if (run === null) return "";
|
|
135
97
|
const { headCommit, recordedAt, runUrl } = run[RUN_RECORD_KEY];
|
|
@@ -142,10 +104,9 @@ const SPACER = `<div><img src="${ICONS}/spacer.svg" width="460" align="left" alt
|
|
|
142
104
|
const renderCard = (card, repository, alone) => {
|
|
143
105
|
const folder = card.name.slice(repository.length + 1);
|
|
144
106
|
const heading = [folder === "" && alone ? "" : `<b>${escapeHtml(folder || "/")}</b> `, `<sub>${escapeHtml(card.stage)}</sub>`].join("");
|
|
145
|
-
const
|
|
146
|
-
const address = addressOf(resources);
|
|
107
|
+
const address = addressOf(card.diagram);
|
|
147
108
|
const addressLine = address === null ? "" : `<br>${link(address, hostOf(address))}`;
|
|
148
|
-
const rows =
|
|
109
|
+
const rows = stageTree(card.diagram).map((node) => `<tbody><tr><td>${treeNode(node, address)}</td></tr></tbody>`).join("\n");
|
|
149
110
|
return `<table>
|
|
150
111
|
<tbody><tr><td>${SPACER}${heading}${addressLine}${runLine(card)}</td></tr></tbody>
|
|
151
112
|
${rows}
|
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(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\");\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":";;;;;;;;;;;AA4BA,MAAM,SAAS;;AAGf,MAAM,QACJ;AAEF,MAAM,aAAa;;AAGnB,MAAM,WAAW,OAAO,MAAM;CAC5B,OAAO,OAAO;EACZ,cAAc,OAAO,QAAQ,mBAAmB;EAChD,MAAM,OAAO,OAAO;GAAE,MAAM,OAAO;GAAQ,SAAS,OAAO;EAAO,CAAC;CACrE,CAAC;CACD,OAAO,OAAO;EACZ,cAAc,OAAO,QAAQ,mBAAmB;EACh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hF,MAAM,QAAQ,QAAQ,IAAI;CAC1B,IAAI,UAAU,KAAA,KAAa,UAAU,IACnC,OAAO,OAAO,IAAI,kBAAkB,EAAE,QAAQ,0BAA0B,CAAC;CAE3E,MAAM,QAAQ,OAAO,eAAe;EAAE;EAAY,OAAO,MAAM;CAAc,CAAC;CAC9E,OAAO,OAAO,iBAAiB;EAC7B;EACA;EACA;EACA,MAAM,mBAAmB,OAAO,UAAU;CAC5C,CAAC;AACH,CAAC;;;ACpTD,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"}
|
|
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(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\");\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;;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;AASD,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;;AAGA,MAAa,kBAAkB,EAAE,YAAY,YAC3C,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,OAAO;CAC5B,MAAM,SAAS,OAAO,MAAM,WAAW,EAAA,CAAG,QACvC,SAAS,SAAS,cAAc,KAAK,WAAW,GAAG,WAAW,EAAE,CACnE;CACA,MAAM,QAAqB,CAAC;CAC5B,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,EAAE,OAAO,MAAM,WAAW,IAAI,EAAA,CAAG,SAAS,KAAK,GACjD;EAEF,MAAM,UAAU;GAAE,OAAO;GAAM;EAAM;EACrC,MAAM,OAAO,OAAO,OAAO,QAAQ,OAAO,MAAM,KAAK,OAAO,IAAI,QAC9D,MAAM,IAAI;GAAE,GAAG;GAAS;EAAI,CAAC,CAAC,CAAC,KAAK,OAAO,KAAK,SAAS;GAAE;GAAK,OAAO;EAAI,EAAE,CAAC,CAChF;EACA,MAAM,SAAS,OAAO,MAAM,UAAU,OAAO;EAC7C,MAAM,KAAK;GACT;GACA;GACA,SAAS,aAAa,IAAI;GAC1B,KAAK,OAAO,GAAG,WAAW,C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AO,eAAe;EAAE;EAAY,OAAO,MAAM;CAAc,CAAC;CAC9E,OAAO,OAAO,iBAAiB;EAC7B;EACA;EACA;EACA,MAAM,mBAAmB,OAAO,UAAU;CAC5C,CAAC;AACH,CAAC;;;AC5QD,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.
|
|
3
|
+
"version": "0.43.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.
|
|
53
|
+
"@samebase/alchemy-kit": "^0.5.0"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@alchemy.run/cloudflare": "2.0.0-beta.87",
|
package/src/StackComment.ts
CHANGED
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
// `owner/name/<folder>` that has the stage `pr-<number>`. A stack without that stage has no card. A
|
|
7
7
|
// run replaces the whole body, so the last run shows the newest state.
|
|
8
8
|
//
|
|
9
|
-
//
|
|
9
|
+
// The rows of a card are the boxes of `stageDiagram` from `@samebase/alchemy-kit/stack`, the model
|
|
10
|
+
// of Samebase's stack diagram. Alchemy state holds secrets in clear text, and that model keeps no
|
|
11
|
+
// secret of a row.
|
|
10
12
|
//
|
|
11
13
|
// GitHub keeps a fixed set of HTML in a comment and removes `style` and `class`, so every choice of
|
|
12
14
|
// the markup is a fact about the sanitizer or the CSS of github.com:
|
|
@@ -24,6 +26,15 @@ import { State } from "alchemy/State";
|
|
|
24
26
|
import * as Effect from "effect/Effect";
|
|
25
27
|
import * as Schema from "effect/Schema";
|
|
26
28
|
import { RUN_RECORD_KEY, runRecord } from "@samebase/alchemy-kit/run-record";
|
|
29
|
+
import {
|
|
30
|
+
boxSubtitle,
|
|
31
|
+
stageDiagram,
|
|
32
|
+
stageTree,
|
|
33
|
+
type DiagramBox,
|
|
34
|
+
type StageDiagram,
|
|
35
|
+
type StageTreeNode,
|
|
36
|
+
} from "@samebase/alchemy-kit/stack";
|
|
37
|
+
import { resourceTypeUI } from "@samebase/alchemy-kit/ui";
|
|
27
38
|
|
|
28
39
|
/** The first text of the comment, which finds it again. */
|
|
29
40
|
const MARKER = "<!-- samebase-stacks -->";
|
|
@@ -34,36 +45,6 @@ const ICONS =
|
|
|
34
45
|
|
|
35
46
|
const GITHUB_API = "https://api.github.com";
|
|
36
47
|
|
|
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
48
|
/** The fields of the run record that a card shows. */
|
|
68
49
|
const StageOutput = Schema.Struct({
|
|
69
50
|
[RUN_RECORD_KEY]: Schema.Struct({
|
|
@@ -76,7 +57,7 @@ const StageOutput = Schema.Struct({
|
|
|
76
57
|
export interface StackCard {
|
|
77
58
|
readonly name: string;
|
|
78
59
|
readonly stage: string;
|
|
79
|
-
readonly
|
|
60
|
+
readonly diagram: StageDiagram;
|
|
80
61
|
readonly run: typeof StageOutput.Type | null;
|
|
81
62
|
}
|
|
82
63
|
|
|
@@ -103,32 +84,19 @@ export const readStackCards = ({ repository, stage }: { repository: string; stag
|
|
|
103
84
|
}
|
|
104
85
|
const request = { stack: name, stage };
|
|
105
86
|
const rows = yield* Effect.forEach(yield* state.list(request), (fqn) =>
|
|
106
|
-
state.get({ ...request, fqn }),
|
|
87
|
+
state.get({ ...request, fqn }).pipe(Effect.map((row) => ({ fqn, state: row }))),
|
|
107
88
|
);
|
|
108
89
|
const output = yield* state.getOutput(request);
|
|
109
90
|
cards.push({
|
|
110
91
|
name,
|
|
111
92
|
stage,
|
|
112
|
-
|
|
93
|
+
diagram: stageDiagram(rows),
|
|
113
94
|
run: Schema.is(StageOutput)(output) ? output : null,
|
|
114
95
|
});
|
|
115
96
|
}
|
|
116
97
|
return cards;
|
|
117
98
|
});
|
|
118
99
|
|
|
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
100
|
const escapeHtml = (text: string) =>
|
|
133
101
|
text
|
|
134
102
|
.replaceAll("&", "&")
|
|
@@ -138,70 +106,63 @@ const escapeHtml = (text: string) =>
|
|
|
138
106
|
|
|
139
107
|
const link = (href: string, text: string) => `<a href="${escapeHtml(href)}">${text}</a>`;
|
|
140
108
|
|
|
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
109
|
const hostOf = (url: string) => escapeHtml(new URL(url).host);
|
|
147
110
|
|
|
148
|
-
/**
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
111
|
+
/** The icon file of a resource type, in `ICONS`. A box of any other type has no icon. */
|
|
112
|
+
const ICON_FILES = new Map([
|
|
113
|
+
["Convex.Deployment", "convex"],
|
|
114
|
+
["Cloudflare.Worker", "worker"],
|
|
115
|
+
["Cloudflare.R2.Bucket", "r2"],
|
|
116
|
+
]);
|
|
117
|
+
|
|
118
|
+
/** The name of a box, as a link to its dashboard page when it has one. */
|
|
119
|
+
const boxName = ({ name, resourceType, rows: [first] }: DiagramBox) => {
|
|
120
|
+
const icon = ICON_FILES.get(resourceType);
|
|
121
|
+
const image =
|
|
122
|
+
icon === undefined
|
|
123
|
+
? null
|
|
124
|
+
: `<img src="${ICONS}/${icon}.svg" width="16" align="absmiddle" alt="">`;
|
|
125
|
+
const text = escapeHtml(name);
|
|
126
|
+
const href = first.dashboard?.href;
|
|
127
|
+
if (href === undefined) {
|
|
128
|
+
return image === null ? text : `${image} ${text}`;
|
|
159
129
|
}
|
|
160
|
-
return null
|
|
130
|
+
return image === null ? link(href, text) : `${link(href, image)} ${link(href, text)}`;
|
|
161
131
|
};
|
|
162
132
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
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
|
-
}
|
|
133
|
+
/**
|
|
134
|
+
A box of the tree: its name with the labels of its line as code, its type and schedule, and its link
|
|
135
|
+
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
|
|
136
|
+
the boxes that share a resource with it. A repeated box has only its name.
|
|
137
|
+
*/
|
|
138
|
+
const treeNode = (node: StageTreeNode, address: string | null): string => {
|
|
139
|
+
const { box, labels, repeated } = node;
|
|
140
|
+
const title = `${boxName(box)}${labels.map((label) => ` <code>${escapeHtml(label)}</code>`).join("")}`;
|
|
141
|
+
if (repeated) {
|
|
142
|
+
return title;
|
|
202
143
|
}
|
|
144
|
+
const linkLine =
|
|
145
|
+
box.link === null || box.link === address
|
|
146
|
+
? ""
|
|
147
|
+
: `<br><sub>${link(box.link, hostOf(box.link))}</sub>`;
|
|
148
|
+
const below = [
|
|
149
|
+
...node.children.map((child) => treeNode(child, address)),
|
|
150
|
+
...box.folded.map(
|
|
151
|
+
(row) =>
|
|
152
|
+
`<sub>${escapeHtml(`${row.logicalId}, ${resourceTypeUI(row.resourceType).name}`)}</sub>`,
|
|
153
|
+
),
|
|
154
|
+
...node.shared.map((text) => `<sub>${escapeHtml(text)}</sub>`),
|
|
155
|
+
];
|
|
156
|
+
const list =
|
|
157
|
+
below.length === 0 ? "" : `<ul>${below.map((item) => `<li>${item}</li>`).join("")}</ul>`;
|
|
158
|
+
return `${title} <sub>${escapeHtml(boxSubtitle(box))}</sub>${linkLine}${list}`;
|
|
203
159
|
};
|
|
204
160
|
|
|
161
|
+
/** Where a stage serves: its Convex app, else the first box with a link. */
|
|
162
|
+
const addressOf = ({ boxes }: StageDiagram) =>
|
|
163
|
+
(boxes.find((box) => box.resourceType === "Convex.Deployment") ?? boxes.find((box) => box.link))
|
|
164
|
+
?.link ?? null;
|
|
165
|
+
|
|
205
166
|
const runLine = ({ run }: StackCard) => {
|
|
206
167
|
if (run === null) {
|
|
207
168
|
return "";
|
|
@@ -221,11 +182,10 @@ const renderCard = (card: StackCard, repository: string, alone: boolean) => {
|
|
|
221
182
|
folder === "" && alone ? "" : `<b>${escapeHtml(folder || "/")}</b> `,
|
|
222
183
|
`<sub>${escapeHtml(card.stage)}</sub>`,
|
|
223
184
|
].join("");
|
|
224
|
-
const
|
|
225
|
-
const address = addressOf(resources);
|
|
185
|
+
const address = addressOf(card.diagram);
|
|
226
186
|
const addressLine = address === null ? "" : `<br>${link(address, hostOf(address))}`;
|
|
227
|
-
const rows =
|
|
228
|
-
.map((
|
|
187
|
+
const rows = stageTree(card.diagram)
|
|
188
|
+
.map((node) => `<tbody><tr><td>${treeNode(node, address)}</td></tr></tbody>`)
|
|
229
189
|
.join("\n");
|
|
230
190
|
return `<table>
|
|
231
191
|
<tbody><tr><td>${SPACER}${heading}${addressLine}${runLine(card)}</td></tr></tbody>
|