build(studio): Vite/TanStack-Start build pipeline behind flag (stack 1/6, from #46424) (#47107)

**Stack 1/6** of the TanStack Start migration (#46424), split into
reviewable, independently-mergeable PRs.

> [!IMPORTANT]
> **Next stays the default and only active framework after this PR.**
This wires up the Vite/TanStack-Start build pipeline behind the
`STUDIO_FRAMEWORK` flag, but there are no TanStack routes yet — so the
TanStack build isn't functional or tested until later PRs in the stack.
Nothing about the Next build, dev, or deploy changes behaviourally here.

## What's in this PR
- **Dispatch:** `dev`/`build`/`start` now go through
`scripts/dispatch.js`, which runs the Next variant unless
`STUDIO_FRAMEWORK=tanstack`. The original commands are preserved as
`dev:next`/`build:next`/`start:next`.
- **Build pipeline:** `vite.config.ts`, `serve.js`, `smoke-server.mjs`,
vite/tanstack deps, `turbo.jsonc`.
- **`tsconfig.json`:** `jsx: react-jsx`, `moduleResolution: Bundler`,
`target: ES2022`. Because `include` is `**/*.ts(x)`, this re-typechecks
the whole app, so the companion adaptations below land with it.
- **Shared adaptations (companions to the tsconfig change):**
`BufferSource` casts, `packages/ui` unused-`React` import removals, etc.
- **Routing/middleware plumbing:** `next.config.ts` +
`redirects.shared.ts` (redirect rules now shared with `vercel.ts`),
`proxy.ts`/`start.ts` middleware + `hosted-api-allowlist.ts`.

## Verification
Run locally off `master`: frozen install ✓, `studio` typecheck ✓, **Next
build ✓** (compiles + generates all routes), lint ratchet ✓ ("some rules
improved"), prettier ✓.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added a hosted API endpoint allowlist to return 404 for non-supported
`/api/*` routes.
* Introduced a TanStack route-migration checklist and expanded TanStack
Start routing support.
* **Improvements**
* Enhanced deployment refresh/detection by tightening cookie handling
for “latest deployment” updates.
* Centralized redirect/maintenance-mode rules for consistent platform vs
self-hosted behavior.
* Improved production serving with a dedicated static + proxy server and
a post-build smoke test.
* **Dependencies**
* Updated TanStack-related packages and React Table/query tooling
versions.
* **Documentation / Chores**
* Updated formatting and tooling config; added shared build environment
parsing utilities.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-06-24 17:55:22 +08:00
1 parent d08461140c
commit 9eab4f8fbf
38 files changed
+2756 -574

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env node
// Dispatch a top-level npm script (dev/build/start) to either the next- or
// tanstack-flavoured variant based on STUDIO_FRAMEWORK. We parse the env files
// (via the shared scripts/lib/env.js parser) and pull out only
// STUDIO_FRAMEWORK — we deliberately don't load the whole file into the
// child's process.env, because scripts/serve.js / vite do their own .env
// loading and would otherwise refuse to override the dispatcher-set values,
// including NEXT_PUBLIC_IS_PLATFORM which the e2e `.env.test` needs to flip to
// `false`.
//
// Usage: node scripts/dispatch.js <target>
// target ∈ { dev, build, start }
//
// Resolves to `pnpm run <target>:<framework>` where framework is `tanstack`
// when STUDIO_FRAMEWORK=tanstack (set in the shell env, `.env`, or
// `.env.local`), otherwise `next`.
import { spawn } from 'node:child_process'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { readEnvFiles } from './lib/env.js'
const target = process.argv[2]
if (!target) {
console.error('dispatch.js: missing target (expected one of: dev, build, start)')
process.exit(2)
}
const studioRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
// Shell env wins, then `.env.local`, then `.env` — the same precedence
// scripts/serve.js and vite use, so STUDIO_FRAMEWORK set in either file is
// picked up (not just `.env.local`).
const fileEnv = readEnvFiles(studioRoot, ['.env', '.env.local'])
const studioFramework = process.env.STUDIO_FRAMEWORK ?? fileEnv.STUDIO_FRAMEWORK
const framework = studioFramework === 'tanstack' ? 'tanstack' : 'next'
const script = `${target}:${framework}`
// Use async `spawn` rather than `spawnSync` — long-running dev servers
// (vite dev / next dev) wedge under `spawnSync` because Node holds the
// event loop and stdin doesn't flow through cleanly. The dev server says
// "ready" then exits ~1s later. `spawn` + manual forwarding keeps the
// child interactive and lets the parent exit cleanly when the child does.
const child = spawn('pnpm', ['run', script], {
stdio: 'inherit',
env: process.env,
})
const forwardSignal = (signal) => {
if (!child.killed) child.kill(signal)
}
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT']) {
process.on(signal, () => forwardSignal(signal))
}
child.on('exit', (code, signal) => {
if (signal) process.kill(process.pid, signal)
else process.exit(code ?? 1)
})
child.on('error', (err) => {
console.error('dispatch.js: failed to spawn child:', err)
process.exit(1)
})
+52
View File
@@ -0,0 +1,52 @@
// Shared .env parsing for the studio build/serve scripts (dispatch.js,
// serve.js). We parse the small subset of the dotenv format we actually rely
// on — `KEY=value`, an optional `export` prefix, and surrounding single/double
// quotes — rather than taking on the `dotenv` dependency for a couple of build
// scripts. Crucially, nothing here touches `process.env`: callers decide what
// to do with the parsed values, which is what lets dispatch.js read a single
// key without leaking the whole file into the child process.
//
// dispatch.js and serve.js must agree on this format, so it lives here once.
import { readFileSync } from 'node:fs'
import path from 'node:path'
const ENV_LINE = /^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*?)\s*$/
// Parse the contents of a single env file into a plain key/value object.
export function parseEnv(content) {
const parsed = {}
for (const raw of content.split('\n')) {
const m = ENV_LINE.exec(raw)
if (!m) continue
let value = m[2]
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1)
}
parsed[m[1]] = value
}
return parsed
}
// Read a cascade of env files from `dir`, with later files overriding earlier
// ones — matching the precedence vite/Next use
// (`.env` < `.env.local` < `.env.<mode>` < `.env.<mode>.local`). A missing file
// is skipped, but any other read error (permissions, IO) is surfaced rather
// than silently dropping that file's values. Returns the merged key/value
// object; never mutates process.env.
export function readEnvFiles(dir, files) {
const parsed = {}
for (const file of files) {
let content
try {
content = readFileSync(path.join(dir, file), 'utf8')
} catch (err) {
if (err && typeof err === 'object' && err.code === 'ENOENT') continue
throw err
}
Object.assign(parsed, parseEnv(content))
}
return parsed
}
+1 -1
View File
@@ -128,7 +128,7 @@ function dangerouslyRunEsLint(eslintCmd: string, eslintArgs: string): ESLintExec
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
env: process.env,
maxBuffer: 32 * 1024 * 1024, // allow large ESLint JSON payloads
maxBuffer: 128 * 1024 * 1024, // allow large ESLint JSON payloads (the studio repo regularly emits ~35MB+)
})
const stdout = typeof proc.stdout === 'string' ? proc.stdout : ''
+183
View File
@@ -0,0 +1,183 @@
#!/usr/bin/env node
// Standalone Node HTTP server that hosts the production studio build.
//
// We export the fetch-handler shape from `dist/server/server.js` because
// Vercel consumes it directly (see `apps/studio/api/server.js`). For
// self-hosted / e2e, we need an HTTP listener of our own — this is that
// listener.
//
// Responsibilities:
// - Load env files in vite preview's order so non-NEXT_PUBLIC_* values
// (POSTGRES_PASSWORD, PG_META_CRYPTO_KEY, etc.) are in process.env
// at request time. NEXT_PUBLIC_* are already inlined into the bundle
// at build time and don't need to be re-loaded.
// - Serve static client assets from `dist/client/` directly with the
// right MIME types and cache headers.
// - Forward everything else to the TanStack Start handler exported
// from `dist/server/server.js`.
import { createReadStream } from 'node:fs'
import { stat } from 'node:fs/promises'
import { createServer } from 'node:http'
import path from 'node:path'
import { Readable } from 'node:stream'
import { fileURLToPath } from 'node:url'
import { readEnvFiles } from './lib/env.js'
const studioRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const clientDir = path.join(studioRoot, 'dist/client')
const mode = process.env.MODE || 'production'
const envFiles = ['.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`]
const parsed = readEnvFiles(studioRoot, envFiles)
// Don't clobber values the shell already provides — match `vite preview`.
for (const [k, v] of Object.entries(parsed)) {
if (process.env[k] !== undefined) continue
process.env[k] = v.replace(
/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g,
(_, name) => process.env[name] ?? parsed[name] ?? ''
)
}
const { default: handler } = await import(path.join(studioRoot, 'dist/server/server.js'))
const mimeByExt = new Map([
['.js', 'application/javascript; charset=utf-8'],
['.mjs', 'application/javascript; charset=utf-8'],
['.css', 'text/css; charset=utf-8'],
['.html', 'text/html; charset=utf-8'],
['.json', 'application/json; charset=utf-8'],
['.map', 'application/json; charset=utf-8'],
['.png', 'image/png'],
['.jpg', 'image/jpeg'],
['.jpeg', 'image/jpeg'],
['.gif', 'image/gif'],
['.svg', 'image/svg+xml'],
['.ico', 'image/x-icon'],
['.woff', 'font/woff'],
['.woff2', 'font/woff2'],
['.txt', 'text/plain; charset=utf-8'],
['.webmanifest', 'application/manifest+json'],
])
// Vite emits hashed filenames (e.g. `index-DB4J79t9.js`) for everything
// it bundles. Those are content-addressed so we serve them immutable.
const HASHED_RE = /-[A-Za-z0-9_-]{6,}\.[a-z0-9]+$/
async function serveStatic(req, res) {
let pathname
try {
pathname = new URL(req.url, 'http://localhost').pathname
} catch {
return false
}
if (pathname === '/' || pathname.endsWith('/')) return false
if (pathname.includes('..') || pathname.includes('\\')) return false
const filePath = path.join(clientDir, pathname)
if (!filePath.startsWith(clientDir + path.sep)) return false
let st
try {
st = await stat(filePath)
} catch {
return false
}
if (!st.isFile()) return false
res.statusCode = 200
res.setHeader(
'content-type',
mimeByExt.get(path.extname(filePath).toLowerCase()) ?? 'application/octet-stream'
)
res.setHeader('content-length', String(st.size))
res.setHeader(
'cache-control',
HASHED_RE.test(pathname) ? 'public, max-age=31536000, immutable' : 'no-cache'
)
await new Promise((resolve, reject) => {
const stream = createReadStream(filePath)
stream.on('error', reject)
stream.on('end', resolve)
stream.pipe(res)
})
return true
}
function toWebRequest(req) {
const protocol = req.socket.encrypted ? 'https' : 'http'
const url = `${protocol}://${req.headers.host ?? 'localhost'}${req.url}`
const headers = new Headers()
for (const [k, v] of Object.entries(req.headers)) {
if (k.startsWith(':')) continue
if (Array.isArray(v)) for (const vv of v) headers.append(k, vv)
else if (v !== undefined) headers.set(k, v)
}
const init = { method: req.method, headers }
// Only attach a body for methods that can carry one AND that actually
// have body bytes coming. Wrapping `req` in `Readable.toWeb(req)` for
// requests where Node has nothing to deliver leaves undici's
// `extractBody` looking at an already-consumed stream and throwing
// `TypeError: Response body object should not be disturbed or locked`
// at the `new Request(...)` call below.
const contentLength = Number(req.headers['content-length'] ?? '0')
const hasBody =
req.method !== 'GET' &&
req.method !== 'HEAD' &&
(contentLength > 0 || req.headers['transfer-encoding'] === 'chunked')
if (hasBody) {
init.body = Readable.toWeb(req)
init.duplex = 'half'
}
return new Request(url, init)
}
async function pipeWebResponse(response, res) {
res.statusCode = response.status
// The Headers iterator collapses duplicate keys, and for `set-cookie` it joins
// every cookie into one comma-separated value — which corrupts auth/session
// cookies. Pull the cookies out separately via getSetCookie() and set them as
// an array so each one becomes its own header.
const setCookies =
typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : []
for (const [k, v] of response.headers) {
if (k.toLowerCase() === 'set-cookie') continue
res.setHeader(k, v)
}
if (setCookies.length > 0) res.setHeader('set-cookie', setCookies)
if (!response.body) {
res.end()
return
}
// Pipe via Readable.fromWeb so the underlying stream gets proper backpressure
// and gets released cleanly. `for await (chunk of response.body)` works in
// simple cases but can leave the body in a "disturbed / locked" state when
// the handler internally peeks at it — surfacing as
// `TypeError: Response body object should not be disturbed or locked` on a
// subsequent request.
await new Promise((resolve, reject) => {
const readable = Readable.fromWeb(response.body)
readable.on('error', reject)
res.on('error', reject)
res.on('close', resolve)
res.on('finish', resolve)
readable.pipe(res)
})
}
const port = Number(process.env.PORT || 8082)
createServer(async (req, res) => {
try {
if (await serveStatic(req, res)) return
const response = await handler.fetch(toWebRequest(req))
await pipeWebResponse(response, res)
} catch (err) {
console.error('[serve] request failed:', err)
if (!res.headersSent) {
res.statusCode = 500
res.setHeader('content-type', 'text/plain; charset=utf-8')
}
res.end('Internal Server Error')
}
}).listen(port, () => {
console.log(`Studio listening on http://localhost:${port} (mode=${mode})`)
})
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env node
// Post-build smoke test: boot the built TanStack server handler and make a
// real request with a platform-like environment, so module-scope boot
// crashes fail the BUILD instead of the deployed function at runtime.
//
// Why this exists: the TanStack server entry eagerly imports the entire route
// tree (`loadEntries`), so every route module is evaluated the first time the
// single function handler serves a request. A bad top-level side effect in any
// one route — e.g. `createClient(process.env.SUPABASE_URL!, ...)` at module
// scope, where SUPABASE_URL is unset on platform — throws during that import
// and 500s every route, including trivial ones like /api/get-utc-time. Those
// failures only showed up at runtime on Vercel; this catches them at build.
//
// What this catches: anything that throws while the route tree is imported
// (the most common class — missing env vars read at module scope).
// What this does NOT catch: assets missing from the *Vercel function bundle*
// (e.g. libpg-query.wasm). Local node_modules still has those, so booting the
// plain `dist/server` build won't surface them — that needs booting the
// `vercel build` output. Pass that function's entry as argv[1] to reuse this
// script in a deploy-gating CI step.
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const studioRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const serverEntry = process.argv[2]
? path.resolve(process.argv[2])
: path.join(studioRoot, 'dist/server/server.js')
// Simulate the platform function runtime: these are only set on self-hosted,
// so removing them surfaces any route that needs them at module-load time.
for (const key of ['SUPABASE_URL', 'SUPABASE_SERVICE_KEY', 'SUPABASE_SERVICE_ROLE_KEY']) {
delete process.env[key]
}
const basePath = process.env.NEXT_PUBLIC_BASE_PATH ?? ''
// A request to any route forces `loadEntries` to import the full route tree,
// so a single cheap, dependency-free endpoint is enough to exercise the boot.
const ROUTES = ['/api/get-utc-time']
console.log(`[smoke] booting ${path.relative(studioRoot, serverEntry)}`)
const { default: handler } = await import(serverEntry)
let failed = false
for (const route of ROUTES) {
const url = `http://localhost${basePath}${route}`
try {
const res = await handler.fetch(new Request(url))
if (res.status >= 500) {
failed = true
const body = await res.text().catch(() => '')
console.error(`[smoke] ✗ ${route} → ${res.status}\n${body.slice(0, 800)}`)
} else {
console.log(`[smoke] ✓ ${route} → ${res.status}`)
}
} catch (err) {
failed = true
console.error(`[smoke] ✗ ${route} threw while booting the server:\n`, err)
}
}
if (failed) {
console.error(
'\n[smoke] FAILED — the server bundle does not boot cleanly. This usually means a\n' +
'route module has a top-level side effect (e.g. createClient at module scope with a\n' +
'missing env var). Make it lazy so it only runs inside the handler.'
)
process.exit(1)
}
console.log('\n[smoke] passed — server boots and routes respond without a 5xx.')
process.exit(0)