| 1 | import { readFileSync } from "node:fs"; |
| 2 | import { renderToStaticMarkup } from "react-dom/server"; |
| 3 | import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 4 | import { FACTS } from "./facts.generated"; |
| 5 | import { withBuildProvenance, isPublishedRelease, type RepoFacts } from "./facts"; |
| 6 | import { fetchRepoStats, readRepoStatsSnapshot } from "./github"; |
| 7 | import { buildLlmsTxt } from "./llms-txt"; |
| 8 | import { buildSoftwareApplicationJsonLd } from "./software-application-schema"; |
| 9 | import { AVAILABILITY_ROWS } from "./content/availability"; |
| 10 | import { APP_COPY } from "./content/app-page"; |
| 11 | import sitemap from "../app/sitemap"; |
| 12 | import HomePage from "../app/[locale]/page"; |
| 13 | import ContributePage from "../app/[locale]/contribute/page"; |
| 14 | import { extractHtmlText, extractJsonLdScripts } from "./test-html-text"; |
| 15 | |
| 16 | vi.mock("next/navigation", () => ({ redirect: vi.fn(), notFound: vi.fn(), usePathname: () => "/en", useRouter: () => ({}) })); |
| 17 | |
| 18 | const snapshot = JSON.parse(readFileSync(new URL("../data/repo-stats-snapshot.json", import.meta.url), "utf8")) as { stars: number }; |
| 19 | const published = JSON.parse(readFileSync(new URL("../data/latest-published-release.json", import.meta.url), "utf8")) as { |
| 20 | tag: string; version: string; publishedAt: string; url: string; readAt: string; assets: { name: string; size: number; sha256: string | null }[]; |
| 21 | }; |
| 22 | |
| 23 | type Page = (props: { params: Promise<{ locale: string }>; searchParams: Promise<Record<string, string>> }) => Promise<unknown> | unknown; |
| 24 | const render = async (page: Page, locale = "en") => |
| 25 | renderToStaticMarkup((await page({ params: Promise.resolve({ locale }), searchParams: Promise.resolve({}) })) as never); |
| 26 | |
| 27 | function failEveryGitHubCall() { |
| 28 | vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("network down"); })); |
| 29 | vi.spyOn(console, "error").mockImplementation(() => {}); |
| 30 | } |
| 31 | |
| 32 | afterEach(() => { |
| 33 | vi.unstubAllGlobals(); |
| 34 | vi.unstubAllEnvs(); |
| 35 | vi.restoreAllMocks(); |
| 36 | }); |
| 37 | |
| 38 | describe("the home page and /contribute with every GitHub call failing", () => { |
| 39 | beforeEach(failEveryGitHubCall); |
| 40 | |
| 41 | it.each(["en", "zh"])("render in %s with the snapshot numbers and no zero", async (locale) => { |
| 42 | for (const page of [HomePage, ContributePage]) { |
| 43 | const html = await render(page as Page, locale); |
| 44 | expect(html).toContain("<h1"); |
| 45 | const numbers = [...html.matchAll(/class="[^"]*\btabular\b[^"]*"[^>]*>([^<]*)</g)].map((match) => match[1].trim()); |
| 46 | expect(numbers).not.toContain("0"); |
| 47 | } |
| 48 | const numberLocale = locale === "zh" ? "zh-CN" : "en-US"; |
| 49 | expect(await render(ContributePage as Page, locale)).toContain(new Intl.NumberFormat(numberLocale).format(snapshot.stars)); |
| 50 | expect(await render(HomePage as Page, locale)).toContain(`>${new Intl.NumberFormat(numberLocale).format(FACTS.contributorCount)}<`); |
| 51 | }); |
| 52 | |
| 53 | it("states the published release, not the source version, on the home page", async () => { |
| 54 | const html = await render(HomePage as Page); |
| 55 | expect(html).toContain(`Version ${published.version} is released, and it needs no account.`); |
| 56 | if (FACTS.version !== published.version) expect(html).not.toContain(`Version ${FACTS.version} is released`); |
| 57 | }); |
| 58 | }); |
| 59 | |
| 60 | describe("a live number that cannot be read", () => { |
| 61 | const unknown = { stars: null, forks: null, openIssues: null, openPulls: null, contributors: null, fetchedAt: null, source: "unknown" }; |
| 62 | |
| 63 | it("is unknown, never 0 and never a floor, when GitHub refuses or is unreachable", async () => { |
| 64 | vi.stubGlobal("fetch", vi.fn(async () => new Response("rate limited", { status: 403 }))); |
| 65 | expect(await fetchRepoStats()).toEqual(unknown); |
| 66 | failEveryGitHubCall(); |
| 67 | expect(await fetchRepoStats()).toEqual(unknown); |
| 68 | }); |
| 69 | |
| 70 | it("leaves only the missing number unknown when one call fails", async () => { |
| 71 | vi.stubGlobal("fetch", vi.fn(async (url: string) => { |
| 72 | if (url.includes("/search/issues") || url.includes("/contributors") || url.includes("/releases/")) return new Response("{}", { status: 403 }); |
| 73 | return Response.json({ stargazers_count: 1234, forks_count: 56, open_issues_count: 70 }); |
| 74 | })); |
| 75 | const stats = await fetchRepoStats(); |
| 76 | expect(stats).toMatchObject({ stars: 1234, forks: 56, openPulls: null, openIssues: null, contributors: null, source: "live" }); |
| 77 | }); |
| 78 | |
| 79 | it("reads the committed snapshot on the production build path and rejects a bad snapshot", async () => { |
| 80 | vi.stubEnv("NEXT_PHASE", "phase-production-build"); |
| 81 | const stats = await fetchRepoStats(); |
| 82 | expect(stats.source).toBe("snapshot"); |
| 83 | expect(stats.stars).toBe(snapshot.stars); |
| 84 | expect(Date.parse(stats.fetchedAt ?? "")).toBeGreaterThan(0); |
| 85 | for (const bad of [null, {}, { stars: 0, readAt: "2026-01-01T00:00:00Z" }, { stars: 5, readAt: "never" }]) { |
| 86 | expect(readRepoStatsSnapshot(bad)).toEqual(unknown); |
| 87 | } |
| 88 | }); |
| 89 | }); |
| 90 | |
| 91 | describe("the version a visitor gets on install", () => { |
| 92 | it("is the one published-release object, in the data file, the facts and every line that names it", () => { |
| 93 | expect(published.tag).toBe(`v${published.version}`); |
| 94 | expect(published.assets.length).toBeGreaterThan(0); |
| 95 | expect(Date.parse(published.readAt)).toBeGreaterThan(0); |
| 96 | expect(FACTS.latestPublishedRelease).toEqual(published); |
| 97 | expect(isPublishedRelease(FACTS.latestPublishedRelease)).toBe(true); |
| 98 | |
| 99 | const llms = buildLlmsTxt(); |
| 100 | expect(llms).toContain(`The latest release is v${published.version}.`); |
| 101 | expect(llms).toContain(`read ${published.readAt.slice(0, 10)}`); |
| 102 | expect(llms).toContain(`This installs the latest published release, v${published.version}.`); |
| 103 | if (FACTS.version !== published.version) { |
| 104 | expect(llms.split("\n").filter((line) => line.includes("latest published release")).join("\n")).not.toContain(`v${FACTS.version}`); |
| 105 | } |
| 106 | expect(buildSoftwareApplicationJsonLd(published).softwareVersion).toBe(published.version); |
| 107 | }); |
| 108 | |
| 109 | it("keeps the source version out of the installed-version copy", () => { |
| 110 | const home = readFileSync(new URL("../app/[locale]/page.tsx", import.meta.url), "utf8"); |
| 111 | expect(home).toContain("fill(d.installNote, { version: release.version })"); |
| 112 | expect(home).not.toContain("facts.version"); |
| 113 | }); |
| 114 | }); |
| 115 | |
| 116 | describe("build provenance", () => { |
| 117 | const base = { ...FACTS, generatedAt: "2020-01-01T00:00:00.000Z", sourceRevision: null, sourceCommittedAt: null } as RepoFacts; |
| 118 | const revision = "a".repeat(40); |
| 119 | |
| 120 | it("stamps revision, commit time and generation time together", () => { |
| 121 | const stamped = withBuildProvenance(base, { revision, committedAt: "2026-11-10T10:00:00Z", generatedAt: "2026-11-10T11:00:00.000Z" }); |
| 122 | expect(stamped).toMatchObject({ sourceRevision: revision, sourceCommittedAt: "2026-11-10T10:00:00Z", generatedAt: "2026-11-10T11:00:00.000Z" }); |
| 123 | }); |
| 124 | |
| 125 | it.each([ |
| 126 | { revision, committedAt: "2026-11-10T10:00:00Z" }, |
| 127 | { revision, generatedAt: "2026-11-10T11:00:00.000Z" }, |
| 128 | { committedAt: "2026-11-10T10:00:00Z", generatedAt: "2026-11-10T11:00:00.000Z" }, |
| 129 | { revision: "abc", committedAt: "2026-11-10T10:00:00Z", generatedAt: "2026-11-10T11:00:00.000Z" }, |
| 130 | ])("never mixes a fresh stamp with the tracked file's date: %j", (stamp) => { |
| 131 | expect(withBuildProvenance(base, stamp)).toBe(base); |
| 132 | }); |
| 133 | }); |
| 134 | |
| 135 | describe("the desktop app is not called native", () => { |
| 136 | it("in the availability row and the app page, in English and Chinese", () => { |
| 137 | const desktop = AVAILABILITY_ROWS.find((row) => row.id === "desktop")!; |
| 138 | const copy = [desktop.detail, APP_COPY.title, APP_COPY.metadata.description].flatMap((text) => [text.en, text.zh]); |
| 139 | for (const sentence of copy) expect(sentence).not.toMatch(/native|原生/i); |
| 140 | }); |
| 141 | }); |
| 142 | |
| 143 | describe("no price, currency amount or plan name in the public surface", () => { |
| 144 | const PRICE = new RegExp([ |
| 145 | String.raw`[$€£¥¥]\s?\d`, |
| 146 | String.raw`\b\d[\d,.]*\s?(?:USD|CNY|RMB|EUR|GBP)\b`, |
| 147 | String.raw`\bper (?:month|seat|user|year)\b`, |
| 148 | String.raw`/\s?(?:month|mo|seat|user|year)\b`, |
| 149 | String.raw`\b(?:Free|Pro|Plus|Team|Teams|Max|Starter|Premium|Business|Enterprise|Individual)\s+(?:plan|tier|subscription)s?\b`, |
| 150 | String.raw`\b(?:plan|tier)s?\s+(?:price|pricing)`, |
| 151 | String.raw`\bpricing\b`, |
| 152 | String.raw`\bbilled\b`, |
| 153 | String.raw`\bfree trial\b`, |
| 154 | ].join("|"), "i"); |
| 155 | const STRUCTURED_PRICE = /"(?:offers?|price|priceCurrency|priceSpecification)"|\bOffer\b/; |
| 156 | |
| 157 | const pages: [string, () => Promise<{ default: unknown }>][] = [ |
| 158 | ["home", () => import("../app/[locale]/page")], |
| 159 | ["app", () => import("../app/[locale]/app/page")], |
| 160 | ["features", () => import("../app/[locale]/features/page")], |
| 161 | ["docs", () => import("../app/[locale]/docs/page")], |
| 162 | ["faq", () => import("../app/[locale]/faq/page")], |
| 163 | ["contribute", () => import("../app/[locale]/contribute/page")], |
| 164 | ["signin", () => import("../app/[locale]/signin/page")], |
| 165 | ["install", () => import("../app/[locale]/install/page")], |
| 166 | ["models", () => import("../app/[locale]/models/page")], |
| 167 | ["plugins", () => import("../app/[locale]/plugins/page")], |
| 168 | ["computer-use", () => import("../app/[locale]/computer-use/page")], |
| 169 | ["docs/constitution", () => import("../app/[locale]/docs/constitution/page")], |
| 170 | ]; |
| 171 | |
| 172 | beforeEach(failEveryGitHubCall); |
| 173 | |
| 174 | it.each(["en", "zh"])("holds on every public page in %s, in the visible text and in structured data", async (locale) => { |
| 175 | for (const [name, load] of pages) { |
| 176 | const html = await render((await load()).default as Page, locale); |
| 177 | const structured = extractJsonLdScripts(html).join("\n"); |
| 178 | // Real-session captures are product evidence, not authored copy: the |
| 179 | // recorded status line and /cost output show the session's own spend |
| 180 | // estimate ("estimate, not a bill"), which is the feature on display, |
| 181 | // not a price the site claims. |
| 182 | const text = extractHtmlText(html, { stripScripts: true, stripCapturePre: true, tagReplacement: " " }); |
| 183 | expect(text.match(PRICE)?.[0], `${locale}/${name} text`).toBeUndefined(); |
| 184 | expect(structured.match(PRICE)?.[0], `${locale}/${name} structured data`).toBeUndefined(); |
| 185 | expect(structured.match(STRUCTURED_PRICE)?.[0], `${locale}/${name} structured data`).toBeUndefined(); |
| 186 | } |
| 187 | }); |
| 188 | |
| 189 | it("holds for the software-application structured data and the sitemap", () => { |
| 190 | expect(JSON.stringify(buildSoftwareApplicationJsonLd(published))).not.toMatch(STRUCTURED_PRICE); |
| 191 | for (const entry of sitemap()) expect(entry.url, entry.url).not.toMatch(/pric|plans?\b|tier|billing|checkout|merch/i); |
| 192 | }); |
| 193 | }); |
| 194 |