Files
supabase/apps/kb/scripts/federated-content/fetch-federated-content.ts
Ivan VasilovandClaude Sonnet 5.5 2ac3b77594 chore: replace pnpm hooks and chains with turbo task dependencies in the remaining apps (#53169)
## Problem

`ui-library`, `design-system`, `learn`, `kb`, `www` and `studio` still
order their build, dev and typecheck steps with pnpm `pre`/`post` hooks,
`&&` chains and `run-p`. Turbo can't see those steps, so it can't cache
or parallelize them. Follow-up to #52556, which migrated `apps/docs`.
Part of
[FE-4977](https://linear.app/supabase/issue/FE-4977/migrate-remaining-apps-pnpm-scripts-to-turbo-tasks).

## Solution

The ordering now lives in each app's `turbo.jsonc` as `dependsOn`, the
hooks and chains are gone, and scripts with same-package prerequisites
are wrapped with `maybe-turbo`. `node
.agents/skills/turbo-scripts/scripts/audit.mjs apps/<name>` reports no
findings for any of the six apps.

- **`ui-library`, `design-system`, `learn`:** content, registry and
markdown steps are turbo tasks with declared outputs. `dev:content` uses
the `with` key. `build:next` and `dev:next` are folded into `build` and
`dev`. `ui-library`'s markdown task now depends on `build:registry`,
which the old chain hid. `pnpm --filter library build:registry` still
regenerates the committed registry output.
- **`kb`:** `fetch:federated-content` is uncached, and the tasks that
read its output use `jit` inputs.
- **`www`:**
- `build` depends on `docs#build:guides-markdown`, so federated content
is fetched once instead of twice.
  - `build:next` is folded into `build`.
  - `typecheck` runs `next typegen` itself.
- `turbo-build.test.ts` is updated for the new task graph. It reads
`PATH` through a copy of the env, because `turbo/no-undeclared-env-vars`
flags it once the `passThroughEnv: ["*"]` wildcard is gone.
- `passThroughEnv: ["*"]` is gone, and the env vars the content scripts
read are declared.
- **`studio`:** `typecheck` runs `next typegen` inline, and `lint`
depends on a new `lint:type-checks` task. The `predev` turbopack cache
clean moved into `scripts/dispatch.js`. It's a local side effect, and
making it a turbo task would route `dev` through turbo's strict env
filtering, which drops `NODE_ENV`, `MODE` and `STUDIO_FRAMEWORK`.

## Review instructions

- For each app, check that a second `pnpm build` hits the cache. `www`'s
fetch and content tasks re-run by design, since they're uncached.
- Not verified: the `www` and `studio` dev servers started from the repo
root, a Studio production build, the e2e flow, and runs with real
production credentials.
- `kb`'s build reads a remote database that turbo can't hash. It stays
cached, keyed on `SUPABASE_URL`. Say if you'd rather make it uncached.
- Builds rewrite two tracked files,
`apps/docs/public/markdown/manifest.json` and
`apps/www/public/customers-rss.xml`, so a fresh checkout can miss the
cache once.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 16:40:21 +01:00

121 lines
4.4 KiB
TypeScript

// Fetches every troubleshooting article from the private supabase/troubleshooting
// repo's `guides` folder into src/content/troubleshooting/ (gitignored,
// regenerated on every build — see content.config.ts's `troubleshooting`
// collection). No content processing: body text is written as fetched.
import '../utils/dotenv.js'
import { mkdir, rm, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { Octokit } from '@octokit/core'
import { retry } from '@octokit/plugin-retry'
import matter from 'gray-matter'
import { githubAuthOptions } from './github-auth.ts'
const SOURCE = { org: 'supabase', repo: 'troubleshooting', branch: 'main', dir: 'guides' }
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url))
const TROUBLESHOOTING_DIRECTORY = join(SCRIPT_DIR, '../../src/content/troubleshooting')
const RetryOctokit = Octokit.plugin(retry)
let octokitInstance: InstanceType<typeof RetryOctokit>
function octokit() {
if (!octokitInstance) octokitInstance = new RetryOctokit(githubAuthOptions())
return octokitInstance
}
async function listMarkdownFiles(path: string): Promise<string[]> {
const response = await octokit().request('GET /repos/{owner}/{repo}/contents/{path}', {
owner: SOURCE.org,
repo: SOURCE.repo,
path,
ref: SOURCE.branch,
})
if (!Array.isArray(response.data))
throw new Error(`${path} in ${SOURCE.org}/${SOURCE.repo} is not a directory`)
return response.data
.filter((entry) => entry.type === 'file' && /\.mdx?$/.test(entry.name))
.map((entry) => entry.name)
}
async function getFileContents(path: string): Promise<string> {
const response = await octokit().request('GET /repos/{owner}/{repo}/contents/{path}', {
owner: SOURCE.org,
repo: SOURCE.repo,
path,
ref: SOURCE.branch,
})
if (
Array.isArray(response.data) ||
!('content' in response.data) ||
response.data.type !== 'file'
) {
throw new Error(`Unexpected response for ${path} in ${SOURCE.org}/${SOURCE.repo}`)
}
return Buffer.from(response.data.content, 'base64').toString('utf-8')
}
// Local slug: the filename without its extension. The hash suffix some
// filenames carry (e.g. `foo-bar-94a76b.mdx` -> `foo-bar-94a76b`) is part of
// the slug and is kept, matching what troubleshooting_entries.slug stores.
function slugFromFilename(filename: string): string {
return filename.replace(/\.mdx?$/, '')
}
// Most source files use TOML frontmatter (`title = "..."`), which gray-matter
// can't parse (it assumes YAML) — it either throws or silently returns
// garbage. Detected here by gray-matter failing to produce a `title` string,
// and skipped entirely rather than guessed at.
function parseGuide(raw: string): { title: string; topics: string[]; body: string } | null {
let data: Record<string, unknown>
let body: string
try {
;({ data, content: body } = matter(raw))
} catch {
return null
}
if (typeof data.title !== 'string') return null
return { title: data.title, topics: Array.isArray(data.topics) ? data.topics : [], body }
}
async function fetchPage(filename: string): Promise<'fetched' | 'legacy-toml'> {
const raw = await getFileContents(`${SOURCE.dir}/${filename}`)
const guide = parseGuide(raw)
if (!guide) return 'legacy-toml'
const frontmatter = {
title: guide.title,
topics: guide.topics,
}
const output = matter.stringify(guide.body, frontmatter)
await writeFile(join(TROUBLESHOOTING_DIRECTORY, `${slugFromFilename(filename)}.mdx`), output)
return 'fetched'
}
async function fetchFederatedContent() {
await rm(TROUBLESHOOTING_DIRECTORY, { recursive: true, force: true })
await mkdir(TROUBLESHOOTING_DIRECTORY, { recursive: true })
const filenames = await listMarkdownFiles(SOURCE.dir)
const results = await Promise.all(filenames.map((filename) => fetchPage(filename)))
const legacyTomlFiles = filenames.filter((_, i) => results[i] === 'legacy-toml')
if (legacyTomlFiles.length > 0) {
console.warn(
`[fetch-federated-content.ts]: ${legacyTomlFiles.length} troubleshooting guide(s) contained TOML frontmatter syntax and were ignored:`
)
for (const filename of legacyTomlFiles) console.warn(` - ${filename}`)
}
const fetchedCount = filenames.length - legacyTomlFiles.length
console.log(
`Fetched ${fetchedCount}/${filenames.length} troubleshooting page(s) into src/content/troubleshooting/`
)
}
fetchFederatedContent().catch((error) => {
throw error
})