diff --git a/.github/scripts/check-sdk-docs.mjs b/.github/scripts/check-sdk-docs.mjs new file mode 100644 index 0000000..074ca79 --- /dev/null +++ b/.github/scripts/check-sdk-docs.mjs @@ -0,0 +1,276 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +import { + currentVersionNote, + docsPath, + hash, + webSDKs, + documentedPackages, + versionedDocsReady, +} from "./sdk-docs.mjs"; + +export const root = path.resolve(fileURLToPath(new URL("../../", import.meta.url))); +const read = (base, file) => fs.readFileSync(path.join(base, file), "utf8"); +export const prose = (content) => content.replace(/```[^\n]*\n[\s\S]*?```/g, ""); +export const links = (content) => + [ + ...prose(content).matchAll( + /\[[^\]]*\]\(([^\s)]+)(?:\s+"[^"]*")?\)|(?:src|href)=["']([^"']+)["']/g, + ), + ].map((match) => match[1] ?? match[2]); +const slug = (text) => + text + .toLowerCase() + .replace(/<\/?(?:a|code|strong|em|span|br)(?:\s[^>]*)?>/g, "") + .replace(/[^\p{L}\p{N}_ -]/gu, "") + .replace(/ /g, "-"); + +export function anchors(content) { + const ids = new Set(); + for (const match of prose(content).matchAll(/\bid=["']([^"']+)["']/g)) ids.add(match[1]); + const headingIDs = new Set(); + for (const match of prose(content).matchAll(/^#{1,6} (.+)$/gm)) { + const base = slug(match[1]); + let id = base; + for (let suffix = 1; headingIDs.has(id); suffix++) id = `${base}-${suffix}`; + headingIDs.add(id); + ids.add(id); + } + return ids; +} + +function resolveLink(base, file, href) { + const [pathname, fragment] = href.split("#"); + let target = path.resolve( + base, + path.dirname(file), + decodeURIComponent(pathname || path.basename(file)), + ); + assert(target.startsWith(`${base}${path.sep}`), `Link escapes repository: ${file} -> ${href}`); + if (fs.existsSync(target) && fs.statSync(target).isDirectory()) + target = path.join(target, "README.md"); + return { target, fragment }; +} + +export function checkLinks(base, pages) { + const errors = []; + for (const file of pages) { + for (const href of links(read(base, file))) { + if (/^(?:[a-z][a-z\d+.-]*:|\/|\{)/i.test(href)) continue; + try { + const { target, fragment } = resolveLink(base, file, href); + assert(fs.existsSync(target), `Missing file: ${file} -> ${href}`); + if (fragment && target.endsWith(".md")) + assert( + anchors(fs.readFileSync(target, "utf8")).has(decodeURIComponent(fragment)), + `Missing anchor: ${file} -> ${href}`, + ); + } catch (error) { + errors.push(error.message); + } + } + } + assert.equal(errors.length, 0, errors.join("\n")); +} + +export function sourceMatrix(base = root) { + const commits = new Map(); + const manifests = path.join(base, ".generated/sdk-docs"); + for (const name of fs.existsSync(manifests) ? fs.readdirSync(manifests) : []) { + assert(documentedPackages.includes(name), `Unknown generated owner: ${name}`); + for (const filename of fs.readdirSync(path.join(base, ".generated/sdk-docs", name))) { + const manifest = JSON.parse(read(base, `.generated/sdk-docs/${name}/${filename}`)); + assert(/^[a-f\d]{40}$/.test(manifest.sourceCommit), "Invalid SDK source ref"); + const packages = commits.get(manifest.sourceCommit) ?? new Set(); + packages.add(name); + commits.set(manifest.sourceCommit, packages); + } + } + return { + include: [...commits].map(([ref, packages]) => ({ + ref, + packages: [...packages] + .sort() + .map((name) => `--package ${name}`) + .join(" "), + })), + }; +} + +export function checkCurrentPagePresentation(content, file) { + const notes = [...content.matchAll(/^Using v1\? .+$/gm)]; + assert.equal(notes.length, 1, `Expected one succinct version note: ${file}`); + assert(content.trimEnd().endsWith(notes[0][0]), `Legacy link must be at the end: ${file}`); + const body = prose(content); + assert.equal( + body.split("\n").filter((line) => line === currentVersionNote).length, + 1, + `Expected one SDK v2 scope note: ${file}`, + ); + const title = /^# .+$/m.exec(body); + const firstSection = /^#{2,6} /m.exec(body); + const scope = body.indexOf(currentVersionNote); + assert( + title && scope > title.index + title[0].length && scope < (firstSection?.index ?? body.length), + `SDK v2 scope note must be in the introduction: ${file}`, + ); + assert(!content.includes("**Protocol v2"), `Repeated protocol banner: ${file}`); + assert(!content.includes("Prerelease source documentation"), `Repeated release warning: ${file}`); + assert(!content.includes("Generated from ["), `Provenance belongs in the manifest: ${file}`); + for (const line of content.split("\n")) + if ( + /^\s*(?:npm (?:i|install)|yarn add|pnpm add|bun add|deno add|npx)\b|cdn\.jsdelivr\.net/.test( + line, + ) + ) + assert( + !/@reflag\/(?:node-sdk|browser-sdk|react-sdk|vue-sdk|cli)@2\b/.test(line), + `Major-pinned installs belong in the upgrade guide: ${file}`, + ); +} + +export function checkSDKDocs(base = root) { + const summary = read(base, "SUMMARY.md"); + if (!versionedDocsReady(base)) { + // Until the separate public-content cutover, only validate existing navigation. + assert( + !fs.existsSync(path.join(base, ".generated/sdk-docs")), + "Incomplete versioned documentation cutover", + ); + checkLinks(base, ["SUMMARY.md"]); + return { + generatedPages: 0, + navigationPages: links(summary).filter((href) => !/^[a-z][a-z\d+.-]*:/i.test(href)).length, + }; + } + const supported = /^## Supported languages\n([\s\S]*?)(?=\n## )/m.exec(summary)?.[1]; + assert(supported, "Missing Supported languages section"); + assert.equal( + links(supported).at(-1), + "supported-languages/migrating-from-v1.md", + "Migration guide must be last in Supported languages", + ); + const navigation = links(summary).filter((href) => !/^[a-z][a-z\d+.-]*:/i.test(href)); + assert.equal(new Set(navigation).size, navigation.length, "Duplicate navigation entry"); + const generated = new Set(); + const owners = new Map(); + for (const name of fs.readdirSync(path.join(base, ".generated/sdk-docs"))) { + for (const filename of fs.readdirSync(path.join(base, ".generated/sdk-docs", name))) { + const manifest = JSON.parse(read(base, `.generated/sdk-docs/${name}/${filename}`)); + assert.equal(manifest.package, `@reflag/${name}`); + assert(/^[a-f\d]{40}$/.test(manifest.sourceCommit), "Missing exact source commit"); + for (const [file, expected] of Object.entries(manifest.files)) { + const actual = hash(fs.readFileSync(path.join(base, file))); + assert.equal(actual, expected, `Generated file drift: ${file}`); + assert(!owners.has(file) || owners.get(file) === actual, `Conflicting ownership: ${file}`); + owners.set(file, actual); + if (file.endsWith(".md")) { + assert( + !/^Generated from\b/im.test(read(base, file)), + `Provenance belongs in the manifest: ${file}`, + ); + generated.add(file); + } + } + } + } + for (const major of [1, 2]) + for (const name of webSDKs) { + for (const filename of [ + "README.md", + "globals.md", + ...(name === "browser-sdk" ? ["feedback.md"] : []), + ]) { + const file = docsPath(name, major, filename); + assert(navigation.includes(file), `SDK page missing from navigation: ${file}`); + assert(generated.has(file), `SDK page has no source manifest: ${file}`); + const content = read(base, file); + const counterpart = docsPath(name, major === 1 ? 2 : 1, filename); + assert( + links(content).some((href) => { + if (/^(?:[a-z][a-z\d+.-]*:|\/)/i.test(href)) return false; + return path.relative(base, resolveLink(base, file, href).target) === counterpart; + }), + `Missing equivalent-version link: ${file}`, + ); + if (major === 2) checkCurrentPagePresentation(content, file); + if (major === 1) { + assert(content.includes("Protocol v1 — legacy")); + assert( + !/cdn\.jsdelivr\.net\/npm\/@reflag\/browser-sdk@(?!1\b)/.test(content), + "Legacy CDN must target v1", + ); + for (const line of content.split("\n")) + if (/^\s*(?:npm (?:i|install)|yarn add|pnpm add|bun add|deno add|npx)\b/.test(line)) { + for (const match of line.matchAll( + /@reflag\/(?:node-sdk|browser-sdk|react-sdk|vue-sdk|cli)(?:@([^\s]+))?/g, + )) + assert.equal(match[1], "1", `Unpinned legacy install: ${file}: ${line}`); + } + } + } + } + const shared = navigation.filter( + (file) => + !generated.has(file) && + !file.startsWith("legacy/") && + !file.startsWith("api/") && + !file.endsWith("globals.md") && + !file.includes("react-native-sdk") && + file !== "supported-languages/migrating-from-v1.md", + ); + for (const file of shared) { + const content = read(base, file); + assert( + !/\{\s*(?:isEnabled|config\s*:)[^\n]*\}\s*=\s*(?:useFlag|.*\.getFlag)\(/.test(content), + `Legacy wrapper in shared example: ${file}`, + ); + assert(!content.includes("../sdk/v2/"), `Obsolete SDK preview link: ${file}`); + if (file === "supported-languages/next.js.md") checkCurrentPagePresentation(content, file); + for (const line of content.split("\n")) + if (/^\s*(?:npm (?:i|install)|yarn add|pnpm add|bun add|deno add|npx)\b/.test(line)) + assert( + !/@reflag\/[a-z-]+@2\b/.test(line), + `Major-pinned installs belong in the upgrade guide: ${file}`, + ); + } + // Existing unrelated handbook anchors are not a gate for generated SDK output. + // New SDK links, migration/overview links and all navigation must resolve. + checkLinks(base, [ + "SUMMARY.md", + ...generated, + "legacy/v1/README.md", + "supported-languages/migrating-from-v1.md", + "supported-languages/overview.md", + ...shared.filter((file) => + [ + "README.md", + "supported-languages/next.js.md", + "product-handbook/service-resiliency.md", + "product-handbook/type-safety.md", + "product-handbook/remote-config.md", + "product-handbook/multivariate-flags.md", + ].includes(file), + ), + ]); + return { generatedPages: generated.size, navigationPages: navigation.length }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + console.log(JSON.stringify(checkSDKDocs(), null, 2)); + if (process.argv.includes("--sources")) { + const outputs = { + matrix: JSON.stringify(sourceMatrix()), + react_v1_ref: JSON.parse(read(root, ".generated/sdk-docs/react-sdk/v1.json")).sourceCommit, + react_v2_ref: JSON.parse(read(root, ".generated/sdk-docs/react-sdk/v2.json")).sourceCommit, + node_v2_ref: JSON.parse(read(root, ".generated/sdk-docs/node-sdk/v2.json")).sourceCommit, + }; + if (process.env.GITHUB_OUTPUT) + for (const [key, value] of Object.entries(outputs)) + fs.appendFileSync(process.env.GITHUB_OUTPUT, `${key}=${value}\n`); + console.log(JSON.stringify(outputs, null, 2)); + } +} diff --git a/.github/scripts/sdk-docs.mjs b/.github/scripts/sdk-docs.mjs new file mode 100644 index 0000000..6f3ad84 --- /dev/null +++ b/.github/scripts/sdk-docs.mjs @@ -0,0 +1,380 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { parseArgs } from "node:util"; + +export const webSDKs = ["browser-sdk", "react-sdk", "vue-sdk", "node-sdk"]; +export const currentVersionNote = "This page covers SDK v2."; +const references = [...webSDKs, "react-native-sdk", "management-sdk"]; +export const documentedPackages = [...references, "cli"]; +export const versionedDocsReady = (destination) => + ["legacy/v1/README.md", "supported-languages/migrating-from-v1.md"].every((file) => + fs.existsSync(path.join(destination, file)), + ); +const repository = "https://github.com/reflagcom/javascript"; +const versionPattern = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[\da-zA-Z.-]+)?(?:\+[\da-zA-Z.-]+)?$/; +const read = (root, file) => fs.readFileSync(path.join(root, file), "utf8"); +const git = (source, ...args) => + execFileSync("git", ["-C", source, ...args], { encoding: "utf8" }).trim(); +export const hash = (content) => createHash("sha256").update(content).digest("hex"); +const relative = (from, to) => path.posix.relative(path.posix.dirname(from), to); + +export function docsPath(name, major, filename = "README.md") { + assert(documentedPackages.includes(name), `Unknown documentation owner: ${name}`); + if (webSDKs.includes(name)) { + assert([1, 2].includes(major), `Unmapped SDK major: ${major}`); + return `${major === 1 ? "legacy/v1" : "supported-languages"}/${name}/${filename}`; + } + if (name === "management-sdk") return `api/management-sdk/${filename}`; + if (name === "cli") return "api/cli.md"; + return `supported-languages/react-native-sdk/${filename}`; +} + +function metadata(source, name) { + assert(documentedPackages.includes(name), `Unknown documentation owner: ${name}`); + const pkg = JSON.parse(read(source, `packages/${name}/package.json`)); + assert.equal(pkg.name, `@reflag/${name}`); + assert(versionPattern.test(pkg.version), `Invalid version: ${pkg.name}`); + assert(!pkg.private, `Private package: ${pkg.name}`); + return pkg; +} + +function withBanner(content, message) { + const note = `{% hint style="info" %}\n${message}\n{% endhint %}\n\n`; + if (!content.startsWith("---\n")) return note + content; + const end = content.indexOf("\n---\n", 4); + assert(end >= 0, "Unclosed frontmatter"); + return content.slice(0, end + 5) + "\n" + note + content.slice(end + 5).trimStart(); +} + +export const headingSlug = (text) => + text + .toLowerCase() + .replace(/<\/?(?:a|code|strong|em|span|br)(?:\s[^>]*)?>/g, "") + .replace(/[^\p{L}\p{N}_ -]/gu, "") + .replace(/ /g, "-"); + +export function anchorHeadings(content, { introNote } = {}) { + const lines = content.split("\n"); + const headings = []; + const linked = new Set([...content.matchAll(/#([\w-]+)/g)].map((match) => match[1])); + let fence; + for (const [index, line] of lines.entries()) { + const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1]; + if (marker) { + if (!fence) fence = marker; + else if (fence[0] === marker[0] && marker.length >= fence.length) fence = undefined; + continue; + } + if (fence) continue; + const match = /^(#{1,6}) (.+)$/.exec(line); + if (match) headings.push({ index, level: match[1].length, text: match[2] }); + } + const ids = new Set(); + // Canonical docs.sh strips property-collision suffixes from type links. + // Reserve public class/interface/type IDs before similarly named members: + // #logger must still identify Logger, not the earlier client.logger field. + const priority = (heading) => (heading.level <= 3 ? 0 : 1); + for (const heading of [...headings].sort((a, b) => priority(a) - priority(b))) { + const base = headingSlug(heading.text); + let id = base; + for (let suffix = 1; ids.has(id); suffix++) id = `${base}-${suffix}`; + heading.id = id; + ids.add(id); + } + for (const { index, level, text, id } of headings) { + // GitBook drops IDs on Markdown levels 4–6. Promote API members and + // linked headings, but keep unlinked Parameters/Returns out of the outline. + if (level > 3 && (level === 5 || linked.has(id))) + lines[index] = lines[index].replace(/^#{4,6}/, "###"); + // Explicit IDs also preserve TypeDoc's and punctuation-based slugs. + if (!/\bid=["']/.test(text)) lines[index] += ` `; + } + if (introNote) { + const firstSection = headings.find((heading) => heading.level > 1)?.index ?? lines.length; + lines.splice(firstSection, 0, introNote, ""); + } + return lines.join("\n"); +} + +export function planPackage({ source, name, commit }) { + assert(/^[a-f\d]{40}$/.test(commit), "A full SDK source commit is required"); + const pkg = metadata(source, name); + const major = Number(pkg.version.split(".")[0]); + const web = webSDKs.includes(name); + const files = new Map(); + const mediaRoot = web + ? major === 1 + ? "legacy/v1/_media" + : "supported-languages/_media" + : "sdk/_media"; + const add = (file, content) => { + const bytes = Buffer.from(content); + assert( + !files.has(file) || files.get(file).equals(bytes), + `Conflicting generated output: ${file}`, + ); + files.set(file, bytes); + }; + const targetMajor = (target) => { + if (!webSDKs.includes(target)) return Number(metadata(source, target).version.split(".")[0]); + if (web) return major; + const range = + pkg.dependencies?.[`@reflag/${target}`] ?? + pkg.peerDependencies?.[`@reflag/${target}`] ?? + (name === "react-native-sdk" ? pkg.dependencies?.["@reflag/react-sdk"] : undefined); + const selected = /^[~^]?(\d+)\./.exec(range ?? "")?.[1]; + assert(selected, `Cannot determine linked SDK major: ${target}`); + return Number(selected); + }; + const route = (url, output) => { + if (url.startsWith("#")) return url; + // Absolute SDK links must not send legacy readers into the current API. + const publicLink = + /^https:\/\/docs\.reflag\.com\/(?:supported-languages|sdk\/@reflag)\/([^/#]+)(?:\/(globals)(?:\.md)?)?\/?(#[^\s]*)?$/.exec( + url, + ); + if (publicLink && webSDKs.includes(publicLink[1])) { + return ( + relative( + output.file, + docsPath( + publicLink[1], + targetMajor(publicLink[1]), + publicLink[2] ? "globals.md" : "README.md", + ), + ) + (publicLink[3] ?? "") + ); + } + if (/^(?:[a-z][a-z\d+.-]*:|\/)/i.test(url)) { + return url + .replace(`${repository}/blob/main/`, `${repository}/blob/${commit}/`) + .replace(`${repository}/tree/main/`, `${repository}/tree/${commit}/`); + } + const [pathname, fragment = ""] = url.split(/(?=#)/, 2); + let raw = path.posix.normalize( + path.posix.join(path.posix.dirname(output.raw), decodeURIComponent(pathname)), + ); + assert(!raw.startsWith("../") && !path.posix.isAbsolute(raw), `Link escapes SDK docs: ${url}`); + // TypeDoc's shared README attachment can contain the wrong package's README. + if (raw === "_media/README.md") { + const original = read(source, `packages/${name}/README.md`); + const linked = /\]\(\.\.\/([^/]+)\/README\.md\)/.exec(original)?.[1]; + assert(linked && documentedPackages.includes(linked), "Unmapped README attachment"); + raw = `@reflag/${linked}/README.md`; + } + const sdk = /^@reflag\/([^/]+)\/(README|globals)\.md$/.exec(raw); + if (sdk) + return ( + relative(output.file, docsPath(sdk[1], targetMajor(sdk[1]), `${sdk[2]}.md`)) + fragment + ); + if (raw === "documents/browser-sdk/FEEDBACK.md") + return ( + relative(output.file, docsPath("browser-sdk", targetMajor("browser-sdk"), "feedback.md")) + + fragment + ); + const document = /^documents\/([^/]+)\/README\.md$/.exec(raw); + if (document && references.includes(document[1])) + return relative(output.file, docsPath(document[1], targetMajor(document[1]))) + fragment; + if (raw.startsWith("_media/")) { + const target = `${mediaRoot}/${raw.slice("_media/".length)}`; + add(target, fs.readFileSync(path.join(source, "dist/docs", raw))); + return relative(output.file, target) + fragment; + } + return `${repository}/blob/${commit}/${raw}${fragment}`; + }; + const render = (raw, file, kind) => { + let content = read(source, `dist/docs/${raw}`); + // Canonical docs.sh normalizes property anchors; normalize all links, too. + content = content.replace(/(globals\.md#[\w-]+?)-\d+(?=[)"\s])/g, "$1"); + content = content.replace(/```[^\n]*\n[\s\S]*?```/g, (block) => block.replace(/[ \t]+$/gm, "")); + content = content.replace( + /(\]\()([^\s)]+)([^)]*\))/g, + (_, open, url, close) => `${open}${route(url, { raw, file })}${close}`, + ); + content = content.replace( + /((?:src|href)=["'])([^"']+)(["'])/g, + (_, open, url, close) => `${open}${route(url, { raw, file })}${close}`, + ); + content = anchorHeadings(content, { + introNote: web && major === 2 ? currentVersionNote : undefined, + }); + if (web) { + if (major === 1) { + // Only legacy installs need a major pin; current docs assume a fresh install. + content = content + .split("\n") + .map((line) => { + if (!/^\s*(?:npm (?:i|install)|yarn add|pnpm add|bun add|deno add|npx)\b/.test(line)) + return line; + return line.replace( + /@reflag\/(?:node-sdk|browser-sdk|react-sdk|vue-sdk|cli)(?:@[\w.^~-]+)?(?![\w/-])/g, + (match) => `${match.replace(/@[^@/]+$/, "")}@1`, + ); + }) + .join("\n"); + content = content.replace( + /(https:\/\/cdn\.jsdelivr\.net\/npm\/@reflag\/browser-sdk)(?:@[^/"'<>\s]+)?/g, + "$1@1", + ); + } + const counterpart = docsPath( + name, + major === 1 ? 2 : 1, + kind === "feedback" ? "feedback.md" : kind === "reference" ? "globals.md" : "README.md", + ); + const migration = relative(file, "supported-languages/migrating-from-v1.md"); + content = + major === 1 + ? withBanner( + content, + `**Protocol v1 — legacy.** [Current v2 documentation](${relative(file, counterpart)}) · [Migration guide](${migration})`, + ) + : `${content.trimEnd()}\n\nUsing v1? [Legacy docs](${relative(file, counterpart)}) · [Upgrade guide](${migration}).\n`; + } else if (name === "react-native-sdk") { + content = withBanner( + content, + `**Independent SDK compatibility.** This React Native release uses React/Browser protocol v${targetMajor("react-sdk")}. Follow the [matching React documentation](${relative(file, docsPath("react-sdk", targetMajor("react-sdk")))}) and use a [matching Node SDK](${relative(file, docsPath("node-sdk", targetMajor("react-sdk")))}) for bootstrap. Do not pass protocol-v2 bootstrap into a v1 consumer.`, + ); + } + add(file, content); + }; + if (references.includes(name)) { + for (const filename of ["README.md", "globals.md"]) { + const raw = `@reflag/${name}/${filename}`; + const kind = filename === "globals.md" ? "reference" : "readme"; + render(raw, docsPath(name, major, filename), kind); + // Keep historical SDK URLs and their reference anchors usable, but only + // the current major owns these aliases. A v1 release cannot replace v2. + if (!web || major === 2) render(raw, `sdk/@reflag/${name}/${filename}`, kind); + if ( + ((name === "react-sdk" && major === 2) || name === "react-native-sdk") && + filename === "README.md" + ) + render(raw, `sdk/documents/${name}/README.md`, kind); + } + } + if (name === "browser-sdk") { + const raw = "documents/browser-sdk/FEEDBACK.md"; + render(raw, docsPath(name, major, "feedback.md"), "feedback"); + if (major === 2) render(raw, "sdk/documents/browser-sdk/FEEDBACK.md", "feedback"); + } + if (name === "cli") { + render("documents/cli/README.md", "api/cli.md", "readme"); + render("documents/cli/README.md", "sdk/documents/cli/README.md", "readme"); + } + const manifest = { + sourceRepository: repository, + sourceCommit: commit, + package: pkg.name, + version: pkg.version, + files: Object.fromEntries([...files].map(([file, content]) => [file, hash(content)])), + }; + add(`.generated/sdk-docs/${name}/v${major}.json`, `${JSON.stringify(manifest, null, 2)}\n`); + return files; +} + +export function applyPlan(files, destination, { check = false } = {}) { + for (const [file, content] of files) { + assert(!path.isAbsolute(file) && !file.split("/").includes(".."), "Unsafe generated path"); + const target = path.join(destination, file); + if (check) + assert(fs.readFileSync(target).equals(content), `Generated documentation differs: ${file}`); + else { + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, content); + } + } + // Never delete a tree, or take ownership of navigation, guides or GitBook settings. +} + +export function releaseFiles(source, plan) { + assert.equal( + git(source, "status", "--porcelain", "--untracked-files=no"), + "", + "SDK source must be clean", + ); + const commit = git(source, "rev-parse", "HEAD"); + assert.equal(plan.sourceCommit, commit, "Release source changed"); + assert(Array.isArray(plan.releases), "Invalid release plan"); + const files = new Map(); + const seen = new Set(); + for (const release of plan.releases) { + assert(/^@reflag\/[a-z][a-z0-9-]*$/.test(release.name), "Invalid package name"); + const name = release.name.slice("@reflag/".length); + const pkg = metadata(source, name); + assert(!seen.has(name), `Duplicate package: ${name}`); + seen.add(name); + assert.equal(pkg.version, release.version, "Published/source version mismatch"); + assert(!versionPattern.exec(pkg.version)[4], "Prereleases cannot promote stable docs"); + assert.equal( + git(source, "rev-parse", `refs/tags/${pkg.name}@${pkg.version}^{commit}`), + commit, + "Release tag/source mismatch", + ); + for (const [file, content] of planPackage({ source, name, commit })) { + assert(!files.has(file) || files.get(file).equals(content), `Conflicting output: ${file}`); + files.set(file, content); + } + } + return files; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + const { values, positionals } = parseArgs({ + allowPositionals: true, + options: { + source: { type: "string" }, + destination: { type: "string", default: "." }, + package: { type: "string", multiple: true }, + plan: { type: "string" }, + check: { type: "boolean", default: false }, + }, + }); + const destination = path.resolve(values.destination); + if (positionals[0] === "ready") { + // Infrastructure can land before the public v1/v2 documentation cutover. + console.log(`ready=${versionedDocsReady(destination)}`); + } else { + assert(values.source, "--source is required"); + const source = path.resolve(values.source); + let files; + if (positionals[0] === "release") { + assert( + versionedDocsReady(destination), + "Versioned documentation must be published before release sync", + ); + assert(values.plan, "--plan is required"); + files = releaseFiles(source, JSON.parse(fs.readFileSync(values.plan, "utf8"))); + } else { + assert.equal(positionals[0], "import", "Use ready, import or release"); + assert(values.package?.length, "Select --package explicitly"); + assert.equal( + git(source, "status", "--porcelain", "--untracked-files=no"), + "", + "SDK source must be clean", + ); + files = new Map(); + for (const name of values.package) + for (const [file, content] of planPackage({ + source, + name, + commit: git(source, "rev-parse", "HEAD"), + })) { + assert( + !files.has(file) || files.get(file).equals(content), + `Conflicting output: ${file}`, + ); + files.set(file, content); + } + } + applyPlan(files, destination, { check: values.check }); + console.log( + `${values.check ? "Verified" : "Generated"} ${files.size} SDK documentation files.`, + ); + } +} diff --git a/.github/scripts/sdk-docs.test.mjs b/.github/scripts/sdk-docs.test.mjs new file mode 100644 index 0000000..ae66967 --- /dev/null +++ b/.github/scripts/sdk-docs.test.mjs @@ -0,0 +1,434 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + anchors, + checkCurrentPagePresentation, + checkLinks, + checkSDKDocs, + root, + sourceMatrix, +} from "./check-sdk-docs.mjs"; +import { + anchorHeadings, + applyPlan, + currentVersionNote, + docsPath, + planPackage, + releaseFiles, + versionedDocsReady, + webSDKs, +} from "./sdk-docs.mjs"; + +function fixture(t, major = 2) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "reflag-sdk-docs-test-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const source = path.join(dir, "source"), + destination = path.join(dir, "docs"); + const put = (file, content) => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content); + }; + const names = [...webSDKs, "react-native-sdk", "management-sdk", "cli"]; + for (const name of names) { + put( + path.join(source, `packages/${name}/package.json`), + JSON.stringify({ + name: `@reflag/${name}`, + version: `${major}.0.0`, + dependencies: { "@reflag/react-sdk": "1.7.4" }, + }), + ); + put( + path.join(source, `packages/${name}/README.md`), + "# SDK\n[Browser](../browser-sdk/README.md)\n", + ); + put( + path.join(source, `dist/docs/@reflag/${name}/README.md`), + `---\nlayout: {}\n---\n# SDK\n\nSDK introduction.\n\n## Setup\n[Browser](../../_media/README.md)\n[Feedback](../../documents/browser-sdk/FEEDBACK.md)\n[Toolbar](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions)\nnpm install @reflag/${name}\nbun add @reflag/${name}\ndeno add npm:@reflag/${name}\nnpx @reflag/cli new\n\n[Source](https://github.com/reflagcom/javascript/blob/main/packages/${name}/README.md)\n`, + ); + put( + path.join(source, `dist/docs/@reflag/${name}/globals.md`), + '# Reference\n## FlagValueFromDefault\\\n\n', + ); + } + put( + path.join(source, "dist/docs/documents/browser-sdk/FEEDBACK.md"), + "# Feedback\n[Browser](../../@reflag/browser-sdk/README.md)\n", + ); + put(path.join(source, "dist/docs/documents/cli/README.md"), "# CLI\n"); + return { + source, + destination, + put, + options: { source, name: "react-sdk", commit: "a".repeat(40) }, + }; +} + +test("repository navigation is valid before the separate public-content cutover", () => { + assert(checkSDKDocs().navigationPages > 0); +}); + +test("source discovery supports infrastructure-only installs and groups exact manifest refs", (t) => { + const { options, destination } = fixture(t); + assert.deepEqual(sourceMatrix(destination), { include: [] }); + for (const name of ["react-sdk", "browser-sdk"]) + applyPlan(planPackage({ ...options, name }), destination); + assert.deepEqual(sourceMatrix(destination), { + include: [ + { + ref: options.commit, + packages: "--package browser-sdk --package react-sdk", + }, + ], + }); +}); + +test("release readiness waits for both public migration and archive landing pages without writing", (t) => { + const { destination, put } = fixture(t); + const ready = () => + execFileSync( + process.execPath, + [path.join(root, ".github/scripts/sdk-docs.mjs"), "ready", "--destination", destination], + { encoding: "utf8" }, + ); + assert.equal(versionedDocsReady(destination), false); + assert.equal(ready(), "ready=false\n"); + assert(!fs.existsSync(destination)); + put(path.join(destination, "legacy/v1/README.md"), "# Legacy\n"); + assert.equal(ready(), "ready=false\n"); + put(path.join(destination, "supported-languages/migrating-from-v1.md"), "# Migration\n"); + assert.equal(ready(), "ready=true\n"); + assert.equal(versionedDocsReady(destination), true); +}); + +test("release CLI rejects a pre-cutover destination before reading sources or writing pages", (t) => { + const { source, destination } = fixture(t); + assert.throws( + () => + execFileSync( + process.execPath, + [ + path.join(root, ".github/scripts/sdk-docs.mjs"), + "release", + "--source", + source, + "--destination", + destination, + "--plan", + "missing.json", + ], + { stdio: "pipe" }, + ), + /Versioned documentation must be published/, + ); + assert(!fs.existsSync(destination)); +}); + +test("a partial content cutover fails validation rather than bypassing version isolation", (t) => { + const { options, destination, put } = fixture(t); + put(path.join(destination, "SUMMARY.md"), "# Contents\n"); + applyPlan(planPackage(options), destination); + assert.throws(() => checkSDKDocs(destination), /Incomplete versioned documentation cutover/); +}); + +test("v1 import owns only the archive, pins installers/CDN and routes SDK links to v1", (t) => { + const { options } = fixture(t, 1); + const files = planPackage(options); + assert( + [...files.keys()].every( + (file) => file.startsWith("legacy/v1/") || file.startsWith(".generated/"), + ), + ); + const readme = files.get("legacy/v1/react-sdk/README.md").toString(); + assert.match(readme, /npm install @reflag\/react-sdk@1/); + assert.match(readme, /bun add @reflag\/react-sdk@1/); + assert.match(readme, /deno add npm:@reflag\/react-sdk@1/); + assert.match(readme, /npx @reflag\/cli@1 new/); + assert.match(readme, /browser-sdk@1/); + assert.match(readme, /\(\.\.\/browser-sdk\/globals.md#toolbaroptions\)/); + assert.match(readme, /blob\/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\//); + assert(readme.indexOf("---") < readme.indexOf("{% hint"), "Keep frontmatter first"); + for (const [file, content] of files) + if (file.endsWith(".md")) { + assert.doesNotMatch(content.toString(), /generated from/i); + assert(!content.toString().includes(currentVersionNote)); + } + const manifest = JSON.parse(files.get(".generated/sdk-docs/react-sdk/v1.json")); + assert.equal(manifest.sourceCommit, options.commit); + assert.equal(manifest.version, "1.0.0"); +}); + +test("v2 sync cannot modify archived docs, navigation, settings or handwritten guides", (t) => { + const { options, destination, put } = fixture(t); + const preserved = [ + "legacy/v1/react-sdk/README.md", + "SUMMARY.md", + "README.md", + "gitbook-docs.yaml", + "supported-languages/migrating-from-v1.md", + ]; + for (const file of preserved) put(path.join(destination, file), "preserve"); + const files = planPackage(options); + applyPlan(files, destination); + applyPlan(files, destination, { check: true }); + for (const file of preserved) + assert.equal(fs.readFileSync(path.join(destination, file), "utf8"), "preserve"); + assert(files.has("supported-languages/react-sdk/README.md")); + assert(files.has("sdk/@reflag/react-sdk/globals.md"), "Preserve historical reference URLs"); + assert.match( + files.get("sdk/@reflag/react-sdk/README.md").toString(), + /\.\.\/\.\.\/\.\.\/legacy\/v1\/react-sdk\/README.md/, + ); +}); + +test("current docs retain the introduction, add one v2 scope line and keep unpinned installs", (t) => { + const { options, source, put } = fixture(t); + put( + path.join(source, "packages/react-sdk/package.json"), + JSON.stringify({ name: "@reflag/react-sdk", version: "2.0.0-next.0" }), + ); + const files = planPackage(options); + for (const file of [ + "supported-languages/react-sdk/README.md", + "sdk/@reflag/react-sdk/README.md", + "sdk/documents/react-sdk/README.md", + ]) { + const content = files.get(file).toString(); + checkCurrentPagePresentation(content, file); + assert(content.indexOf("SDK introduction.") < content.indexOf(currentVersionNote)); + assert(content.indexOf(currentVersionNote) < content.indexOf("## Setup")); + assert(content.indexOf("## Setup") < content.indexOf("Using v1?")); + assert.match(content, /npm install @reflag\/react-sdk\n/); + assert.match(content, /npx @reflag\/cli new/); + assert.match(content, /browser-sdk"><\/script>/); + assert(!content.includes("{% hint")); + assert( + !content.includes("2.0.0-next.0"), + "Source versions remain in provenance, not page warnings", + ); + } + const manifest = JSON.parse(files.get(".generated/sdk-docs/react-sdk/v2.json")); + assert.equal(manifest.version, "2.0.0-next.0"); +}); + +test("presentation checks reject repeated or leading notices and major-pinned current installs", () => { + const note = "Using v1? [Legacy docs](legacy.md) · [Upgrade guide](migration.md)."; + const page = `# SDK\n\nGet started.\n\n${currentVersionNote}\n\n## Setup\n\nInstall the SDK.\n\n${note}\n`; + checkCurrentPagePresentation(page, "page.md"); + assert.throws( + () => checkCurrentPagePresentation(page.replace(currentVersionNote, ""), "page.md"), + /one SDK v2 scope note/, + ); + assert.throws( + () => checkCurrentPagePresentation(`${currentVersionNote}\n\n${page}`, "page.md"), + /one SDK v2 scope note/, + ); + assert.throws( + () => + checkCurrentPagePresentation( + `${currentVersionNote}\n\n${page.replace(currentVersionNote, "")}`, + "page.md", + ), + /in the introduction/, + ); + assert.throws( + () => + checkCurrentPagePresentation( + page.replace(`${currentVersionNote}\n\n## Setup`, `## Setup\n\n${currentVersionNote}`), + "page.md", + ), + /in the introduction/, + ); + assert.throws(() => checkCurrentPagePresentation(`${note}\n\n# SDK\n`, "page.md"), /at the end/); + assert.throws( + () => checkCurrentPagePresentation(`${note}\n\n${page}`, "page.md"), + /one succinct/, + ); + assert.throws( + () => + checkCurrentPagePresentation( + page.replace("Get started.", "npm install @reflag/react-sdk@2"), + "page.md", + ), + /Major-pinned installs/, + ); + assert.throws( + () => checkCurrentPagePresentation(page.replace("Get started.", "**Protocol v2.**"), "page.md"), + /Repeated protocol banner/, + ); +}); + +test("independent Native references route to its pinned React/Browser major, not workspace v2", (t) => { + const { options } = fixture(t); + const files = planPackage({ ...options, name: "react-native-sdk" }); + const readme = files.get("supported-languages/react-native-sdk/README.md").toString(); + assert.match(readme, /legacy\/v1\/browser-sdk\/README.md/); + assert.match(readme, /legacy\/v1\/react-sdk\/README.md/); + assert(!readme.includes(currentVersionNote)); + assert(!files.has("supported-languages/react-sdk/README.md")); + assert(!files.has("legacy/v1/react-sdk/README.md")); +}); + +test("Management and CLI updates never own coordinated SDK trees", (t) => { + const { options, source, put } = fixture(t); + put(path.join(source, "dist/docs/@reflag/management-sdk/README.md"), "# Management SDK\n"); + for (const name of ["management-sdk", "cli"]) { + const files = planPackage({ ...options, name }); + assert( + ![...files.keys()].some( + (file) => file.startsWith("legacy/") || file.startsWith("supported-languages/"), + ), + ); + } +}); + +test("GitBook heading IDs preserve TypeDoc/generic deep links without changing code fences", () => { + const content = + "# `` component\n## FlagValueFromDefault\\\n## Properties\n## Properties\n```md\n# Leave code alone\n```\n"; + const rendered = anchorHeadings(content); + assert.match(rendered, /id="reflagprovider-component"/); + assert.match(rendered, /id="flagvaluefromdefaultt"/); + assert.match(rendered, /id="properties-1"/); + assert(rendered.includes("```md\n# Leave code alone\n```")); +}); + +test("the current-version line stays in the introduction without entering code fences", () => { + const content = "# SDK\n\nIntroduction.\n\n```md\n## Code example\n```\n\n## Setup\n"; + const rendered = anchorHeadings(content, { introNote: currentVersionNote }); + assert(rendered.includes("```md\n## Code example\n```")); + assert(rendered.indexOf(`\`\`\`\n\n${currentVersionNote}`) > rendered.indexOf("## Code example")); + assert(rendered.indexOf(currentVersionNote) < rendered.indexOf("## Setup")); + assert.equal(rendered.split(currentVersionNote).length - 1, 1); +}); + +test("GitBook keeps deep API-member and linked-section anchors without outlining every parameter label", () => { + const rendered = anchorHeadings( + "### Client\n#### Constructors\n##### getFlag()\n###### Parameters\n[Constructor](globals.md#constructors)\n", + ); + assert.match(rendered, /^### Constructors { + const rendered = anchorHeadings( + "### Client\n##### logger\n##### flagOverrides\n### Logger\n### FlagOverrides\n[Type](globals.md#logger)\n", + ); + assert.match(rendered, /^### logger { + const { source, options, destination } = fixture(t); + fs.unlinkSync(path.join(source, "dist/docs/@reflag/react-sdk/globals.md")); + assert.throws(() => applyPlan(planPackage(options), destination), /ENOENT/); + assert(!fs.existsSync(destination)); +}); + +test("manifest check detects manual generated-content changes", (t) => { + const { options, destination, put } = fixture(t); + const plan = planPackage(options); + applyPlan(plan, destination); + put(path.join(destination, "supported-languages/react-sdk/README.md"), "edited"); + assert.throws( + () => applyPlan(plan, destination, { check: true }), + /Generated documentation differs/, + ); +}); + +test("unknown owners and majors fail closed", (t) => { + const { options } = fixture(t); + assert.throws( + () => planPackage({ ...options, name: "../../escape" }), + /Unknown documentation owner/, + ); + assert.throws(() => docsPath("react-sdk", 3), /Unmapped SDK major/); + assert.throws(() => planPackage({ ...options, commit: "main" }), /full SDK source commit/); +}); + +test("negative link controls catch missing files and anchors; generic headings remain addressable", (t) => { + const { destination, put } = fixture(t); + put(path.join(destination, "page.md"), "[missing](other.md)\n"); + assert.throws(() => checkLinks(destination, ["page.md"]), /Missing file/); + put(path.join(destination, "other.md"), "# FlagValueFromDefault\\\n"); + put(path.join(destination, "page.md"), "[missing](other.md#nope)\n"); + assert.throws(() => checkLinks(destination, ["page.md"]), /Missing anchor/); + assert( + anchors(fs.readFileSync(path.join(destination, "other.md"), "utf8")).has( + "flagvaluefromdefaultt", + ), + ); +}); + +test("release sync requires the exact clean tagged source and rejects prereleases before writes", (t) => { + const { source, options, put } = fixture(t); + const git = (...args) => + execFileSync("git", ["-C", source, ...args], { encoding: "utf8" }).trim(); + git("init", "--quiet"); + git("add", "."); + git( + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--quiet", + "-m", + "Fixture", + ); + const sourceCommit = git("rev-parse", "HEAD"); + const plan = { + sourceCommit, + releases: [{ name: "@reflag/react-sdk", version: "2.0.0" }], + }; + git("tag", "@reflag/react-sdk@2.0.0"); + assert(releaseFiles(source, plan).has("supported-languages/react-sdk/README.md")); + assert.throws( + () => releaseFiles(source, { ...plan, sourceCommit: options.commit }), + /source changed/, + ); + assert.throws( + () => + releaseFiles(source, { + ...plan, + releases: [...plan.releases, ...plan.releases], + }), + /Duplicate package/, + ); + put( + path.join(source, "packages/react-sdk/package.json"), + JSON.stringify({ name: "@reflag/react-sdk", version: "2.0.1-next.0" }), + ); + assert.throws(() => releaseFiles(source, plan), /must be clean/); + git("add", "."); + git( + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--quiet", + "-m", + "Prerelease", + ); + assert.throws( + () => + releaseFiles(source, { + sourceCommit: git("rev-parse", "HEAD"), + releases: [{ name: "@reflag/react-sdk", version: "2.0.1-next.0" }], + }), + /Prereleases cannot promote/, + ); +}); + +test("this change does not introduce a GitBook variant picker or alternate site mapping", () => { + assert(!fs.existsSync(path.join(root, ".gitbook.yaml")), "No new per-space root mapping"); + assert(!fs.readFileSync(path.join(root, "SUMMARY.md"), "utf8").includes("v2-candidate/")); +}); diff --git a/.github/workflows/sdk-docs.yml b/.github/workflows/sdk-docs.yml new file mode 100644 index 0000000..8dfd1d6 --- /dev/null +++ b/.github/workflows/sdk-docs.yml @@ -0,0 +1,34 @@ +name: SDK documentation + +on: + pull_request: + paths: + - "**/*.md" + - .generated/** + - .github/scripts/** + - .github/workflows/sdk-docs.yml + - gitbook-docs.yaml + push: + branches: [main] + paths: + - .github/scripts/** + - .github/workflows/sdk-docs.yml + +permissions: + contents: read + +jobs: + check: + name: Importer safety and existing navigation + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + - run: node --test .github/scripts/sdk-docs.test.mjs + - run: node .github/scripts/check-sdk-docs.mjs + - name: Report public-content cutover readiness without publishing + run: node .github/scripts/sdk-docs.mjs ready