| 1 | // fixture pages for the `meta` tab of the debugger: every card that a link can |
| 2 | // become, so that the tab can be checked against what it should draw. |
| 3 | // |
| 4 | // node --experimental-vm-modules lib/examples/meta-cards.ts serve |
| 5 | // node --experimental-vm-modules lib/examples/meta-cards.ts shots [name...] |
| 6 | // node --experimental-vm-modules lib/examples/meta-cards.ts discord [name...] |
| 7 | // node --experimental-vm-modules lib/examples/meta-cards.ts compare name... |
| 8 | // |
| 9 | // `serve` lists the pages at http://localhost:3456. `shots` drives chrome (the |
| 10 | // repo's playwright) over them and writes the `meta` tab of each to |
| 11 | // `.clover/meta-cards/<name>.png`. `discord` posts the component embeds as |
| 12 | // messages to the webhook in `TEST_DISCORD_WEBHOOK`, to see them in real Discord, |
| 13 | // and captures the chrome window that has Discord open after each (macOS, with |
| 14 | // screen recording). `compare` lays that capture beside the tab, for a |
| 15 | // `shots --width=620 --scale=2` of the same names. |
| 16 | const port = 3456; |
| 17 | const base = new URL(`http://localhost:${port}/`); |
| 18 | const template: meta.Template = { base }; |
| 19 | const outDir = ".clover/meta-cards"; |
| 20 | |
| 21 | // -- images: solid, striped, with a circle that shows how it was cropped -- |
| 22 | |
| 23 | const hues = [[59, 130, 246], [239, 68, 68], [34, 197, 94], [234, 179, 8], [168, 85, 247], [236, 72, 153]] as const; |
| 24 | |
| 25 | function png(width: number, height: number, [r, g, b]: readonly [number, number, number]): Buffer { |
| 26 | const stride = 1 + width * 3; |
| 27 | const raw = Buffer.alloc(stride * height); |
| 28 | const radius = Math.min(width, height) / 3; |
| 29 | for (let y = 0; y < height; y++) { |
| 30 | for (let x = 0; x < width; x++) { |
| 31 | const inside = Math.hypot(x - width / 2, y - height / 2) < radius; |
| 32 | const shade = inside ? 255 : ((x + y) >> 5) & 1 ? 0.75 : 1; |
| 33 | raw.set(inside ? [255, 255, 255] : [r * shade, g * shade, b * shade], y * stride + 1 + x * 3); |
| 34 | } |
| 35 | } |
| 36 | const chunk = (type: string, data: Buffer) => { |
| 37 | const out = Buffer.alloc(12 + data.length); |
| 38 | out.writeUInt32BE(data.length, 0); |
| 39 | out.write(type, 4, "latin1"); |
| 40 | data.copy(out, 8); |
| 41 | out.writeUInt32BE(zlib.crc32(out.subarray(4, 8 + data.length)), 8 + data.length); |
| 42 | return out; |
| 43 | }; |
| 44 | const header = Buffer.alloc(13); |
| 45 | header.writeUInt32BE(width, 0); |
| 46 | header.writeUInt32BE(height, 4); |
| 47 | header.set([8, 2, 0, 0, 0], 8); |
| 48 | return Buffer.concat([ |
| 49 | Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), |
| 50 | chunk("IHDR", header), |
| 51 | chunk("IDAT", zlib.deflateSync(raw)), |
| 52 | chunk("IEND", Buffer.alloc(0)), |
| 53 | ]); |
| 54 | } |
| 55 | |
| 56 | /** `/img/1200x630-2.png`: the size, and which color of the six */ |
| 57 | const image = (width: number, height: number, hue = 0) => `/img/${width}x${height}-${hue % hues.length}.png`; |
| 58 | |
| 59 | // -- fixtures -- |
| 60 | |
| 61 | const section = (text: string, accessory: meta.DiscordComponent): meta.DiscordComponent => ({ |
| 62 | type: "section", |
| 63 | components: [{ type: "text", content: text }], |
| 64 | accessory, |
| 65 | }); |
| 66 | const container = (...components: meta.DiscordComponent[]): meta.DiscordComponent => ({ |
| 67 | type: "container", |
| 68 | components, |
| 69 | }); |
| 70 | const text = (content: string): meta.DiscordComponent => ({ type: "text", content }); |
| 71 | const gallery = (count: number, size: readonly [number, number] = [600, 400]): meta.DiscordComponent => ({ |
| 72 | type: "gallery", |
| 73 | items: Array.from( |
| 74 | { length: count }, |
| 75 | (_, i) => ({ media: { url: image(size[0], size[1], i) }, description: `item ${i + 1}` }), |
| 76 | ), |
| 77 | }); |
| 78 | const link = (label: string, extra: object = {}): meta.DiscordComponent => ({ |
| 79 | type: "button", |
| 80 | url: "/somewhere", |
| 81 | label, |
| 82 | ...extra, |
| 83 | }); |
| 84 | |
| 85 | /** a page that has the component embed, and the Open Graph tags that it falls back to */ |
| 86 | const embed = (discord: meta.DiscordComponent): meta.Meta => ({ |
| 87 | title: "Component embed", |
| 88 | description: "falls back to this", |
| 89 | embed: { thumbnail: image(1200, 630), siteTitle: "fixtures" }, |
| 90 | discord, |
| 91 | }); |
| 92 | |
| 93 | /** what `c-linked` links to, rather than holds */ |
| 94 | const linked = container(text("linked json")); |
| 95 | |
| 96 | const cards: Record<string, meta.Meta> = { |
| 97 | "c-markdown": embed(container(text([ |
| 98 | "# Heading one", |
| 99 | "## Heading two", |
| 100 | "### Heading three", |
| 101 | "-# subtext", |
| 102 | "**bold** *italic* __underline__ ~~strike~~ ***both*** ||spoiler|| `code`", |
| 103 | "[a masked link](https://example.com) and https://example.com/bare", |
| 104 | "> a quote", |
| 105 | "- one", |
| 106 | "- two", |
| 107 | "1. first", |
| 108 | "```", |
| 109 | "code block", |
| 110 | " indented", |
| 111 | "```", |
| 112 | "the end", |
| 113 | ].join("\n")))), |
| 114 | "c-section-thumbnail": embed(container(section( |
| 115 | "# Patch notes\nTwo lines beside a thumbnail.", |
| 116 | { type: "thumbnail", media: { url: image(400, 400) }, description: "alt text" }, |
| 117 | ))), |
| 118 | "c-section-button": embed(container(section("Text beside a button.", link("Open")))), |
| 119 | "c-section-spoiler": embed(container( |
| 120 | section("The thumbnail is a spoiler.", { type: "thumbnail", media: { url: image(400, 400, 1) }, spoiler: true }), |
| 121 | )), |
| 122 | ...Object.fromEntries( |
| 123 | Array.from( |
| 124 | { length: 10 }, |
| 125 | (_, i) => [`c-gallery-${i + 1}`, embed(container(text(`${i + 1} items`), gallery(i + 1)))], |
| 126 | ), |
| 127 | ), |
| 128 | "c-gallery-tall": embed(container(gallery(3, [400, 800]))), |
| 129 | "c-gallery-wide": embed(container(gallery(2, [1600, 400]))), |
| 130 | "c-separators": embed(container( |
| 131 | text("small"), |
| 132 | { type: "separator" }, |
| 133 | text("large"), |
| 134 | { type: "separator", spacing: 2 }, |
| 135 | text("no divider"), |
| 136 | { type: "separator", divider: false }, |
| 137 | text("end"), |
| 138 | )), |
| 139 | "c-buttons": embed(container( |
| 140 | text("A row of buttons"), |
| 141 | { |
| 142 | type: "row", |
| 143 | components: [ |
| 144 | link("Store"), |
| 145 | link("Community", { emoji: { name: "🎮" } }), |
| 146 | link("", { emoji: { name: "⭐" } }), |
| 147 | link("Disabled", { disabled: true }), |
| 148 | link("A button with a label that is quite long indeed"), |
| 149 | ], |
| 150 | }, |
| 151 | )), |
| 152 | "c-spoiler": embed({ type: "container", spoiler: true, components: [text("a spoiler container"), gallery(2)] }), |
| 153 | "c-accent-none": embed(container(text("no accent"))), |
| 154 | "c-accent-red": embed({ type: "container", accent_color: 0xff0000, components: [text("red")] }), |
| 155 | "c-accent-black": embed({ type: "container", accent_color: 0, components: [text("black")] }), |
| 156 | "c-docs": embed({ |
| 157 | type: "container", |
| 158 | accent_color: 1752220, |
| 159 | components: [ |
| 160 | section("# **[New version out!](https://example.com/v2)**\nThe dungeon is deceptively tougher.", link("Open")), |
| 161 | gallery(3), |
| 162 | text("*Screenshots of new content*"), |
| 163 | { type: "separator", spacing: 1 }, |
| 164 | { type: "row", components: [link("Store"), link("Community"), link("Patch Notes")] }, |
| 165 | { type: "separator" }, |
| 166 | section("## **[??????](https://example.com/me)**\nWho could this be?", { |
| 167 | type: "thumbnail", |
| 168 | media: { url: image(400, 400, 4) }, |
| 169 | spoiler: true, |
| 170 | }), |
| 171 | ], |
| 172 | }), |
| 173 | "c-long": embed(container(text("a long line without any breaks ".repeat(70)))), |
| 174 | "c-linked": { ...embed(linked), discord: "/embeds/linked.json" }, |
| 175 | |
| 176 | // what Discord leaves out, and falls back from |
| 177 | "bad-nested-container": embed(container({ type: "container", components: [text("inner")] })), |
| 178 | "bad-button-key": embed(container({ type: "row", components: [link("x", { custom_id: "nope" })] })), |
| 179 | "bad-forty-one": embed(container(...Array.from({ length: 40 }, () => text("x")))), |
| 180 | "bad-gallery-11": embed(container(gallery(6), gallery(5))), |
| 181 | "bad-section-four": embed(container({ |
| 182 | type: "section", |
| 183 | components: [text("1"), text("2"), text("3"), text("4")], |
| 184 | accessory: link("x"), |
| 185 | })), |
| 186 | "bad-thumbnail-alone": embed(container({ type: "thumbnail", media: { url: image(400, 400) } })), |
| 187 | "bad-linked-missing": { ...embed(container(text("x"))), discord: "/embeds/missing.json" }, |
| 188 | |
| 189 | // open graph and twitter |
| 190 | "og-title-only": { openGraph: { title: "A title and nothing else" } }, |
| 191 | "og-pair": { title: "Title", description: "the title and description tags" }, |
| 192 | "og-pair-lonely": { title: "Title without a description" }, |
| 193 | "og-nothing": {}, |
| 194 | "og-small": { |
| 195 | title: "Small", |
| 196 | description: "A thumbnail beside the text.", |
| 197 | embed: { thumbnail: image(600, 600), thumbnailSize: "icon" }, |
| 198 | }, |
| 199 | "og-large": { |
| 200 | title: "Large", |
| 201 | description: "An image under the text.", |
| 202 | embed: { thumbnail: image(1200, 630) }, |
| 203 | themeColor: "#5865F2", |
| 204 | }, |
| 205 | "og-site-name": { |
| 206 | title: "Site", |
| 207 | description: "With a site name.", |
| 208 | embed: { siteTitle: "Paper Clover", thumbnail: image(1200, 630) }, |
| 209 | }, |
| 210 | "og-gallery-2": { |
| 211 | title: "Gallery", |
| 212 | description: "Two images.", |
| 213 | openGraph: { image: [image(800, 600), image(800, 600, 1)] }, |
| 214 | }, |
| 215 | "og-gallery-3": { |
| 216 | title: "Gallery", |
| 217 | description: "Three images.", |
| 218 | openGraph: { image: [image(800, 600), image(800, 600, 1), image(800, 600, 2)] }, |
| 219 | }, |
| 220 | "og-gallery-4": { |
| 221 | title: "Gallery", |
| 222 | description: "Four images.", |
| 223 | openGraph: { image: [0, 1, 2, 3].map((i) => image(800, 600, i)) }, |
| 224 | }, |
| 225 | "og-photo": { |
| 226 | title: "Photo", |
| 227 | twitter: { card: "photo", image: image(1200, 630) }, |
| 228 | openGraph: { image: image(1200, 630) }, |
| 229 | }, |
| 230 | "og-instapp": { title: "Instapp", openGraph: { type: "instapp:photo", image: image(1200, 630) } }, |
| 231 | "og-video": { |
| 232 | title: "Video", |
| 233 | openGraph: { type: "video.other", video: "/video.mp4", image: image(1280, 720) }, |
| 234 | twitter: { card: "player", title: "Video", image: image(1280, 720) }, |
| 235 | }, |
| 236 | "og-rich": { |
| 237 | title: "Rich", |
| 238 | description: "**bold** and a [link](https://example.com)\n- list", |
| 239 | openGraph: { type: "rich" }, |
| 240 | embed: { thumbnail: image(400, 400), thumbnailSize: "icon" }, |
| 241 | }, |
| 242 | "og-long": { |
| 243 | title: "A title that runs on well past the seventy bytes that Discord leaves of it", |
| 244 | description: "A description that runs on. ".repeat(20), |
| 245 | embed: { thumbnail: image(1200, 630) }, |
| 246 | }, |
| 247 | "og-color-bad": { title: "Color", description: "not a hex color", themeColor: "red" }, |
| 248 | "og-oembed": { title: "oEmbed", embed: {}, oEmbed: "/oembed.json" }, |
| 249 | "og-too-long-url": { |
| 250 | title: "Url", |
| 251 | description: "long image url", |
| 252 | openGraph: { image: "/" + "a".repeat(2100) + ".png" }, |
| 253 | }, |
| 254 | "tw-summary": { |
| 255 | title: "Summary", |
| 256 | description: "A summary card.", |
| 257 | embed: { thumbnail: image(600, 600), thumbnailSize: "icon" }, |
| 258 | }, |
| 259 | "tw-large": { title: "Large image", description: "Not shown on this card.", embed: { thumbnail: image(1200, 630) } }, |
| 260 | "tw-no-image": { title: "No image", description: "A summary card without an image.", embed: {} }, |
| 261 | "tw-no-card": { openGraph: { title: "OG", description: "only Open Graph tags" } }, |
| 262 | "tw-title-only": { twitter: { card: "summary", title: "Only a title" } }, |
| 263 | "tw-app": { title: "App", twitter: { card: "app" }, openGraph: { title: "App" } }, |
| 264 | }; |
| 265 | |
| 266 | /** pages that are not a `Meta`, for what a crawler is refused or finds malformed */ |
| 267 | const raw: Record<string, () => Response> = { |
| 268 | "http-403": () => new Response("<title>no</title>", { status: 403, headers: { "content-type": "text/html" } }), |
| 269 | "bad-json": () => rawPage(`{nope`), |
| 270 | "bad-oversize": () => |
| 271 | rawPage(JSON.stringify({ component: { type: 17, components: [{ type: 10, content: "x".repeat(3100) }] } })), |
| 272 | }; |
| 273 | |
| 274 | function rawPage(script: string) { |
| 275 | const html = `<!doctype html><title>Raw</title><meta property=og:title content=Raw>` |
| 276 | + `<meta property=og:description content="the fallback">` |
| 277 | + `<script id="discord:component-embed" type="application/json">${script}</script>`; |
| 278 | return new Response(html, { headers: { "content-type": "text/html" } }); |
| 279 | } |
| 280 | |
| 281 | const names = [...Object.keys(cards), ...Object.keys(raw)]; |
| 282 | |
| 283 | // -- the server -- |
| 284 | |
| 285 | async function serve() { |
| 286 | const graph = new incremental.Graph({ db: null }); |
| 287 | const debug = new incremental.Debugger(graph); |
| 288 | debug.update({ |
| 289 | ok: true, |
| 290 | value: null, |
| 291 | changed: [], |
| 292 | stats: { duration: 12, ran: 1, reused: 2, written: 3, cacheBytes: 4, outputBytes: 5 }, |
| 293 | watching: { file: 1 }, |
| 294 | statusLine: "Watching 1 file", |
| 295 | } as never); |
| 296 | |
| 297 | return http.serve({ |
| 298 | port, |
| 299 | respond: debug.respond(async (request) => { |
| 300 | const { pathname } = new URL(request.url); |
| 301 | const picture = /^\/img\/(\d+)x(\d+)-(\d)\.png$/.exec(pathname); |
| 302 | if (picture) { |
| 303 | const [, width, height, hue] = picture; |
| 304 | return new Response(new Uint8Array(png(Number(width), Number(height), hues[Number(hue)]!)), { |
| 305 | headers: { "content-type": "image/png" }, |
| 306 | }); |
| 307 | } |
| 308 | if (pathname === "/embeds/linked.json") return Response.json(payloadOf(linked)); |
| 309 | if (pathname === "/oembed.json") { |
| 310 | return Response.json({ |
| 311 | version: "1.0", |
| 312 | type: "link", |
| 313 | author_name: "Anthony Tešija", |
| 314 | provider_name: "Dungeon Delvers", |
| 315 | thumbnail_url: image(1200, 630, 4), |
| 316 | thumbnail_width: 1200, |
| 317 | thumbnail_height: 630, |
| 318 | }); |
| 319 | } |
| 320 | const name = pathname.slice(1); |
| 321 | if (name === "") { |
| 322 | const items = names.map((name) => `<li><a href="/${name}">${name}</a>`).join(""); |
| 323 | return new Response(`<!doctype html><title>meta cards</title><ul>${items}</ul>`, { |
| 324 | headers: { "content-type": "text/html" }, |
| 325 | }); |
| 326 | } |
| 327 | if (raw[name]) return raw[name](); |
| 328 | if (!cards[name]) return new Response("not a fixture", { status: 404 }); |
| 329 | const html = `<!doctype html><html><head>${ |
| 330 | meta.toHtml(template, cards[name]) |
| 331 | }</head><body><h1>${name}</h1></body></html>`; |
| 332 | return new Response(html, { headers: { "content-type": "text/html" } }); |
| 333 | }), |
| 334 | upgrade: debug.upgrade, |
| 335 | shouldUpgrade: debug.shouldUpgrade, |
| 336 | }); |
| 337 | } |
| 338 | |
| 339 | /** what discord reads of a component embed, which `toTags` makes of it */ |
| 340 | function payloadOf(discord: meta.DiscordComponent): meta.DiscordPayload { |
| 341 | const children = meta.toTags(template, { discord }).scripts[0]!.children; |
| 342 | return JSON.parse(children as string); |
| 343 | } |
| 344 | |
| 345 | // -- screenshots -- |
| 346 | |
| 347 | /** `--width=560 --scale=2` and the names of fixtures, which is all of them if there are none */ |
| 348 | function parse(args: string[]) { |
| 349 | const flags = Object.fromEntries(args.filter((arg) => arg.startsWith("--")).map((arg) => arg.slice(2).split("="))); |
| 350 | return { flags: flags as Record<string, string | undefined>, only: args.filter((arg) => !arg.startsWith("--")) }; |
| 351 | } |
| 352 | |
| 353 | async function shots(args: string[]) { |
| 354 | const { flags, only } = parse(args); |
| 355 | const { chromium } = await import("playwright"); |
| 356 | const server = await serve(); |
| 357 | // a page that reports itself automated gets no visualization |
| 358 | const browser = await chromium.launch({ channel: "chrome", args: ["--disable-blink-features=AutomationControlled"] }); |
| 359 | fs.mkdirSync(outDir, { recursive: true }); |
| 360 | try { |
| 361 | for (const name of only.length > 0 ? only : names) { |
| 362 | const context = await browser.newContext({ |
| 363 | viewport: { width: 900, height: 1200 }, |
| 364 | deviceScaleFactor: Number(flags.scale ?? 1), |
| 365 | }); |
| 366 | const page = await context.newPage(); |
| 367 | const problems: string[] = []; |
| 368 | page.on("pageerror", (error) => problems.push(error.message)); |
| 369 | await page.goto(`${base.href}${name}`); |
| 370 | await page.locator(".clover").click(); |
| 371 | await page.locator("#tab-meta").click(); |
| 372 | // the panel is as wide as the message that a card is checked against |
| 373 | if (flags.width) { |
| 374 | await page.evaluate( |
| 375 | (width) => |
| 376 | (document.querySelector("clover-debugger") as HTMLElement).style.setProperty("--width", `${width}px`), |
| 377 | flags.width, |
| 378 | ); |
| 379 | } |
| 380 | await page.locator(".cards > .preview").first().waitFor(); |
| 381 | // images that are published somewhere else fall back to this server's, and then they are done |
| 382 | await page.waitForFunction( |
| 383 | () => { |
| 384 | const images = document.querySelector("clover-debugger")!.shadowRoot!.querySelectorAll("img"); |
| 385 | return Array.from(images).every((img) => img.complete); |
| 386 | }, |
| 387 | undefined, |
| 388 | { polling: 100 }, |
| 389 | ); |
| 390 | await page.locator(".cards").screenshot({ path: `${outDir}/${name}.png` }); |
| 391 | const chat = page.locator(".chat").first(); |
| 392 | const box = await page.locator(".chat .d-container, .chat .discord").first().boundingBox().catch(() => null); |
| 393 | if (await chat.count()) await chat.screenshot({ path: `${outDir}/${name}.chat.png` }); |
| 394 | const size = box ? ` ${Math.round(box.width)}x${Math.round(box.height)}` : ""; |
| 395 | console.log(`${name}${size}${problems.length > 0 ? ` errors: ${problems.join("; ")}` : ""}`); |
| 396 | await context.close(); |
| 397 | } |
| 398 | } finally { |
| 399 | await browser.close(); |
| 400 | await server.close(); |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | // -- real discord -- |
| 405 | |
| 406 | /** the window of chrome that has discord open, as an image. macOS only, and it needs screen recording */ |
| 407 | function capture(file: string) { |
| 408 | const find = `ObjC.import("CoreGraphics"); |
| 409 | const windows = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo( |
| 410 | $.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements, $.kCGNullWindowID))); |
| 411 | windows.find((w) => w.kCGWindowOwnerName === "Google Chrome" && /Discord/.test(w.kCGWindowName ?? "")).kCGWindowNumber`; |
| 412 | const id = child_process.execFileSync("osascript", ["-l", "JavaScript", "-e", find]).toString().trim(); |
| 413 | child_process.execFileSync("screencapture", ["-x", "-o", `-l${id}`, file]); |
| 414 | } |
| 415 | |
| 416 | /** |
| 417 | * what to post for a fixture: a component embed as a message of components, and |
| 418 | * what a link to the rest would unfurl to as embeds, which Discord draws as it |
| 419 | * draws that unfurl, but for the provider's name |
| 420 | */ |
| 421 | function message(name: string): object | null { |
| 422 | const page = cards[name]!; |
| 423 | if (page.discord && typeof page.discord === "object") { |
| 424 | return { flags: 1 << 15, components: [payloadOf(page.discord).component] }; |
| 425 | } |
| 426 | const { title, description, themeColor, openGraph: og, twitter } = meta.scrape(meta.toTags(template, page)); |
| 427 | const text = { |
| 428 | url: `${base.href}${name}`, |
| 429 | title: og.title?.[0] ?? title ?? undefined, |
| 430 | description: og.description?.[0] ?? description ?? undefined, |
| 431 | color: themeColor && /^#[0-9a-f]{6}$/i.test(themeColor) ? parseInt(themeColor.slice(1), 16) : undefined, |
| 432 | }; |
| 433 | if (!text.title && !text.description) return null; |
| 434 | const images = (og.image ?? []).map((url) => new URL(url, base).href); |
| 435 | // embeds that share a link are one card with a gallery |
| 436 | if (images.length > 1 || (images.length === 1 && twitter.card?.at(-1) === "summary_large_image")) { |
| 437 | return { |
| 438 | embeds: images.slice(0, 4).map((url, i) => ({ ...(i === 0 ? text : { url: text.url }), image: { url } })), |
| 439 | }; |
| 440 | } |
| 441 | return { embeds: [{ ...text, ...(images[0] && { thumbnail: { url: images[0] } }) }] }; |
| 442 | } |
| 443 | |
| 444 | async function discord(only: string[]) { |
| 445 | const webhook = process.env.TEST_DISCORD_WEBHOOK; |
| 446 | if (!webhook) throw new Error("TEST_DISCORD_WEBHOOK is not set"); |
| 447 | const server = await serve(); |
| 448 | try { |
| 449 | for (const name of only.length > 0 ? only : Object.keys(cards).filter((name) => name.startsWith("c-"))) { |
| 450 | const body = message(name); |
| 451 | if (!body) continue; |
| 452 | // media on this machine goes along as attachments, which discord can read |
| 453 | const files = new Map<string, Buffer>(); |
| 454 | const json = JSON.stringify(body, (key, value) => { |
| 455 | if (key !== "url" || typeof value !== "string" || !value.startsWith(`${base.href}img/`)) return value; |
| 456 | const file = new URL(value).pathname.slice("/img/".length); |
| 457 | const [, width, height, hue] = /^(\d+)x(\d+)-(\d)\.png$/.exec(file)!; |
| 458 | files.set(file, png(Number(width), Number(height), hues[Number(hue)]!)); |
| 459 | return `attachment://${file}`; |
| 460 | }); |
| 461 | const form = new FormData(); |
| 462 | form.set("payload_json", json); |
| 463 | Array.from(files).forEach(([file, bytes], i) => form.set(`files[${i}]`, new Blob([new Uint8Array(bytes)]), file)); |
| 464 | const response = await fetch(`${webhook}?wait=true&with_components=true`, { method: "POST", body: form }); |
| 465 | console.log(`${name} ${response.status}${response.ok ? "" : " " + (await response.text())}`); |
| 466 | // the message is drawn, and its images are fetched, before the window is taken |
| 467 | await async.delay(3000); |
| 468 | fs.mkdirSync(`${outDir}/discord`, { recursive: true }); |
| 469 | capture(`${outDir}/discord/${name}.png`); |
| 470 | } |
| 471 | } finally { |
| 472 | await server.close(); |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | /** |
| 477 | * the capture of discord and the `meta` tab side by side, as high as the card and |
| 478 | * bottom aligned, in `.clover/meta-cards/compare`. `shots --width=620 --scale=2` |
| 479 | * makes the one half, and `discord` the other. The message pane is assumed to |
| 480 | * start at `paneX` device pixels, and the card to be the last thing in it. |
| 481 | */ |
| 482 | async function compare(args: string[]) { |
| 483 | const { only } = parse(args); |
| 484 | const { chromium } = await import("playwright"); |
| 485 | const browser = await chromium.launch({ channel: "chrome" }); |
| 486 | const page = await browser.newPage(); |
| 487 | fs.mkdirSync(`${outDir}/compare`, { recursive: true }); |
| 488 | const read = (file: string) => `data:image/png;base64,${fs.readFileSync(file).toString("base64")}`; |
| 489 | try { |
| 490 | for (const name of only) { |
| 491 | const url = await page.evaluate(async ([real, mine]) => { |
| 492 | const paneX = 760, width = 1040; |
| 493 | const load = async (src: string) => { |
| 494 | const img = new Image(); |
| 495 | img.src = src; |
| 496 | await img.decode(); |
| 497 | return img; |
| 498 | }; |
| 499 | const [capture, ours] = await Promise.all([load(real!), load(mine!)]); |
| 500 | // the bottom border of the last card, which is the last long run of its color |
| 501 | const canvas = document.createElement("canvas"); |
| 502 | canvas.width = capture.width; |
| 503 | canvas.height = capture.height; |
| 504 | const context = canvas.getContext("2d")!; |
| 505 | context.drawImage(capture, 0, 0); |
| 506 | const pixels = context.getImageData(0, 0, capture.width, capture.height).data; |
| 507 | let bottom = 0; |
| 508 | for (let y = 0; y < capture.height; y++) { |
| 509 | let run = 0; |
| 510 | for (let x = paneX; x < capture.width && run < 40; x++) { |
| 511 | const i = (y * capture.width + x) * 4; |
| 512 | run = Math.abs(pixels[i]! - 0x43) + Math.abs(pixels[i + 1]! - 0x45) + Math.abs(pixels[i + 2]! - 0x4c) < 6 |
| 513 | ? run + 1 |
| 514 | : 0; |
| 515 | } |
| 516 | if (run >= 40) bottom = y; |
| 517 | } |
| 518 | // the chat of the tab has 12 pixels of padding below the card, which is 24 device pixels |
| 519 | const height = Math.min(ours.height - 24, 1100); |
| 520 | const out = document.createElement("canvas"); |
| 521 | out.width = 2 * width + 8; |
| 522 | out.height = height + 24; |
| 523 | const draw = out.getContext("2d")!; |
| 524 | draw.fillStyle = "#000"; |
| 525 | draw.fillRect(0, 0, out.width, out.height); |
| 526 | draw.drawImage(capture, paneX, bottom + 2 - height, width, height + 24, 0, 0, width, height + 24); |
| 527 | draw.drawImage(ours, 0, ours.height - 24 - height, width, height + 24, width + 8, 0, width, height + 24); |
| 528 | return out.toDataURL("image/png"); |
| 529 | }, [read(`${outDir}/discord/${name}.png`), read(`${outDir}/${name}.chat.png`)]); |
| 530 | fs.writeFileSync(`${outDir}/compare/${name}.png`, Buffer.from(url.split(",")[1]!, "base64")); |
| 531 | console.log(`${outDir}/compare/${name}.png`); |
| 532 | } |
| 533 | } finally { |
| 534 | await browser.close(); |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | if (existsSync(".env")) process.loadEnvFile(".env"); |
| 539 | const [command, ...rest] = process.argv.slice(2); |
| 540 | if (command === "serve") { |
| 541 | const server = await serve(); |
| 542 | console.log(`up: ${base.href} (${names.length} pages)`); |
| 543 | process.on("SIGINT", () => void server.close().then(() => process.exit(0))); |
| 544 | } else if (command === "shots") { |
| 545 | await shots(rest); |
| 546 | } else if (command === "discord") { |
| 547 | await discord(rest); |
| 548 | } else if (command === "compare") { |
| 549 | await compare(rest); |
| 550 | } else { |
| 551 | console.log("usage: meta-cards.ts serve | shots [name...] | discord [name...] | compare name..."); |
| 552 | } |
| 553 | |
| 554 | import * as child_process from "node:child_process"; |
| 555 | import { existsSync } from "node:fs"; |
| 556 | import * as fs from "node:fs"; |
| 557 | import * as zlib from "node:zlib"; |
| 558 | import * as async from "../async.ts"; |
| 559 | import * as http from "../http.ts"; |
| 560 | import * as incremental from "../incremental.ts"; |
| 561 | import * as meta from "../meta.ts"; |