diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8c7dadb..d5ae4f0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,6 +1,6 @@ name: CI -# Pull-request checks. Deploys belong to deploy.yml (push to main/staging). +# Pull-request checks. Deployments require an explicit workflow dispatch. on: pull_request: branches: [main, staging] @@ -11,7 +11,6 @@ concurrency: permissions: contents: read - packages: read jobs: checks: @@ -30,8 +29,6 @@ jobs: - name: Install run: pnpm install --frozen-lockfile - env: - NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Typecheck run: pnpm typecheck @@ -48,7 +45,7 @@ jobs: - name: Report production client bundle sizes run: pnpm bundle:report - - name: Build staging and verify isolated R2 binding + - name: Build staging and verify isolated Worker configuration run: | pnpm build:staging node scripts/check-deploy-config.mjs staging diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 418937e..26ffc69 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -24,7 +24,6 @@ concurrency: permissions: contents: read - packages: read jobs: authorize-release: @@ -68,7 +67,7 @@ jobs: shell: bash run: | if [[ "$RELEASE_READY" != "true" ]]; then - echo "::error::Documentation release blocked. Verify Cloudflare R2, domain, secrets and manifests, then set DOCS_RELEASE_READY=true in this GitHub Environment." + echo "::error::Documentation release blocked. Verify Cloudflare domain and credentials, then set DOCS_RELEASE_READY=true in this GitHub Environment." exit 1 fi @@ -86,10 +85,8 @@ jobs: node-version: 24 cache: pnpm - - name: Install with private package read permission + - name: Install run: pnpm install --frozen-lockfile - env: - NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Typecheck run: pnpm typecheck @@ -139,6 +136,10 @@ jobs: test "$landing" = "200 1 $URL/docs/assay" curl --fail --silent --show-error "$URL/docs/assay" >/dev/null curl --fail --silent --show-error "$URL/docs/throughline" >/dev/null + curl --fail --silent --show-error "$URL/docs/assay.md" --location >/dev/null + curl --fail --silent --show-error "$URL/llms.mdx/docs/throughline" >/dev/null + missing="$(curl --silent --show-error --output /dev/null --write-out '%{http_code}' "$URL/docs/nonexistent-smoke-test")" + test "$missing" = "404" curl --fail --silent --show-error "$URL/llms.txt" >/dev/null curl --fail --silent --show-error "$URL/llms-full.txt" >/dev/null curl --fail --silent --show-error "$URL/robots.txt" >/dev/null diff --git a/.npmrc b/.npmrc deleted file mode 100644 index 914c936..0000000 --- a/.npmrc +++ /dev/null @@ -1,2 +0,0 @@ -@0xbuffdev:registry=https://npm.pkg.github.com -//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN} diff --git a/README.md b/README.md index 5d92d02..e257a08 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 0xBUFF Documentation -Public documentation for 0xBUFF products, built with React Router 8, Fumadocs MDX and Cloudflare Workers. Articles are maintained in `content/docs/`; the published **product catalog** is read at runtime from the private 0xBUFF R2 content bucket. The documentation Worker does not access 0xNAND's private learning content or assessment assets. +Public documentation for 0xBUFF products, built with React Router 8, Fumadocs MDX and Cloudflare Workers. Articles and navigation live in `content/docs/`. The app compiles and serves this public collection without a runtime content store. ## Documentation organization @@ -25,7 +25,7 @@ content/docs/ - The root `content/docs/meta.json` lists Assay first, then Throughline and uses Fumadocs' `"..."` entry to include future tools automatically. - Give every tool its own `content/docs//` directory with an `index.mdx` and `meta.json`. Set `"root": true` in the tool's metadata so its navigation is separate from other tools. Give it a clear title, a short description, and an explicit `pages` order. Section separators such as `"---Reference---"` group related pages without changing URLs. - Use stable filenames: Fumadocs derives each public address from its MDX path. Navigation changes must not unnecessarily change existing addresses. -- New tools also need a published product entry in the R2 catalog, with no outbound `url`, before they appear on the public site. Content files alone do not publish a product. +- Add only material intended for public release. Every MDX article in the collection is public after deployment and is eligible for search and LLM exports. - Keep product-specific descriptions in the product's own MDX and metadata. Shared site metadata must describe the full documentation library. The navigation validation tests run with `pnpm test`. They verify tool roots, declared pages, and document frontmatter. @@ -36,20 +36,16 @@ Selected Throughline guides render the published `@0xbuff/throughline@0.0.2` Rea The showcase is deliberately limited to a few pages and does not automatically transform every `thl` code fence. The official `remarkThroughline({ mode: "mdx" })` integration and `ThroughlineEmbed` require a subsequent package release; v0.0.2 must not be assumed to contain them. This preserves portable source examples and avoids unnecessary client JavaScript. `scripts/throughline-interactive.test.mjs` compiles every showcased trace with the installed package; CI also typechecks and builds both environments. -## Content ownership and publication +## Routing and publication -The private `0xbuffdev/content` repository owns the product records and publishes them to independent 0xBUFF buckets via its validated content pipeline. Documentation reads `manifest.json` and the referenced `products/manifest.json` through its Worker `CONTENT` R2 binding and validates them with `@0xbuffdev/content-contract@0.1.0` (imported as `@0xbuff/content-contract`). +Fumadocs builds the page tree, search index, sitemap and Markdown exports from the local MDX collection. Both `/` and `/docs` redirect directly to `/docs/assay`. Unknown articles return HTTP 404. Updating the collection requires a documentation deployment; the company product catalog is independent. -Only published product records with **no outbound `url`** and a matching `content/docs//index.mdx` are listed. The R2 catalog controls documentation routes, sidebar, sitemap, search index and LLM exports. Both `/` and `/docs` temporarily redirect directly to `/docs/assay` in one hop, only when Assay is published. Missing Assay returns 503 rather than falling back to another tool. Publish the Assay catalog record to each target R2 bucket before deploying this change. The MDX articles themselves are compiled from this repository and require a documentation deployment to update. Catalog changes appear after the 60-second edge cache expires; no documentation rebuild is needed for catalog changes alone. +| Target | Worker | Public domain | +| --- | --- | --- | +| Staging | `0xbuff-docs-staging` | `staging.docs.0xbuff.com` | +| Production | `0xbuff-docs` | `docs.0xbuff.com` | -The two production-facing buckets are **not interchangeable**: - -| Target | Worker | Public domain | Private `CONTENT` bucket | -| --- | --- | --- | --- | -| Staging | `0xbuff-docs-staging` | `staging.docs.0xbuff.com` | `content-staging` | -| Production | `0xbuff-docs` | `docs.0xbuff.com` | `content` | - -The top-level Wrangler configuration is production. `env.staging` overrides the domain, bucket, and `DOCS_ENV` binding. `DOCS_ENV` also isolates cached manifests. +The top-level Wrangler configuration is production. `env.staging` overrides the domain and `DOCS_ENV` value. ## Development @@ -59,25 +55,10 @@ Node 24 and pnpm 11.2.2 are required. pnpm install pnpm typecheck pnpm test -``` - -GitHub Packages read permission is required for the private content contract. The tracked `.npmrc` scopes the registry; supply an appropriate read-only `NODE_AUTH_TOKEN` locally. **Never commit a token.** GitHub Actions uses `GITHUB_TOKEN` with `packages: read`; grant this repository Actions read permission in the private package's settings. - -For local development, build and partition the **Content** repository first (from that repository): - -```bash -pnpm run build:content -node scripts/publish-targets.ts -``` - -From this documentation repository, seed only the **local** Miniflare R2 state using the resulting 0xBUFF partition: - -```bash -pnpm seed:content /absolute/path/to/content/.cache/publish/0xbuff pnpm dev ``` -The seed command validates the published manifest and uploads `manifest.json` and `products/manifest.json` to the local `content` bucket with Wrangler `--local`. It never writes to remote R2. Re-seed after changing local product metadata. Set local `RESEND_API_KEY` in an untracked `.dev.vars` only when newsletter testing is necessary; `.dev.vars.example` documents it. +No private registry credentials or content seeding are required. Set local `RESEND_API_KEY` in an untracked `.dev.vars` only when newsletter testing is necessary; `.dev.vars.example` documents it. ## Build and deployment @@ -90,27 +71,27 @@ pnpm build:staging - `pnpm build`: production target, using top-level Wrangler settings. - `pnpm build:staging`: selects `env.staging` with `CLOUDFLARE_ENV=staging` **during the Vite build**. - `pnpm bundle:report`: prints compressed JS/CSS asset sizes, largest first. The sum of all chunks is **not** the initial browser download; route-level MDX and Mermaid remain lazy, and the search dialog is deferred. -- `scripts/check-deploy-config.mjs staging|production`: asserts the generated `build/server/wrangler.json` carries the intended Worker name, custom domain, runtime environment, and R2 bucket. +- `scripts/check-deploy-config.mjs staging|production`: asserts the generated `build/server/wrangler.json` carries the intended Worker name, custom domain, runtime environment, and absence of R2 bindings. With the Cloudflare Vite plugin, `wrangler deploy` uses the generated deployment config; `wrangler deploy --env staging` **must not** be used after the build. Code merges do **not** deploy to Cloudflare. The deployment workflow follows 0xNAND's explicit release boundary: 1. Merge the reviewed and signed code into `main` after CI passes. This alone does not deploy either environment. -2. Set up GitHub Environments named `staging` and `production`. Verify each environment's R2 content, domain, credentials, and Worker secrets. Set environment variable `DOCS_RELEASE_READY=true` **only after** verifying that environment. -3. Run **Actions → Deploy Documentation → Run workflow** from the `main` branch, choose `staging`, and enter `DEPLOY_STAGING`. The workflow checks readiness, builds the staging environment, confirms the generated binding, deploys, and probes the live endpoints. +2. Set up GitHub Environments named `staging` and `production`. Verify each environment's domain, credentials, and any newsletter secrets. Set environment variable `DOCS_RELEASE_READY=true` **only after** verifying that environment. +3. Run **Actions → Deploy Documentation → Run workflow** from the `main` branch, choose `staging`, and enter `DEPLOY_STAGING`. The workflow checks readiness, builds the staging environment, checks the generated Worker configuration, deploys, and probes the live endpoints. 4. Once staging is verified, dispatch the same workflow from `main` targeting `production` with `DEPLOY_PRODUCTION` and a separately verified production environment (`DOCS_RELEASE_READY=true`). -Pull requests continue to typecheck, test, build **both** target configurations, verify the generated R2 bindings and report client asset sizes without deploying. +Pull requests continue to typecheck, test, build **both** target configurations, verify the generated Worker configuration and report client asset sizes without deploying. Cloudflare deployment requires repository secrets `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` with the minimum permissions for Workers and the configured custom domains. Newsletter `RESEND_API_KEY` is a **Worker secret**, set independently for the production and staging Workers. The staging `RESEND_SEGMENT_ID` is intentionally empty to prevent accidental subscriptions to the production audience; configure a separate staging segment before testing signup delivery. -Before either deployment, independently confirm the relevant R2 bucket exists, contains a valid `manifest.json` and `products/manifest.json`, is accessible to that Worker's `CONTENT` binding, and that Cloudflare domains and credentials are provisioned. CI cannot create or verify those Cloudflare resources by reading the repository. The deployment smoke tests verify both redirects and request `/docs/assay` to check real R2 access, plus the LLM, search, robots, sitemap and subscription routes. Staging serves `robots.txt` with `Disallow: /` and sets `X-Robots-Tag: noindex, nofollow, noarchive` on Worker responses. +Before either deployment, confirm the Cloudflare domain and credentials are provisioned. The deployment smoke tests verify both redirects, Assay and Throughline pages, a missing page, Markdown exports, LLM indexes, search, robots, sitemap and subscription routes. Staging serves `robots.txt` with `Disallow: /` and sets `X-Robots-Tag: noindex, nofollow, noarchive` on Worker responses. ## Bundle strategy -Fumadocs MDX uses `async: true`, so individual documents are compiled into page-level lazy chunks. Mermaid loads through a dynamic import when a diagram mounts. The search UI is also loaded on demand; the content search index is fetched from the same R2-authorized product set and cached briefly. The bundle report provides reproducible size evidence in pull-request and deploy workflows. Compare it with a browser network waterfall before claiming any percentage reduction in initial transfer or setting budgets. +Fumadocs MDX uses `async: true`, so individual documents are compiled into page-level lazy chunks. Mermaid loads through a dynamic import when a diagram mounts. The search UI is also loaded on demand; the search index is generated from the compiled MDX collection and cached briefly. The bundle report provides reproducible size evidence in pull-request and deploy workflows. Compare it with a browser network waterfall before claiming any percentage reduction in initial transfer or setting budgets. ## Worker types -`worker-configuration.d.ts` is generated locally by `wrangler types` and is intentionally **not tracked**. `pnpm typecheck` regenerates it before React Router types and the TypeScript compiler run; run `pnpm exec wrangler types` separately after changing bindings if editor types need refreshing. `opencode.json` is also ignored as machine-specific OpenCode configuration. The `CONTENT` R2 binding and `DOCS_ENV` are accessed server-side only, and no R2 credentials are shipped to the browser. +`worker-configuration.d.ts` is generated locally by `wrangler types` and is intentionally **not tracked**. `pnpm typecheck` regenerates it before React Router types and the TypeScript compiler run; run `pnpm exec wrangler types` separately after changing bindings if editor types need refreshing. `opencode.json` is also ignored as machine-specific OpenCode configuration. The `DOCS_ENV` value is used server-side to keep staging out of search indexes. diff --git a/package.json b/package.json index 523f415..419b3bf 100644 --- a/package.json +++ b/package.json @@ -19,8 +19,7 @@ "typecheck": "wrangler types && react-router typegen && tsc", "test": "node --test scripts/*.test.mjs && node --experimental-strip-types --test src/lib/*.test.ts", "bundle:report": "node scripts/report-bundle.mjs", - "build:staging": "node scripts/build-env.mjs staging", - "seed:content": "node scripts/seed-content.mjs" + "build:staging": "node scripts/build-env.mjs staging" }, "dependencies": { "@fontsource-variable/dm-sans": "^5.3.0", @@ -49,7 +48,6 @@ "takumi-js": "^2.13.1", "tw-animate-css": "^1.4.0", "zod": "^4.4.3", - "@0xbuff/content-contract": "npm:@0xbuffdev/content-contract@0.1.0", "@0xbuff/throughline": "0.0.2" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9248d88..e81259c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,9 +8,6 @@ importers: .: dependencies: - '@0xbuff/content-contract': - specifier: npm:@0xbuffdev/content-contract@0.1.0 - version: '@0xbuffdev/content-contract@0.1.0' '@0xbuff/throughline': specifier: 0.0.2 version: 0.0.2(react-dom@19.3.1(react@19.3.1))(react@19.3.1) @@ -138,9 +135,6 @@ packages: react-dom: optional: true - '@0xbuffdev/content-contract@0.1.0': - resolution: {integrity: sha512-hKh8qOBHPEwFNKrGhVt8tNrU2psqSKDxt0GkOcMERCE9f6d/imQJBhbiVEXHtsIPZuIFIQzrOaNdNgXldyfB7Q==, tarball: https://npm.pkg.github.com/download/@0xbuffdev/content-contract/0.1.0/6b9d70e4ee7c488df28fe78d7095e7ad5dd63c94} - '@antfu/install-pkg@2.1.0': resolution: {integrity: sha512-sdg9NxU3zR4Mnawfbc/x6GB5Wf17WYud5qOuEuxXjaKpYpMkISSJEjItGebXJ2bQ4DIcly4NYH23mtkGJjvKUw==} @@ -4645,10 +4639,6 @@ snapshots: react: 19.3.1 react-dom: 19.3.1(react@19.3.1) - '@0xbuffdev/content-contract@0.1.0': - dependencies: - zod: 4.6.7 - '@antfu/install-pkg@2.1.0': dependencies: package-manager-detector: 1.9.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 37136a4..7e9bf9d 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,7 +1,6 @@ # Reviewed first-party releases are explicitly pinned below. # All other dependencies retain pnpm 11's default 24-hour release-age policy. minimumReleaseAgeExclude: - - '@0xbuffdev/content-contract@0.1.0' - '@0xbuff/throughline@0.0.2' # Reviewed native toolchain install scripts; unlisted builds remain blocked. diff --git a/react-router.config.ts b/react-router.config.ts index 073e8b2..2a9f708 100644 --- a/react-router.config.ts +++ b/react-router.config.ts @@ -1,6 +1,6 @@ import type { Config } from "@react-router/dev/config"; -/** R2-backed pages are served by the Worker, never prerendered at build time. */ +/** Render the compiled MDX collection through the Worker. */ export default { ssr: true, appDirectory: "src", diff --git a/scripts/check-deploy-config.mjs b/scripts/check-deploy-config.mjs index acf4cbe..e5e6800 100644 --- a/scripts/check-deploy-config.mjs +++ b/scripts/check-deploy-config.mjs @@ -6,31 +6,22 @@ const expected = { staging: { name: "0xbuff-docs-staging", domain: "staging.docs.0xbuff.com", - bucket: "content-staging", }, production: { name: "0xbuff-docs", domain: "docs.0xbuff.com", - bucket: "content", }, }[target]; if (!expected) throw new Error("Expected staging or production target"); -const config = JSON.parse( - await readFile("build/server/wrangler.json", "utf8"), -); +const config = JSON.parse(await readFile("build/server/wrangler.json", "utf8")); assert.equal(config.name, expected.name, "Incorrect Worker target"); assert.equal(config.vars?.DOCS_ENV, target, "Incorrect runtime environment"); -assert.deepEqual(config.r2_buckets, [ - { binding: "CONTENT", bucket_name: expected.bucket }, -]); +assert.deepEqual(config.r2_buckets ?? [], [], "Documentation must not bind R2"); assert.ok( config.routes?.some( - (route) => - route.pattern === expected.domain && route.custom_domain === true, + (route) => route.pattern === expected.domain && route.custom_domain === true, ), "Incorrect Worker custom domain", ); -console.log( - `Verified ${config.name} → ${expected.domain} with R2 CONTENT=${expected.bucket}`, -); +console.log(`Verified ${config.name} → ${expected.domain} without R2 bindings`); diff --git a/scripts/deploy-config.test.mjs b/scripts/deploy-config.test.mjs new file mode 100644 index 0000000..51a6a6d --- /dev/null +++ b/scripts/deploy-config.test.mjs @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import { readFile, readdir } from "node:fs/promises"; +import { join } from "node:path"; +import test from "node:test"; + +const config = JSON.parse(await readFile("wrangler.jsonc", "utf8")); + +test("staging and production have independent domains and no R2 dependency", () => { + assert.equal(config.name, "0xbuff-docs"); + assert.deepEqual(config.r2_buckets ?? [], []); + assert.equal(config.vars.DOCS_ENV, "production"); + assert.deepEqual(config.env.staging.r2_buckets ?? [], []); + assert.equal(config.env.staging.vars.DOCS_ENV, "staging"); + assert.equal(config.routes[0].pattern, "docs.0xbuff.com"); + assert.equal(config.env.staging.routes[0].pattern, "staging.docs.0xbuff.com"); + assert.equal(config.env.staging.vars.RESEND_SEGMENT_ID, ""); +}); + +async function sourceFiles(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const files = await Promise.all(entries.map(async (entry) => { + const path = join(directory, entry.name); + return entry.isDirectory() ? sourceFiles(path) : [path]; + })); + return files.flat(); +} + +test("documentation builds without the private content package or catalog", async () => { + const manifest = JSON.parse(await readFile("package.json", "utf8")); + assert.equal(manifest.scripts["seed:content"], undefined); + for (const group of [manifest.dependencies, manifest.devDependencies]) { + assert.ok(!Object.keys(group).some((name) => name.includes("content-contract"))); + } + assert.doesNotMatch(await readFile("pnpm-lock.yaml", "utf8"), /content-contract|npm\.pkg\.github\.com/); + for (const path of [...await sourceFiles("src"), ...await sourceFiles("workers")]) { + if (!/\.[jt]sx?$/.test(path)) continue; + assert.doesNotMatch(await readFile(path, "utf8"), /getDocumentedProducts|catalog\.server|@0xbuff\/content-contract|R2Bucket/, path); + } +}); diff --git a/scripts/r2-config.test.mjs b/scripts/r2-config.test.mjs deleted file mode 100644 index 65be1a5..0000000 --- a/scripts/r2-config.test.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import assert from "node:assert/strict"; -import { readFile } from "node:fs/promises"; -import test from "node:test"; - -const config = JSON.parse(await readFile("wrangler.jsonc", "utf8")); - -test("production and staging use distinct published 0xBUFF buckets", () => { - assert.equal(config.name, "0xbuff-docs"); - assert.deepEqual(config.r2_buckets, [{ binding: "CONTENT", bucket_name: "content" }]); - assert.equal(config.vars.DOCS_ENV, "production"); - assert.deepEqual(config.env.staging.r2_buckets, [ - { binding: "CONTENT", bucket_name: "content-staging" }, - ]); - assert.equal(config.env.staging.vars.DOCS_ENV, "staging"); - assert.equal(config.routes[0].pattern, "docs.0xbuff.com"); - assert.equal(config.env.staging.routes[0].pattern, "staging.docs.0xbuff.com"); - assert.notEqual( - config.env.staging.r2_buckets[0].bucket_name, - config.r2_buckets[0].bucket_name, - ); - assert.equal(config.env.staging.vars.RESEND_SEGMENT_ID, ""); -}); diff --git a/scripts/seed-content.mjs b/scripts/seed-content.mjs deleted file mode 100644 index b0b1997..0000000 --- a/scripts/seed-content.mjs +++ /dev/null @@ -1,54 +0,0 @@ -import { spawnSync } from "node:child_process"; -import { readFile } from "node:fs/promises"; -import path from "node:path"; - -const source = process.argv[2] ?? process.env.CONTENT_PUBLISH_DIR; -if (!source) { - throw new Error( - "Usage: pnpm seed:content /absolute/path/to/content/.cache/publish/0xbuff", - ); -} - -const root = path.resolve(source); -const topPath = path.join(root, "manifest.json"); -const top = JSON.parse(await readFile(topPath, "utf8")); -if (top.sections?.products !== "products/manifest.json") { - throw new Error("Expected a published 0xBUFF manifest with a products section"); -} - -const productsPath = path.join(root, top.sections.products); -const products = JSON.parse(await readFile(productsPath, "utf8")); -if (!Array.isArray(products.items) || products.count !== products.items.length) { - throw new Error("Invalid published products manifest"); -} - -const config = JSON.parse(await readFile("wrangler.jsonc", "utf8")); -const bucket = config.r2_buckets?.find((item) => item.binding === "CONTENT")?.bucket_name; -if (!bucket) throw new Error("Missing local CONTENT bucket name"); - -const command = process.platform === "win32" ? "pnpm.cmd" : "pnpm"; -for (const [key, file] of [ - ["products/manifest.json", productsPath], - ["manifest.json", topPath], -]) { - const args = [ - "exec", - "wrangler", - "r2", - "object", - "put", - `${bucket}/${key}`, - "--file", - file, - "--local", - "--content-type", - "application/json", - ]; - const result = spawnSync(command, args, { - stdio: "inherit", - shell: process.platform === "win32", - }); - if (result.error) throw result.error; - if (result.status !== 0) process.exit(result.status ?? 1); -} -console.log(`Seeded local CONTENT (${bucket}) from ${root}; no remote buckets modified`); diff --git a/src/lib/catalog.server.ts b/src/lib/catalog.server.ts deleted file mode 100644 index 9b4876d..0000000 --- a/src/lib/catalog.server.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { - ProductSchema, - sectionManifestSchema, - TopManifestSchema, -} from "@0xbuff/content-contract"; -import type { RouterContextProvider } from "react-router"; -import { cloudflareContext } from "./cloudflare-context"; -import { source } from "./source"; -import { selectDocumentedProducts } from "./published-products"; - -const MANIFEST_TTL = 60; - -async function readManifest( - bucket: R2Bucket, - key: string, - environment: string, - ctx: ExecutionContext, -): Promise { - const cache = (globalThis as typeof globalThis & { - caches?: { default?: Cache }; - }).caches?.default; - const cacheKey = `https://${environment}.docs-content.invalid/${key}`; - let raw: string | undefined; - - if (cache) { - try { - const cached = await cache.match(cacheKey); - if (cached) raw = await cached.text(); - } catch { - // Cache is best-effort; R2 remains authoritative. - } - } - if (raw === undefined) { - const object = await bucket.get(key); - if (!object) throw new Error(`[documentation] missing R2 content: ${key}`); - raw = await object.text(); - if (cache) { - ctx.waitUntil( - cache - .put( - cacheKey, - new Response(raw, { - headers: { - "Content-Type": "application/json; charset=utf-8", - "Cache-Control": `public, max-age=${MANIFEST_TTL}`, - }, - }), - ) - .catch(() => {}), - ); - } - } - - try { - return JSON.parse(raw); - } catch { - throw new Error(`[documentation] invalid JSON in R2 content: ${key}`); - } -} - -export async function getDocumentedProducts( - context: Readonly, -): Promise> { - const { env, ctx } = context.get(cloudflareContext); - const bucket = (env as Env & { CONTENT?: R2Bucket }).CONTENT; - if (!bucket) { - throw new Error("[documentation] R2 CONTENT binding is missing"); - } - - const environment = (env as { DOCS_ENV?: string }).DOCS_ENV; - if (environment !== "development" && environment !== "staging" && environment !== "production") { - throw new Error("[documentation] invalid DOCS_ENV"); - } - - const top = TopManifestSchema.parse( - await readManifest(bucket, "manifest.json", environment, ctx), - ); - if (top.sections.products !== "products/manifest.json") { - throw new Error("[documentation] R2 manifest does not publish products"); - } - const manifest = sectionManifestSchema(ProductSchema).parse( - await readManifest(bucket, top.sections.products, environment, ctx), - ); - if (manifest.count !== manifest.items.length) { - throw new Error("[documentation] product manifest count mismatch"); - } - - return selectDocumentedProducts(manifest.items, (slug) => source.getPage([slug]) != null); -} diff --git a/src/lib/docs-entry.server.ts b/src/lib/docs-entry.server.ts index 83dd382..529d8b8 100644 --- a/src/lib/docs-entry.server.ts +++ b/src/lib/docs-entry.server.ts @@ -1,15 +1,8 @@ import { redirect } from "react-router"; -import { hasDefaultDocsProduct } from "./docs-navigation"; -import { ROUTES } from "./site"; +import { defaultDocsLocation } from "./docs-navigation"; -export function redirectToDefaultDocs(request: Request, published: readonly { slug: string }[]) { - if (!hasDefaultDocsProduct(published)) { - throw new Response("Default documentation is not published", { - status: 503, - headers: { "Cache-Control": "no-store" }, - }); - } - return redirect(ROUTES.docsDefault + new URL(request.url).search, { +export function redirectToDefaultDocs(request: Request) { + return redirect(defaultDocsLocation(request.url), { status: 302, headers: { "Cache-Control": "no-store" }, }); diff --git a/src/lib/docs-navigation.test.ts b/src/lib/docs-navigation.test.ts index e819327..0430f31 100644 --- a/src/lib/docs-navigation.test.ts +++ b/src/lib/docs-navigation.test.ts @@ -1,28 +1,21 @@ import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; import test from "node:test"; -import type { Root } from "fumadocs-core/page-tree"; -import { DEFAULT_DOCS_PRODUCT, filterPublishedProductRoots, hasDefaultDocsProduct } from "./docs-navigation.ts"; +import { DEFAULT_DOCS_PATH, DEFAULT_DOCS_PRODUCT, defaultDocsLocation } from "./docs-navigation.ts"; -test("Assay is the explicit default regardless of catalog ordering", () => { +test("the default product has a local MDX overview and appears first in navigation", async () => { assert.equal(DEFAULT_DOCS_PRODUCT, "assay"); - assert.equal(hasDefaultDocsProduct([{ slug: "throughline" }, { slug: "assay" }]), true); - assert.equal(hasDefaultDocsProduct([{ slug: "assay" }, { slug: "throughline" }]), true); - assert.equal(hasDefaultDocsProduct([{ slug: "throughline" }]), false); - assert.equal(hasDefaultDocsProduct([]), false); + assert.equal(DEFAULT_DOCS_PATH, "/docs/assay"); + const root = new URL("../../content/docs/", import.meta.url); + const meta = JSON.parse(await readFile(new URL("meta.json", root), "utf8")); + assert.equal(meta.pages[0], DEFAULT_DOCS_PRODUCT); + const overview = await readFile(new URL(`${DEFAULT_DOCS_PRODUCT}/index.mdx`, root), "utf8"); + assert.match(overview, /^---\r?\n/); }); -test("published product folders retain index-only roots and exclude unpublished roots", () => { - const page = (slug: string) => ({ type: "page" as const, name: slug, url: `/docs/${slug}` }); - const tree: Root = { - name: "Docs", - children: [ - { type: "folder", name: "Assay", root: true, index: page("assay"), children: [] }, - { type: "folder", name: "Throughline", root: true, children: [page("throughline")] }, - { type: "folder", name: "Unpublished", root: true, index: page("unpublished"), children: [] }, - ], - }; - const filtered = filterPublishedProductRoots(tree, new Set(["/docs/assay", "/docs/throughline"])); - assert.deepEqual(filtered.children.map((node) => node.name), ["Assay", "Throughline"]); - assert.equal(tree.children.length, 3); - assert.deepEqual(filterPublishedProductRoots(tree, new Set()).children, []); +test("both entry paths resolve directly to Assay and preserve query strings", () => { + for (const path of ["/", "/docs", "/docs/"]) { + assert.equal(defaultDocsLocation(`https://docs.0xbuff.com${path}`), "/docs/assay"); + assert.equal(defaultDocsLocation(`https://docs.0xbuff.com${path}?q=a%20b&x=1`), "/docs/assay?q=a%20b&x=1"); + } }); diff --git a/src/lib/docs-navigation.ts b/src/lib/docs-navigation.ts index 2ef5f04..b243206 100644 --- a/src/lib/docs-navigation.ts +++ b/src/lib/docs-navigation.ts @@ -1,20 +1,7 @@ -import type { Root } from "fumadocs-core/page-tree"; - export const DEFAULT_DOCS_PRODUCT = "assay"; +export const DEFAULT_DOCS_PATH = `/docs/${DEFAULT_DOCS_PRODUCT}`; -export function hasDefaultDocsProduct(published: readonly { slug: string }[]): boolean { - return published.some(({ slug }) => slug === DEFAULT_DOCS_PRODUCT); -} - -/** Keep only authorized product roots, including Fumadocs folder index pages. */ -export function filterPublishedProductRoots(tree: Root, availableUrls: ReadonlySet): Root { - const isPublished = (url: string) => availableUrls.has(url.replace(/\/$/, "")); - return { - ...tree, - children: tree.children.filter((node) => - node.type === "folder" && - ((node.index != null && isPublished(node.index.url)) || - node.children.some((child) => child.type === "page" && isPublished(child.url))), - ), - }; +/** Both entry routes redirect directly to the default MDX overview. */ +export function defaultDocsLocation(requestUrl: string): string { + return DEFAULT_DOCS_PATH + new URL(requestUrl).search; } diff --git a/src/lib/published-products.test.ts b/src/lib/published-products.test.ts deleted file mode 100644 index 09aa837..0000000 --- a/src/lib/published-products.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import type { Product } from "@0xbuff/content-contract"; -import { selectDocumentedProducts } from "./published-products.ts"; - -function product( - slug: string, - pid: string, - options: { url?: string; kicker?: string } = {}, -): Product { - return { - slug, - pid, - hash: "abcdef12", - file: `${slug}.abcdef12.md`, - name: slug, - status: "alpha", - kicker: options.kicker ?? "A practical tool", - description: "Detailed description", - features: [{ title: "Feature", description: "Details" }], - ...(options.url ? { url: options.url } : {}), - }; -} - -test("only products with local docs and no destination are rendered in pid order", () => { - const entries = [ - product("throughline", "0x03"), - product("external-tool", "0x01", { url: "https://example.com" }), - product("not-documented", "0x02"), - product("yes", "0x04"), - product("../invalid", "0x05"), - ]; - const selected = selectDocumentedProducts(entries, (slug) => - ["throughline", "yes"].includes(slug), - ); - assert.deepEqual(selected.map((p) => p.slug), ["throughline", "yes"]); - assert.equal(selected[0].tagline, "A practical tool"); - assert.equal("file" in selected[0], false); - assert.equal("features" in selected[0], false); -}); - -test("rejects conflicting pids and slugs even on hidden products", () => { - assert.throws( - () => selectDocumentedProducts([product("one", "0x01"), product("two", "0x01")], () => true), - /duplicate product identifiers/, - ); - assert.throws( - () => selectDocumentedProducts([product("one", "0x01"), product("one", "0x02")], () => true), - /duplicate product identifiers/, - ); -}); diff --git a/src/lib/published-products.ts b/src/lib/published-products.ts deleted file mode 100644 index 1b4c977..0000000 --- a/src/lib/published-products.ts +++ /dev/null @@ -1,42 +0,0 @@ -import type { Product } from "@0xbuff/content-contract"; - -export type DocumentedProduct = Pick< - Product, - "slug" | "pid" | "name" | "status" | "description" -> & { tagline: string }; - -/** - * Only cataloged products with a local documentation entry are published. - * Their identities and display copy come from R2; the MDX repo owns the pages. - */ -export function selectDocumentedProducts( - items: readonly Product[], - hasPage: (slug: string) => boolean, -): DocumentedProduct[] { - const pids = new Set(); - const slugs = new Set(); - for (const item of items) { - if (pids.has(item.pid) || slugs.has(item.slug)) { - throw new Error("[documentation] duplicate product identifiers in R2"); - } - pids.add(item.pid); - slugs.add(item.slug); - } - - return items - .filter( - (item) => - !item.url && - /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(item.slug) && - hasPage(item.slug), - ) - .map(({ slug, pid, name, status, kicker, description }) => ({ - slug, - pid, - name, - status, - tagline: kicker, - description, - })) - .sort((a, b) => a.pid.localeCompare(b.pid)); -} diff --git a/src/lib/site.ts b/src/lib/site.ts index 8afba27..9633fb0 100644 --- a/src/lib/site.ts +++ b/src/lib/site.ts @@ -1,5 +1,5 @@ import docsConfig from "./docs-config.json"; -import { DEFAULT_DOCS_PRODUCT } from "./docs-navigation"; +import { DEFAULT_DOCS_PATH } from "./docs-navigation"; /** * Canonical site identity, navigation, and static-route metadata for the docs @@ -59,7 +59,7 @@ export const ROUTES = { home: "/", docs: "/docs", /** Default product shown when navigating to /docs. */ - docsDefault: `/docs/${DEFAULT_DOCS_PRODUCT}`, + docsDefault: DEFAULT_DOCS_PATH, /** Legacy path. Redirected permanently to the canonical company-site manifesto. */ manifesto: "/manifesto", docsOg: docsConfig.docsImageRoute, diff --git a/src/routes/docs/$.tsx b/src/routes/docs/$.tsx index e5bcf5e..3a81fb8 100644 --- a/src/routes/docs/$.tsx +++ b/src/routes/docs/$.tsx @@ -15,25 +15,18 @@ import { baseOptions } from "../../lib/layout.shared"; import { createPageMeta } from "../../lib/meta"; import { createRelativeLink } from "../../lib/relative-link"; import { getPageImagePath } from "../../lib/shared"; -import { - CONTENT_DIRS, - ROUTES, - SITE, -} from "../../lib/site"; +import { CONTENT_DIRS, SITE } from "../../lib/site"; import { docs } from "../../lib/docs"; -import { filterPublishedProductRoots } from "../../lib/docs-navigation"; import { redirectToDefaultDocs } from "../../lib/docs-entry.server"; import { resolveDocPage, source } from "../../lib/source"; -import { getDocumentedProducts } from "../../lib/catalog.server"; import type { Route } from "./+types/$"; -export async function loader({ params, request, context }: Route.LoaderArgs) { - const published = await getDocumentedProducts(context); +export async function loader({ params, request }: Route.LoaderArgs) { const rawSlug = (params as Record)["*"] ?? ""; // Redirect bare /docs to the default product. if (rawSlug === "" || rawSlug === "/") { - throw redirectToDefaultDocs(request, published); + throw redirectToDefaultDocs(request); } const isMarkdownRequested = @@ -42,20 +35,12 @@ export async function loader({ params, request, context }: Route.LoaderArgs) { request.headers.get("Accept")?.includes("text/markdown"); const { page } = resolveDocPage(rawSlug); - if (!published.some(({ slug }) => slug === page.slugs[0])) { - throw new Response("Not found", { status: 404 }); - } - if (isMarkdownRequested) { throw redirect(`/llms.mdx/docs/${page.slugs.join("/")}`, { headers: { Vary: "Accept" }, }); } - const tree = source.getPageTree(); - const availableUrls = new Set(published.map(({ slug }) => `${ROUTES.docs}/${slug}`)); - const sidebarTree = filterPublishedProductRoots(tree, availableUrls); - return { toc: (await page.data.load()).toc as unknown as TOCItemType[], path: page.path, @@ -63,7 +48,7 @@ export async function loader({ params, request, context }: Route.LoaderArgs) { title: page.data.title, description: page.data.description, imagePath: getPageImagePath(page.slugs), - pageTree: await source.serializePageTree(sidebarTree), + pageTree: await source.serializePageTree(source.getPageTree()), }; } diff --git a/src/routes/index.tsx b/src/routes/index.tsx index f52ed9f..d498912 100644 --- a/src/routes/index.tsx +++ b/src/routes/index.tsx @@ -1,7 +1,6 @@ -import { getDocumentedProducts } from "../lib/catalog.server"; import { redirectToDefaultDocs } from "../lib/docs-entry.server"; import type { Route } from "./+types/index"; -export async function loader({ request, context }: Route.LoaderArgs) { - return redirectToDefaultDocs(request, await getDocumentedProducts(context)); +export function loader({ request }: Route.LoaderArgs) { + return redirectToDefaultDocs(request); } diff --git a/src/routes/llms-full[.]txt.ts b/src/routes/llms-full[.]txt.ts index fdaf4e8..977aa9d 100644 --- a/src/routes/llms-full[.]txt.ts +++ b/src/routes/llms-full[.]txt.ts @@ -1,11 +1,8 @@ import { getLLMText } from "../lib/get-llm-text"; import { source } from "../lib/source"; -import { getDocumentedProducts } from "../lib/catalog.server"; -import type { Route } from "./+types/llms-full[.]txt"; -export async function loader({ context }: Route.LoaderArgs) { - const allowed = new Set((await getDocumentedProducts(context)).map((p) => p.slug)); - const scan = source.getPages().filter((p) => allowed.has(p.slugs[0])).map(getLLMText); +export async function loader() { + const scan = source.getPages().map(getLLMText); const scanned = await Promise.all(scan); return new Response(scanned.join("\n\n---\n\n"), { diff --git a/src/routes/llms[.]mdx.docs.$.ts b/src/routes/llms[.]mdx.docs.$.ts index 6d79f7d..dfeb6a2 100644 --- a/src/routes/llms[.]mdx.docs.$.ts +++ b/src/routes/llms[.]mdx.docs.$.ts @@ -1,15 +1,10 @@ import { getLLMText } from "../lib/get-llm-text"; import { resolveDocPage } from "../lib/source"; -import { getDocumentedProducts } from "../lib/catalog.server"; import type { Route } from "./+types/llms[.]mdx.docs.$"; -export async function loader({ params, context }: Route.LoaderArgs) { +export async function loader({ params }: Route.LoaderArgs) { const rawSlug = (params as Record)["*"] ?? ""; const { page } = resolveDocPage(rawSlug); - const published = await getDocumentedProducts(context); - if (!published.some((product) => product.slug === page.slugs[0])) { - throw new Response("Not found", { status: 404 }); - } const content = await getLLMText(page); diff --git a/src/routes/llms[.]txt.ts b/src/routes/llms[.]txt.ts index 6710db3..d38fc70 100644 --- a/src/routes/llms[.]txt.ts +++ b/src/routes/llms[.]txt.ts @@ -1,11 +1,8 @@ -import { getDocumentedProducts } from "../lib/catalog.server"; import { SITE } from "../lib/site"; import { source } from "../lib/source"; -import type { Route } from "./+types/llms[.]txt"; -export async function loader({ context }: Route.LoaderArgs) { - const allowed = new Set((await getDocumentedProducts(context)).map((p) => p.slug)); - const pages = source.getPages().filter((page) => allowed.has(page.slugs[0])); +export async function loader() { + const pages = source.getPages(); const index = [ "# 0xBUFF Documentation", "", diff --git a/src/routes/og/docs/$.tsx b/src/routes/og/docs/$.tsx index 4c92bb3..e79e576 100644 --- a/src/routes/og/docs/$.tsx +++ b/src/routes/og/docs/$.tsx @@ -1,17 +1,12 @@ import { generate as DefaultImage } from "fumadocs-ui/og/takumi"; import { ImageResponse } from "takumi-js/response"; import { SITE } from "../../../lib/site"; -import { getDocumentedProducts } from "../../../lib/catalog.server"; import { resolveDocPage } from "../../../lib/source"; import type { Route } from "./+types/$"; -export async function loader({ params, context }: Route.LoaderArgs) { +export async function loader({ params }: Route.LoaderArgs) { const rawSlug = (params as Record)["*"] || ""; const { page } = resolveDocPage(rawSlug, { stripTrailingImage: true }); - const published = await getDocumentedProducts(context); - if (!published.some(({ slug }) => slug === page.slugs[0])) { - throw new Response("Not found", { status: 404 }); - } return new ImageResponse( p.slug)); +export async function loader() { const indexes = await Promise.all( source .getPages() - .filter((page) => allowed.has(page.slugs[0])) .map(async (page) => ({ title: page.data.title, description: page.data.description, diff --git a/src/routes/sitemap[.]xml.ts b/src/routes/sitemap[.]xml.ts index 1caae91..f076ba9 100644 --- a/src/routes/sitemap[.]xml.ts +++ b/src/routes/sitemap[.]xml.ts @@ -1,12 +1,8 @@ import { ROUTES, toSiteUrl } from "../lib/site"; -import { getDocumentedProducts } from "../lib/catalog.server"; -import type { Route } from "./+types/sitemap[.]xml"; import { source } from "../lib/source"; -export async function loader({ context }: Route.LoaderArgs) { - const products = await getDocumentedProducts(context); - const allowed = new Set(products.map((product) => product.slug)); - const pages = source.getPages().filter((page) => allowed.has(page.slugs[0])); +export async function loader() { + const pages = source.getPages(); const urls = [ { loc: toSiteUrl(ROUTES.llms), changefreq: "weekly", priority: "0.6" }, diff --git a/wrangler.jsonc b/wrangler.jsonc index ecf035a..e894863 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -23,12 +23,6 @@ "RESEND_FROM": "0xBUFF Team ", "DOCS_ENV": "production" }, - "r2_buckets": [ - { - "binding": "CONTENT", - "bucket_name": "content" - } - ], "env": { "staging": { "routes": [ @@ -41,13 +35,7 @@ "DOCS_ENV": "staging", "RESEND_FROM": "0xBUFF Team ", "RESEND_SEGMENT_ID": "" - }, - "r2_buckets": [ - { - "binding": "CONTENT", - "bucket_name": "content-staging" - } - ] + } } } }