@timber-js/app 0.2.0-alpha.206 → 0.2.0-alpha.207

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { n as scanRoutes } from "./scanner-BQ5sPIJ7.js";
2
- import { a as CODEGEN_OUTPUT, c as writeRouteCodegen, n as formatConventionWarnings, o as ENV_DTS_FILENAME, r as lintConventions } from "./convention-lint-BnO5TyHD.js";
2
+ import { a as CODEGEN_OUTPUT, c as writeRouteCodegen, n as formatConventionWarnings, o as ENV_DTS_FILENAME, r as lintConventions } from "./convention-lint-5KzoMg_A.js";
3
3
  import { n as isTimberPluginApi } from "./plugin-context-8idfR3UZ.js";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { createRequire } from "node:module";
@@ -290,4 +290,4 @@ async function runTypeCheck(options = {}, deps = {}) {
290
290
  //#endregion
291
291
  export { checkRoutes, runTypeCheck };
292
292
 
293
- //# sourceMappingURL=cli-check-BqOylm-3.js.map
293
+ //# sourceMappingURL=cli-check-G8o30ldg.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cli-check-BqOylm-3.js","names":[],"sources":["../../src/cli-check.ts"],"sourcesContent":["/**\n * `timber check` — the implementation behind the CLI command.\n *\n * Two passes, in order:\n *\n * 1. **Routes.** Resolve the project through Vite — so root, `appDir`, and\n * `pageExtensions` are the ones `timber build` uses, including config\n * passed inline to `timber()` — then scan, run the convention linter, and\n * write the route codegen (`.timber/timber-routes.d.ts`,\n * `.timber/segment-types.d.ts`, `timber-env.d.ts`).\n *\n * Codegen runs *before* the type pass on purpose: those\n * files are what give `<Link href>`, `useSegmentParams()` and\n * `MiddlewareContext` their per-route types (design/09-typescript.md\n * §\"Typed Routes\"), and they are build artifacts — a fresh clone that has\n * never run `timber dev` or `timber build` does not have them, so a type\n * pass on its own would report errors about correct code. A clone whose\n * routes changed since the last build has the same problem with stale ones.\n * 2. **Types.** `tsgo --noEmit` over the project.\n *\n * tsgo is spawned as `node <@typescript/native-preview>/lib/tsgo.js`, never as\n * a bare `tsgo` off PATH — the package is an *optional peer dependency*, so\n * there is no reason for its shim to be on a user's PATH, and the shim is a\n * `.cmd` on Windows which cannot be spawned without a shell. `shell: true`\n * would then concatenate the argv into an unescaped command string, so a\n * project path containing a space would break on exactly the platform the\n * shell was there to support. This mirrors `scripts/build-types.js`, whose\n * header comment is the specification for the pattern.\n *\n * Design docs: 11-platform.md §CLI, 09-typescript.md, 28-npm-packaging.md\n */\n\nimport { createRequire } from 'node:module';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { scanRoutes } from './routing/scanner.ts';\nimport { lintConventions, formatConventionWarnings } from './routing/convention-lint.ts';\nimport { writeRouteCodegen, CODEGEN_OUTPUT, ENV_DTS_FILENAME } from './routing/codegen-write.ts';\nimport { isTimberPluginApi } from './plugin-context.ts';\n\n/** The plugin that publishes timber's resolved context on its Vite `api`. */\nconst TIMBER_ROOT_SYNC_PLUGIN = 'timber-root-sync';\n\n/** The npm package that provides tsgo. Named in the missing-tool message. */\nconst TSGO_PACKAGE = '@typescript/native-preview';\n\n/**\n * The two generated declaration paths, relative to the project root, as they\n * appear in a resolved tsconfig file list. Derived from the writer's own\n * constants — a rename there cannot leave this check hunting for a file nothing\n * writes.\n */\nconst GENERATED_TYPE_PATHS = [ENV_DTS_FILENAME, CODEGEN_OUTPUT];\n\n/**\n * Run the compiler to completion.\n *\n * Resolves with its exit status (`null` when a signal killed it) and rejects\n * only when the process could not be started — the two outcomes `runTypeCheck`\n * has to keep apart. The seam is this narrow on purpose: a test double is a\n * plain async function, with no `ChildProcess` shape to imitate.\n */\nexport type RunTsgo = (command: string, args: string[], cwd: string) => Promise<number | null>;\n\n/**\n * Run the compiler and capture its stdout — used for `--showConfig`, whose\n * output is data we read rather than diagnostics the user reads.\n */\nexport type ReadTsgoConfig = (command: string, args: string[], cwd: string) => Promise<string>;\n\n/**\n * Vite's own `resolveConfig`, narrowed to what this module passes and reads.\n *\n * The seam sits at `resolveConfig` rather than at \"give me the plugins\" so the\n * *arguments* are the thing under test: which config file, which command, and\n * which mode defaults. Those arguments have been wrong three separate times\n * (TIM-1332 rounds 4-6), and a double that answered \"here are the plugins\"\n * could not see any of it. The double returns what Vite returns — plugins with\n * an opaque `api` — so the lookup and narrowing under test stay the real ones.\n */\nexport type ResolveViteConfig = (\n inlineConfig: { configFile: string | undefined },\n command: 'build',\n defaultMode: string,\n defaultNodeEnv: string\n) => Promise<{ plugins: readonly PluginWithApi[] }>;\n\n/** @internal Dependency injection for testing. */\nexport interface CheckDeps {\n /**\n * Resolve tsgo's own JS entry point. Throws when the package is not\n * installed — the caller turns that into an install instruction.\n */\n resolveTsgoEntry?: () => string;\n runTsgo?: RunTsgo;\n readTsgoConfig?: ReadTsgoConfig;\n resolveViteConfig?: ResolveViteConfig;\n}\n\nexport interface CheckOptions {\n /** Project root, for resolving tsgo. Defaults to `process.cwd()`. */\n root?: string;\n /**\n * Path to a **tsconfig**, forwarded to tsgo as `--project` and sourced from\n * the CLI's own `--project`. The route pass takes no part in it: it resolves\n * the app's configuration through Vite, as `timber build` does.\n */\n config?: string;\n}\n\n/**\n * Locate `@typescript/native-preview`'s JS entry.\n *\n * Resolution is attempted from this package first (it is declared an optional\n * peer dependency, so a package manager links it here when the user installs\n * it) and then from the project root (covering a hoisted install, or a user who\n * added it without the peer link). Throws if neither finds it.\n */\nexport function resolveTsgoEntry(\n root: string,\n resolveFrom: (from: string, specifier: string) => string = (from, specifier) =>\n createRequire(from).resolve(specifier)\n): string {\n // `createRequire` takes a filename or a file URL; a plain absolute path is\n // the portable spelling for the project root (a `file://` prefix on a Windows\n // path is not a valid URL). Same form as `checkPeerDependencies`.\n const candidates = [import.meta.url, join(root, 'package.json')];\n let lastError: unknown;\n\n for (const from of candidates) {\n try {\n // The package exports no subpath for its entry, so resolve the manifest\n // and walk to the module its `bin/tsgo` shim imports.\n const manifest = resolveFrom(from, `${TSGO_PACKAGE}/package.json`);\n return join(dirname(manifest), 'lib', 'tsgo.js');\n } catch (err) {\n lastError = err;\n }\n }\n\n throw new Error(\n `[timber] Cannot find ${TSGO_PACKAGE}, which \\`timber check\\` uses to type-check.\\n\\n` +\n ` Install it as a dev dependency:\\n\\n` +\n ` pnpm add -D ${TSGO_PACKAGE}\\n\\n` +\n ` (resolution failed: ${lastError instanceof Error ? lastError.message : String(lastError)})`\n );\n}\n\n/** What the route pass needs from the command line. */\nexport interface RouteOptions {\n /**\n * Path to a **Vite** config file, from `--config`. Undefined means Vite's own\n * discovery, the same as `timber dev`/`build` without the flag. A project\n * that builds with a custom Vite config has to be checkable with it too, or\n * `check` resolves a different app than `build` does (TIM-1332, round 4).\n */\n viteConfigFile?: string;\n}\n\n/** Everything the route scan needs, as the build itself resolves it. */\nexport interface RouteInputs {\n root: string;\n appDir: string;\n pageExtensions: string[] | undefined;\n}\n\n/** The subset of a resolved Vite plugin this module reads. */\nexport interface PluginWithApi {\n name: string;\n api?: unknown;\n}\n\n/**\n * Ask Vite for the resolved config, which is what carries timber's context.\n *\n * `resolveConfig` runs the whole config pipeline — config file discovery,\n * `config` and `configResolved` hooks — so the context it produces is the one\n * `timber build` would use. Measured at ~300-400ms on a real app; the type pass\n * it precedes costs far more.\n */\nconst defaultResolveViteConfig: ResolveViteConfig = async (\n inlineConfig,\n command,\n defaultMode,\n defaultNodeEnv\n) => {\n const { resolveConfig } = await import('vite');\n return resolveConfig(inlineConfig, command, defaultMode, defaultNodeEnv);\n};\n\n/**\n * The mode defaults `timber build` resolves under.\n *\n * `resolveConfig`'s own defaults are `'development'` for both, but nothing\n * reaches it with those on a build: `createBuilder` goes through Vite's\n * internal `resolveConfigToBuild`, which calls\n * `resolveConfig(inlineConfig, 'build', 'production', 'production')`. A config\n * written as `defineConfig(({ mode }) => …)`, or one that loads `.env.production`,\n * therefore resolves to a *different* app under the two. Passing the defaults\n * explicitly is what makes \"check validates what build builds\" true rather than\n * true-by-coincidence for configs that ignore mode (TIM-1332, round 6).\n */\nconst BUILD_MODE_DEFAULTS = ['production', 'production'] as const;\n\n/**\n * Resolve root, appDir and pageExtensions the way `timber build` resolves them.\n *\n * Reading `timber.config.ts` directly is **not** equivalent, which is the whole\n * reason this goes through Vite (TIM-1332, review round 3):\n *\n * - Config passed inline — `timber({ pageExtensions: [...] })` in\n * `vite.config.ts` — lives only in the plugin's closure. Nothing that\n * re-reads the config file can see it, so a scan built that way silently uses\n * default page extensions and writes a route map missing the app's pages.\n * `examples/next-playground-migration` is exactly this shape.\n * - `root` is Vite's resolved root, not the caller's cwd, and the two differ in\n * the monorepo layouts TIM-498 describes. `appDir` resolves against it.\n *\n * There is no fallback to a second, hand-rolled resolution. A project whose\n * Vite config does not produce the timber plugin cannot be built either, so a\n * check that quietly proceeded on a guessed tree would report a verdict about\n * an app that does not exist.\n */\nexport async function resolveRouteInputs(\n options: RouteOptions = {},\n deps: CheckDeps = {}\n): Promise<RouteInputs> {\n const resolveViteConfig = deps.resolveViteConfig ?? defaultResolveViteConfig;\n // `configFile: undefined` is Vite's own \"discover it\" value, so the default\n // path stays exactly what Vite does for `timber build` without `--config`.\n const { plugins } = await resolveViteConfig(\n { configFile: options.viteConfigFile },\n 'build',\n ...BUILD_MODE_DEFAULTS\n );\n\n const rootSync = plugins.find((plugin) => plugin.name === TIMBER_ROOT_SYNC_PLUGIN);\n if (!rootSync || !isTimberPluginApi(rootSync.api)) {\n throw new Error(\n `[timber] Could not read the resolved timber configuration from your Vite config.\\n\\n` +\n ` \\`timber check\\` resolves your project through Vite so it validates the same\\n` +\n ` routes \\`timber build\\` builds — including config passed inline to timber().\\n\\n` +\n ` Check that vite.config.ts exists and lists the timber plugin:\\n\\n` +\n ` import { timber } from '@timber-js/app';\\n` +\n ` export default { plugins: [timber()] };\\n`\n );\n }\n\n const ctx = rootSync.api.getContext();\n return { root: ctx.root, appDir: ctx.appDir, pageExtensions: ctx.config.pageExtensions };\n}\n\n/**\n * Resolve the app directory, scan it, fail on proven-fatal route\n * misconfigurations, print warnings, and write the route codegen the type pass\n * depends on.\n *\n * Error-level lint findings throw rather than print, matching what\n * `plugins/routing.ts` does at build time: the tree is not fit to publish, so\n * it must not reach codegen either. Warnings are printed and do not fail the\n * command — same severity contract as dev and build, so `timber check` cannot\n * disagree with them about what a valid app is.\n */\nexport async function checkRoutes(\n options: RouteOptions = {},\n deps: CheckDeps = {}\n): Promise<RouteInputs> {\n const inputs = await resolveRouteInputs(options, deps);\n const { root, appDir, pageExtensions } = inputs;\n\n const tree = scanRoutes(appDir, { pageExtensions });\n\n const warnings = lintConventions(tree, appDir);\n const fatal = warnings.filter((w) => w.level === 'error');\n if (fatal.length > 0) {\n throw new Error(formatConventionWarnings(fatal, { color: false }));\n }\n if (warnings.length > 0) {\n process.stderr.write(`${formatConventionWarnings(warnings)}\\n`);\n }\n\n // Awaited, unlike the dev/build path: the type pass reads these files, so a\n // failed write would be reported as type errors in the user's own code.\n // Reported as a codegen failure rather than surfaced as a bare `EROFS`/\n // `EACCES` from somewhere unnamed — the raw error says which path could not\n // be written but not which pass wanted it.\n try {\n await writeRouteCodegen(tree, appDir, root);\n } catch (err) {\n throw new Error(\n `[timber] Failed to write the generated route types, which the type check reads: ` +\n `${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n verifyCodegenImports(root);\n\n // Returned so the type pass runs against the same root these files landed in.\n return inputs;\n}\n\n/**\n * Verify that the import specifiers in the generated route types resolve on the\n * filesystem. A `.d.ts` whose import fails does NOT produce a TypeScript error —\n * every type that depends on it silently becomes `any`. The generated file\n * contains type-level `_AssertSchemaNotAny` / `_AssertCodecTypeNotAny` guards\n * that catch this at typecheck time, but a diagnostic here fires earlier and\n * names the exact import that is broken rather than leaving the user to decode\n * a constraint error.\n */\nexport function verifyCodegenImports(root: string): void {\n const dtsPath = join(root, CODEGEN_OUTPUT);\n let content: string;\n try {\n content = readFileSync(dtsPath, 'utf-8');\n } catch {\n return;\n }\n\n const dtsDir = dirname(dtsPath);\n\n // Check relative imports (default imports only — the generated codegen uses\n // `import type schema from '...'` for relative paths). Named imports from\n // relative paths are not emitted today; if codegen adds them, extend this.\n const RELATIVE_IMPORT_RE = /^import\\s+type\\s+\\w+\\s+from\\s+'(\\.\\.?\\/[^']+)'/gm;\n const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.tsx'];\n let match;\n while ((match = RELATIVE_IMPORT_RE.exec(content)) !== null) {\n const specifier = match[1];\n const base = join(dtsDir, specifier);\n const resolves = existsSync(base) || EXTENSIONS.some((ext) => existsSync(base + ext));\n if (!resolves) {\n process.stderr.write(\n `[timber] WARNING: the generated ${CODEGEN_OUTPUT} imports '${specifier}',\\n` +\n ` but no file resolves at ${base}{${EXTENSIONS.join(',')}}.\\n` +\n ` Every type that depends on this import will silently become \\`any\\`.\\n\\n` +\n ` Check that your app/ directory is where timber expects it.\\n\\n`\n );\n }\n }\n\n // Bare-specifier imports (`@timber-js/app/params`) are NOT checked here.\n // They are all dependencies of @timber-js/app itself — if timber is installed,\n // they resolve. And createRequire uses CJS resolution which cannot follow\n // ESM-only subpath exports, producing false warnings (TIM-1348 review).\n}\n\n/**\n * The production `RunTsgo`: spawn the compiler with its stdio inherited, so its\n * diagnostics stream to the terminal as they are produced (and are not capped\n * by a buffer, as `execFile` output would be).\n */\nconst spawnTsgo: RunTsgo = async (command, args, cwd) => {\n const { spawn } = await import('node:child_process');\n return new Promise<number | null>((resolve, reject) => {\n // No `shell: true`: Node would concatenate the argv into an unescaped\n // command string, so a project path containing a space would break.\n const child = spawn(command, args, { stdio: 'inherit', cwd });\n child.on('error', reject);\n child.on('close', (code) => resolve(code));\n });\n};\n\n/**\n * The production `ReadTsgoConfig`: `--showConfig`, with stdout captured.\n *\n * `maxBuffer` is raised well past `execFile`'s 1 MB default because the output\n * is one line per file in the program — a large app can exceed that, and\n * overflowing it would make this advisory go quiet on exactly the projects\n * where a misconfigured `include` costs the most. A size-dependent silence is\n * indistinguishable from \"everything is fine\".\n */\nconst execTsgoConfig: ReadTsgoConfig = async (command, args, cwd) => {\n const { execFile } = await import('node:child_process');\n return new Promise<string>((resolve, reject) => {\n execFile(command, args, { cwd, maxBuffer: 64 * 1024 * 1024 }, (err, stdout) =>\n err ? reject(err) : resolve(stdout)\n );\n });\n};\n\n/**\n * Warn when the generated route declarations will not reach the type checker.\n *\n * Writing `.timber/timber-routes.d.ts` and `timber-env.d.ts` is only half the\n * job: TypeScript loads them only if the project's `include`/`files` actually\n * pull `timber-env.d.ts` in (it is what `/// <reference>`s the route map). A\n * tsconfig with an explicit `include` that lists only source directories —\n * `[\"app\", \"*.config.ts\"]`, which is what `create-timber-app` shipped before\n * TIM-1332 — silently omits it, and every `<Link href>` then type-checks\n * against the empty placeholder instead of the generated route union. The\n * check would pass while answering the wrong question.\n *\n * The resolved file list comes from `tsgo --showConfig` rather than from our\n * own reading of the tsconfig: `include`, `exclude`, `files`, and `extends`\n * compose in ways that are the compiler's to decide, and a second\n * implementation of them would be a duplicate that drifts. `--showConfig` only\n * resolves globs, so it costs no type checking.\n *\n * This warns rather than fails. An app that never uses typed routes is\n * correct without those declarations, and a hard error would refuse it — the\n * one outcome a check must not produce for a working project. When the answer\n * cannot be determined (tsgo errored, output was not the expected JSON), the\n * warning is skipped: an advisory that fires on an unknown is noise.\n */\nasync function warnIfRouteTypesUnreachable(\n tsgoEntry: string,\n configArgs: string[],\n cwd: string,\n readConfig: ReadTsgoConfig\n): Promise<void> {\n let files: unknown;\n try {\n const raw = await readConfig(process.execPath, [tsgoEntry, '--showConfig', ...configArgs], cwd);\n files = (JSON.parse(raw) as { files?: unknown }).files;\n } catch {\n return;\n }\n if (!Array.isArray(files)) return;\n\n // Suffix match, not path resolution: `--showConfig` prints paths relative to\n // whichever tsconfig the compiler *found*, which for a bare `timber check`\n // is a directory we never learn. Over-matching only suppresses an advisory.\n //\n // The bare form is matched as well as the `/`-prefixed one. tsgo emits\n // `./timber-env.d.ts` today, but a leading `./` is cosmetic and an emitter\n // that dropped it would turn this into a warning printed at every correctly\n // configured project — the failure direction that trains people to ignore it.\n const reaches = files.some((file) => {\n if (typeof file !== 'string') return false;\n const normalized = file.replace(/\\\\/g, '/');\n return GENERATED_TYPE_PATHS.some(\n (path) => normalized === path || normalized.endsWith(`/${path}`)\n );\n });\n if (reaches) return;\n\n process.stderr.write(\n `[timber] The generated route types are not part of this TypeScript project, so\\n` +\n ` \\`<Link href>\\` and \\`useSegmentParams()\\` are being checked against empty\\n` +\n ` placeholders. Your tsconfig's \"include\" does not pull in timber-env.d.ts.\\n\\n` +\n ` To fix: add it to \"include\":\\n\\n` +\n ` \"include\": [\"app\", \"*.config.ts\", \"timber-env.d.ts\"]\\n\\n`\n );\n}\n\n/**\n * Run `tsgo --noEmit`, streaming its output.\n *\n * Rejects with the real numeric exit status on type errors. A failure to *start*\n * the compiler is reported separately — the historical bug this replaces\n * surfaced ENOENT as \"Type check failed with exit code undefined\", which read\n * as a type error and sent users looking at their own code.\n */\nexport async function runTypeCheck(\n options: CheckOptions = {},\n deps: CheckDeps = {}\n): Promise<void> {\n // The *resolved* root, handed over by the route pass — not `process.cwd()`.\n // The two differ whenever `--config` names a Vite config elsewhere, and the\n // route pass wrote `.timber/*` and `timber-env.d.ts` under the resolved one.\n // Running tsgo from cwd would then discover a different tsconfig entirely and\n // type-check a different project than the one just validated (TIM-1332, round\n // 5) — routes checked for the app, types checked for the monorepo around it.\n const root = options.root ?? process.cwd();\n const tsgoEntry = (deps.resolveTsgoEntry ?? (() => resolveTsgoEntry(root)))();\n const runTsgo = deps.runTsgo ?? spawnTsgo;\n\n // An explicit `--project` is a path the user typed at their own prompt, so it\n // is resolved against *their* cwd before the compiler is moved to the project\n // root. Without `--project`, tsgo discovers `tsconfig.json` from `root`,\n // which is where the declarations it needs were just written.\n const configArgs = options.config ? ['--project', resolve(process.cwd(), options.config)] : [];\n\n // Before checking: say so if the declarations the route pass just wrote will\n // not be part of the program. Otherwise the check passes while `<Link href>`\n // is measured against a placeholder. Same root and same argv as the check\n // itself, or it would inspect a different program than the one tsgo reads.\n await warnIfRouteTypesUnreachable(\n tsgoEntry,\n configArgs,\n root,\n deps.readTsgoConfig ?? execTsgoConfig\n );\n\n let code: number | null;\n try {\n code = await runTsgo(process.execPath, [tsgoEntry, '--noEmit', ...configArgs], root);\n } catch (err) {\n // Could not start the compiler at all. Kept distinct from a nonzero exit:\n // the version this replaced reported ENOENT as \"Type check failed with\n // exit code undefined\", which reads as a verdict on the user's types.\n throw new Error(\n `[timber] Failed to start the type checker: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n if (code === 0) return;\n\n // A null code means a signal killed the process rather than it exiting.\n // Say so instead of printing \"exit code null\".\n throw new Error(\n code === null\n ? 'Type check terminated before it finished'\n : `Type check failed with exit code ${code}`\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAM,0BAA0B;;AAGhC,IAAM,eAAe;;;;;;;AAQrB,IAAM,uBAAuB,CAAC,kBAAkB,cAAc;;;;;;;;;AAkE9D,SAAgB,iBACd,MACA,eAA4D,MAAM,cAChE,cAAc,IAAI,CAAC,CAAC,QAAQ,SAAS,GAC/B;CAIR,MAAM,aAAa,CAAC,YAAY,KAAK,KAAK,MAAM,cAAc,CAAC;CAC/D,IAAI;CAEJ,KAAK,MAAM,QAAQ,YACjB,IAAI;EAGF,MAAM,WAAW,YAAY,MAAM,GAAG,aAAa,cAAc;EACjE,OAAO,KAAK,QAAQ,QAAQ,GAAG,OAAO,SAAS;CACjD,SAAS,KAAK;EACZ,YAAY;CACd;CAGF,MAAM,IAAI,MACR,wBAAwB,aAAa,uGAEhB,aAAa,4BACP,qBAAqB,QAAQ,UAAU,UAAU,OAAO,SAAS,EAAE,EAChG;AACF;;;;;;;;;AAkCA,IAAM,2BAA8C,OAClD,cACA,SACA,aACA,mBACG;CACH,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,OAAO,cAAc,cAAc,SAAS,aAAa,cAAc;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GAAgB,GAAG;EAAU,GAAG,GAAG;EAC9F,QAAS,KAAK,MAAM,GAAG,CAAC,CAAyB;CACnD,QAAQ;EACN;CACF;CACA,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG;CAiB3B,IAPgB,MAAM,MAAM,SAAS;EACnC,IAAI,OAAO,SAAS,UAAU,OAAO;EACrC,MAAM,aAAa,KAAK,QAAQ,OAAO,GAAG;EAC1C,OAAO,qBAAqB,MACzB,SAAS,eAAe,QAAQ,WAAW,SAAS,IAAI,MAAM,CACjE;CACF,CACI,GAAS;CAEb,QAAQ,OAAO,MACb,qVAKF;AACF;;;;;;;;;AAUA,eAAsB,aACpB,UAAwB,CAAC,GACzB,OAAkB,CAAC,GACJ;CAOf,MAAM,OAAO,QAAQ,QAAQ,QAAQ,IAAI;CACzC,MAAM,aAAa,KAAK,2BAA2B,iBAAiB,IAAI,GAAA,CAAI;CAC5E,MAAM,UAAU,KAAK,WAAW;CAMhC,MAAM,aAAa,QAAQ,SAAS,CAAC,aAAa,QAAQ,QAAQ,IAAI,GAAG,QAAQ,MAAM,CAAC,IAAI,CAAC;CAM7F,MAAM,4BACJ,WACA,YACA,MACA,KAAK,kBAAkB,cACzB;CAEA,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,QAAQ,UAAU;GAAC;GAAW;GAAY,GAAG;EAAU,GAAG,IAAI;CACrF,SAAS,KAAK;EAIZ,MAAM,IAAI,MACR,8CAA8C,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,GAC/F;CACF;CAEA,IAAI,SAAS,GAAG;CAIhB,MAAM,IAAI,MACR,SAAS,OACL,6CACA,oCAAoC,MAC1C;AACF"}
1
+ {"version":3,"file":"cli-check-G8o30ldg.js","names":[],"sources":["../../src/cli-check.ts"],"sourcesContent":["/**\n * `timber check` — the implementation behind the CLI command.\n *\n * Two passes, in order:\n *\n * 1. **Routes.** Resolve the project through Vite — so root, `appDir`, and\n * `pageExtensions` are the ones `timber build` uses, including config\n * passed inline to `timber()` — then scan, run the convention linter, and\n * write the route codegen (`.timber/timber-routes.d.ts`,\n * `.timber/segment-types.d.ts`, `timber-env.d.ts`).\n *\n * Codegen runs *before* the type pass on purpose: those\n * files are what give `<Link href>`, `useSegmentParams()` and\n * `MiddlewareContext` their per-route types (design/09-typescript.md\n * §\"Typed Routes\"), and they are build artifacts — a fresh clone that has\n * never run `timber dev` or `timber build` does not have them, so a type\n * pass on its own would report errors about correct code. A clone whose\n * routes changed since the last build has the same problem with stale ones.\n * 2. **Types.** `tsgo --noEmit` over the project.\n *\n * tsgo is spawned as `node <@typescript/native-preview>/lib/tsgo.js`, never as\n * a bare `tsgo` off PATH — the package is an *optional peer dependency*, so\n * there is no reason for its shim to be on a user's PATH, and the shim is a\n * `.cmd` on Windows which cannot be spawned without a shell. `shell: true`\n * would then concatenate the argv into an unescaped command string, so a\n * project path containing a space would break on exactly the platform the\n * shell was there to support. This mirrors `scripts/build-types.js`, whose\n * header comment is the specification for the pattern.\n *\n * Design docs: 11-platform.md §CLI, 09-typescript.md, 28-npm-packaging.md\n */\n\nimport { createRequire } from 'node:module';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { scanRoutes } from './routing/scanner.ts';\nimport { lintConventions, formatConventionWarnings } from './routing/convention-lint.ts';\nimport { writeRouteCodegen, CODEGEN_OUTPUT, ENV_DTS_FILENAME } from './routing/codegen-write.ts';\nimport { isTimberPluginApi } from './plugin-context.ts';\n\n/** The plugin that publishes timber's resolved context on its Vite `api`. */\nconst TIMBER_ROOT_SYNC_PLUGIN = 'timber-root-sync';\n\n/** The npm package that provides tsgo. Named in the missing-tool message. */\nconst TSGO_PACKAGE = '@typescript/native-preview';\n\n/**\n * The two generated declaration paths, relative to the project root, as they\n * appear in a resolved tsconfig file list. Derived from the writer's own\n * constants — a rename there cannot leave this check hunting for a file nothing\n * writes.\n */\nconst GENERATED_TYPE_PATHS = [ENV_DTS_FILENAME, CODEGEN_OUTPUT];\n\n/**\n * Run the compiler to completion.\n *\n * Resolves with its exit status (`null` when a signal killed it) and rejects\n * only when the process could not be started — the two outcomes `runTypeCheck`\n * has to keep apart. The seam is this narrow on purpose: a test double is a\n * plain async function, with no `ChildProcess` shape to imitate.\n */\nexport type RunTsgo = (command: string, args: string[], cwd: string) => Promise<number | null>;\n\n/**\n * Run the compiler and capture its stdout — used for `--showConfig`, whose\n * output is data we read rather than diagnostics the user reads.\n */\nexport type ReadTsgoConfig = (command: string, args: string[], cwd: string) => Promise<string>;\n\n/**\n * Vite's own `resolveConfig`, narrowed to what this module passes and reads.\n *\n * The seam sits at `resolveConfig` rather than at \"give me the plugins\" so the\n * *arguments* are the thing under test: which config file, which command, and\n * which mode defaults. Those arguments have been wrong three separate times\n * (TIM-1332 rounds 4-6), and a double that answered \"here are the plugins\"\n * could not see any of it. The double returns what Vite returns — plugins with\n * an opaque `api` — so the lookup and narrowing under test stay the real ones.\n */\nexport type ResolveViteConfig = (\n inlineConfig: { configFile: string | undefined },\n command: 'build',\n defaultMode: string,\n defaultNodeEnv: string\n) => Promise<{ plugins: readonly PluginWithApi[] }>;\n\n/** @internal Dependency injection for testing. */\nexport interface CheckDeps {\n /**\n * Resolve tsgo's own JS entry point. Throws when the package is not\n * installed — the caller turns that into an install instruction.\n */\n resolveTsgoEntry?: () => string;\n runTsgo?: RunTsgo;\n readTsgoConfig?: ReadTsgoConfig;\n resolveViteConfig?: ResolveViteConfig;\n}\n\nexport interface CheckOptions {\n /** Project root, for resolving tsgo. Defaults to `process.cwd()`. */\n root?: string;\n /**\n * Path to a **tsconfig**, forwarded to tsgo as `--project` and sourced from\n * the CLI's own `--project`. The route pass takes no part in it: it resolves\n * the app's configuration through Vite, as `timber build` does.\n */\n config?: string;\n}\n\n/**\n * Locate `@typescript/native-preview`'s JS entry.\n *\n * Resolution is attempted from this package first (it is declared an optional\n * peer dependency, so a package manager links it here when the user installs\n * it) and then from the project root (covering a hoisted install, or a user who\n * added it without the peer link). Throws if neither finds it.\n */\nexport function resolveTsgoEntry(\n root: string,\n resolveFrom: (from: string, specifier: string) => string = (from, specifier) =>\n createRequire(from).resolve(specifier)\n): string {\n // `createRequire` takes a filename or a file URL; a plain absolute path is\n // the portable spelling for the project root (a `file://` prefix on a Windows\n // path is not a valid URL). Same form as `checkPeerDependencies`.\n const candidates = [import.meta.url, join(root, 'package.json')];\n let lastError: unknown;\n\n for (const from of candidates) {\n try {\n // The package exports no subpath for its entry, so resolve the manifest\n // and walk to the module its `bin/tsgo` shim imports.\n const manifest = resolveFrom(from, `${TSGO_PACKAGE}/package.json`);\n return join(dirname(manifest), 'lib', 'tsgo.js');\n } catch (err) {\n lastError = err;\n }\n }\n\n throw new Error(\n `[timber] Cannot find ${TSGO_PACKAGE}, which \\`timber check\\` uses to type-check.\\n\\n` +\n ` Install it as a dev dependency:\\n\\n` +\n ` pnpm add -D ${TSGO_PACKAGE}\\n\\n` +\n ` (resolution failed: ${lastError instanceof Error ? lastError.message : String(lastError)})`\n );\n}\n\n/** What the route pass needs from the command line. */\nexport interface RouteOptions {\n /**\n * Path to a **Vite** config file, from `--config`. Undefined means Vite's own\n * discovery, the same as `timber dev`/`build` without the flag. A project\n * that builds with a custom Vite config has to be checkable with it too, or\n * `check` resolves a different app than `build` does (TIM-1332, round 4).\n */\n viteConfigFile?: string;\n}\n\n/** Everything the route scan needs, as the build itself resolves it. */\nexport interface RouteInputs {\n root: string;\n appDir: string;\n pageExtensions: string[] | undefined;\n}\n\n/** The subset of a resolved Vite plugin this module reads. */\nexport interface PluginWithApi {\n name: string;\n api?: unknown;\n}\n\n/**\n * Ask Vite for the resolved config, which is what carries timber's context.\n *\n * `resolveConfig` runs the whole config pipeline — config file discovery,\n * `config` and `configResolved` hooks — so the context it produces is the one\n * `timber build` would use. Measured at ~300-400ms on a real app; the type pass\n * it precedes costs far more.\n */\nconst defaultResolveViteConfig: ResolveViteConfig = async (\n inlineConfig,\n command,\n defaultMode,\n defaultNodeEnv\n) => {\n const { resolveConfig } = await import('vite');\n return resolveConfig(inlineConfig, command, defaultMode, defaultNodeEnv);\n};\n\n/**\n * The mode defaults `timber build` resolves under.\n *\n * `resolveConfig`'s own defaults are `'development'` for both, but nothing\n * reaches it with those on a build: `createBuilder` goes through Vite's\n * internal `resolveConfigToBuild`, which calls\n * `resolveConfig(inlineConfig, 'build', 'production', 'production')`. A config\n * written as `defineConfig(({ mode }) => …)`, or one that loads `.env.production`,\n * therefore resolves to a *different* app under the two. Passing the defaults\n * explicitly is what makes \"check validates what build builds\" true rather than\n * true-by-coincidence for configs that ignore mode (TIM-1332, round 6).\n */\nconst BUILD_MODE_DEFAULTS = ['production', 'production'] as const;\n\n/**\n * Resolve root, appDir and pageExtensions the way `timber build` resolves them.\n *\n * Reading `timber.config.ts` directly is **not** equivalent, which is the whole\n * reason this goes through Vite (TIM-1332, review round 3):\n *\n * - Config passed inline — `timber({ pageExtensions: [...] })` in\n * `vite.config.ts` — lives only in the plugin's closure. Nothing that\n * re-reads the config file can see it, so a scan built that way silently uses\n * default page extensions and writes a route map missing the app's pages.\n * `examples/next-playground-migration` is exactly this shape.\n * - `root` is Vite's resolved root, not the caller's cwd, and the two differ in\n * the monorepo layouts TIM-498 describes. `appDir` resolves against it.\n *\n * There is no fallback to a second, hand-rolled resolution. A project whose\n * Vite config does not produce the timber plugin cannot be built either, so a\n * check that quietly proceeded on a guessed tree would report a verdict about\n * an app that does not exist.\n */\nexport async function resolveRouteInputs(\n options: RouteOptions = {},\n deps: CheckDeps = {}\n): Promise<RouteInputs> {\n const resolveViteConfig = deps.resolveViteConfig ?? defaultResolveViteConfig;\n // `configFile: undefined` is Vite's own \"discover it\" value, so the default\n // path stays exactly what Vite does for `timber build` without `--config`.\n const { plugins } = await resolveViteConfig(\n { configFile: options.viteConfigFile },\n 'build',\n ...BUILD_MODE_DEFAULTS\n );\n\n const rootSync = plugins.find((plugin) => plugin.name === TIMBER_ROOT_SYNC_PLUGIN);\n if (!rootSync || !isTimberPluginApi(rootSync.api)) {\n throw new Error(\n `[timber] Could not read the resolved timber configuration from your Vite config.\\n\\n` +\n ` \\`timber check\\` resolves your project through Vite so it validates the same\\n` +\n ` routes \\`timber build\\` builds — including config passed inline to timber().\\n\\n` +\n ` Check that vite.config.ts exists and lists the timber plugin:\\n\\n` +\n ` import { timber } from '@timber-js/app';\\n` +\n ` export default { plugins: [timber()] };\\n`\n );\n }\n\n const ctx = rootSync.api.getContext();\n return { root: ctx.root, appDir: ctx.appDir, pageExtensions: ctx.config.pageExtensions };\n}\n\n/**\n * Resolve the app directory, scan it, fail on proven-fatal route\n * misconfigurations, print warnings, and write the route codegen the type pass\n * depends on.\n *\n * Error-level lint findings throw rather than print, matching what\n * `plugins/routing.ts` does at build time: the tree is not fit to publish, so\n * it must not reach codegen either. Warnings are printed and do not fail the\n * command — same severity contract as dev and build, so `timber check` cannot\n * disagree with them about what a valid app is.\n */\nexport async function checkRoutes(\n options: RouteOptions = {},\n deps: CheckDeps = {}\n): Promise<RouteInputs> {\n const inputs = await resolveRouteInputs(options, deps);\n const { root, appDir, pageExtensions } = inputs;\n\n const tree = scanRoutes(appDir, { pageExtensions });\n\n const warnings = lintConventions(tree, appDir);\n const fatal = warnings.filter((w) => w.level === 'error');\n if (fatal.length > 0) {\n throw new Error(formatConventionWarnings(fatal, { color: false }));\n }\n if (warnings.length > 0) {\n process.stderr.write(`${formatConventionWarnings(warnings)}\\n`);\n }\n\n // Awaited, unlike the dev/build path: the type pass reads these files, so a\n // failed write would be reported as type errors in the user's own code.\n // Reported as a codegen failure rather than surfaced as a bare `EROFS`/\n // `EACCES` from somewhere unnamed — the raw error says which path could not\n // be written but not which pass wanted it.\n try {\n await writeRouteCodegen(tree, appDir, root);\n } catch (err) {\n throw new Error(\n `[timber] Failed to write the generated route types, which the type check reads: ` +\n `${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n verifyCodegenImports(root);\n\n // Returned so the type pass runs against the same root these files landed in.\n return inputs;\n}\n\n/**\n * Verify that the import specifiers in the generated route types resolve on the\n * filesystem. A `.d.ts` whose import fails does NOT produce a TypeScript error —\n * every type that depends on it silently becomes `any`. The generated file\n * contains type-level `_AssertSchemaNotAny` / `_AssertCodecTypeNotAny` guards\n * that catch this at typecheck time, but a diagnostic here fires earlier and\n * names the exact import that is broken rather than leaving the user to decode\n * a constraint error.\n */\nexport function verifyCodegenImports(root: string): void {\n const dtsPath = join(root, CODEGEN_OUTPUT);\n let content: string;\n try {\n content = readFileSync(dtsPath, 'utf-8');\n } catch {\n return;\n }\n\n const dtsDir = dirname(dtsPath);\n\n // Check relative imports (default imports only — the generated codegen uses\n // `import type schema from '...'` for relative paths). Named imports from\n // relative paths are not emitted today; if codegen adds them, extend this.\n const RELATIVE_IMPORT_RE = /^import\\s+type\\s+\\w+\\s+from\\s+'(\\.\\.?\\/[^']+)'/gm;\n const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.tsx'];\n let match;\n while ((match = RELATIVE_IMPORT_RE.exec(content)) !== null) {\n const specifier = match[1];\n const base = join(dtsDir, specifier);\n const resolves = existsSync(base) || EXTENSIONS.some((ext) => existsSync(base + ext));\n if (!resolves) {\n process.stderr.write(\n `[timber] WARNING: the generated ${CODEGEN_OUTPUT} imports '${specifier}',\\n` +\n ` but no file resolves at ${base}{${EXTENSIONS.join(',')}}.\\n` +\n ` Every type that depends on this import will silently become \\`any\\`.\\n\\n` +\n ` Check that your app/ directory is where timber expects it.\\n\\n`\n );\n }\n }\n\n // Bare-specifier imports (`@timber-js/app/params`) are NOT checked here.\n // They are all dependencies of @timber-js/app itself — if timber is installed,\n // they resolve. And createRequire uses CJS resolution which cannot follow\n // ESM-only subpath exports, producing false warnings (TIM-1348 review).\n}\n\n/**\n * The production `RunTsgo`: spawn the compiler with its stdio inherited, so its\n * diagnostics stream to the terminal as they are produced (and are not capped\n * by a buffer, as `execFile` output would be).\n */\nconst spawnTsgo: RunTsgo = async (command, args, cwd) => {\n const { spawn } = await import('node:child_process');\n return new Promise<number | null>((resolve, reject) => {\n // No `shell: true`: Node would concatenate the argv into an unescaped\n // command string, so a project path containing a space would break.\n const child = spawn(command, args, { stdio: 'inherit', cwd });\n child.on('error', reject);\n child.on('close', (code) => resolve(code));\n });\n};\n\n/**\n * The production `ReadTsgoConfig`: `--showConfig`, with stdout captured.\n *\n * `maxBuffer` is raised well past `execFile`'s 1 MB default because the output\n * is one line per file in the program — a large app can exceed that, and\n * overflowing it would make this advisory go quiet on exactly the projects\n * where a misconfigured `include` costs the most. A size-dependent silence is\n * indistinguishable from \"everything is fine\".\n */\nconst execTsgoConfig: ReadTsgoConfig = async (command, args, cwd) => {\n const { execFile } = await import('node:child_process');\n return new Promise<string>((resolve, reject) => {\n execFile(command, args, { cwd, maxBuffer: 64 * 1024 * 1024 }, (err, stdout) =>\n err ? reject(err) : resolve(stdout)\n );\n });\n};\n\n/**\n * Warn when the generated route declarations will not reach the type checker.\n *\n * Writing `.timber/timber-routes.d.ts` and `timber-env.d.ts` is only half the\n * job: TypeScript loads them only if the project's `include`/`files` actually\n * pull `timber-env.d.ts` in (it is what `/// <reference>`s the route map). A\n * tsconfig with an explicit `include` that lists only source directories —\n * `[\"app\", \"*.config.ts\"]`, which is what `create-timber-app` shipped before\n * TIM-1332 — silently omits it, and every `<Link href>` then type-checks\n * against the empty placeholder instead of the generated route union. The\n * check would pass while answering the wrong question.\n *\n * The resolved file list comes from `tsgo --showConfig` rather than from our\n * own reading of the tsconfig: `include`, `exclude`, `files`, and `extends`\n * compose in ways that are the compiler's to decide, and a second\n * implementation of them would be a duplicate that drifts. `--showConfig` only\n * resolves globs, so it costs no type checking.\n *\n * This warns rather than fails. An app that never uses typed routes is\n * correct without those declarations, and a hard error would refuse it — the\n * one outcome a check must not produce for a working project. When the answer\n * cannot be determined (tsgo errored, output was not the expected JSON), the\n * warning is skipped: an advisory that fires on an unknown is noise.\n */\nasync function warnIfRouteTypesUnreachable(\n tsgoEntry: string,\n configArgs: string[],\n cwd: string,\n readConfig: ReadTsgoConfig\n): Promise<void> {\n let files: unknown;\n try {\n const raw = await readConfig(process.execPath, [tsgoEntry, '--showConfig', ...configArgs], cwd);\n files = (JSON.parse(raw) as { files?: unknown }).files;\n } catch {\n return;\n }\n if (!Array.isArray(files)) return;\n\n // Suffix match, not path resolution: `--showConfig` prints paths relative to\n // whichever tsconfig the compiler *found*, which for a bare `timber check`\n // is a directory we never learn. Over-matching only suppresses an advisory.\n //\n // The bare form is matched as well as the `/`-prefixed one. tsgo emits\n // `./timber-env.d.ts` today, but a leading `./` is cosmetic and an emitter\n // that dropped it would turn this into a warning printed at every correctly\n // configured project — the failure direction that trains people to ignore it.\n const reaches = files.some((file) => {\n if (typeof file !== 'string') return false;\n const normalized = file.replace(/\\\\/g, '/');\n return GENERATED_TYPE_PATHS.some(\n (path) => normalized === path || normalized.endsWith(`/${path}`)\n );\n });\n if (reaches) return;\n\n process.stderr.write(\n `[timber] The generated route types are not part of this TypeScript project, so\\n` +\n ` \\`<Link href>\\` and \\`useSegmentParams()\\` are being checked against empty\\n` +\n ` placeholders. Your tsconfig's \"include\" does not pull in timber-env.d.ts.\\n\\n` +\n ` To fix: add it to \"include\":\\n\\n` +\n ` \"include\": [\"app\", \"*.config.ts\", \"timber-env.d.ts\"]\\n\\n`\n );\n}\n\n/**\n * Run `tsgo --noEmit`, streaming its output.\n *\n * Rejects with the real numeric exit status on type errors. A failure to *start*\n * the compiler is reported separately — the historical bug this replaces\n * surfaced ENOENT as \"Type check failed with exit code undefined\", which read\n * as a type error and sent users looking at their own code.\n */\nexport async function runTypeCheck(\n options: CheckOptions = {},\n deps: CheckDeps = {}\n): Promise<void> {\n // The *resolved* root, handed over by the route pass — not `process.cwd()`.\n // The two differ whenever `--config` names a Vite config elsewhere, and the\n // route pass wrote `.timber/*` and `timber-env.d.ts` under the resolved one.\n // Running tsgo from cwd would then discover a different tsconfig entirely and\n // type-check a different project than the one just validated (TIM-1332, round\n // 5) — routes checked for the app, types checked for the monorepo around it.\n const root = options.root ?? process.cwd();\n const tsgoEntry = (deps.resolveTsgoEntry ?? (() => resolveTsgoEntry(root)))();\n const runTsgo = deps.runTsgo ?? spawnTsgo;\n\n // An explicit `--project` is a path the user typed at their own prompt, so it\n // is resolved against *their* cwd before the compiler is moved to the project\n // root. Without `--project`, tsgo discovers `tsconfig.json` from `root`,\n // which is where the declarations it needs were just written.\n const configArgs = options.config ? ['--project', resolve(process.cwd(), options.config)] : [];\n\n // Before checking: say so if the declarations the route pass just wrote will\n // not be part of the program. Otherwise the check passes while `<Link href>`\n // is measured against a placeholder. Same root and same argv as the check\n // itself, or it would inspect a different program than the one tsgo reads.\n await warnIfRouteTypesUnreachable(\n tsgoEntry,\n configArgs,\n root,\n deps.readTsgoConfig ?? execTsgoConfig\n );\n\n let code: number | null;\n try {\n code = await runTsgo(process.execPath, [tsgoEntry, '--noEmit', ...configArgs], root);\n } catch (err) {\n // Could not start the compiler at all. Kept distinct from a nonzero exit:\n // the version this replaced reported ENOENT as \"Type check failed with\n // exit code undefined\", which reads as a verdict on the user's types.\n throw new Error(\n `[timber] Failed to start the type checker: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n if (code === 0) return;\n\n // A null code means a signal killed the process rather than it exiting.\n // Say so instead of printing \"exit code null\".\n throw new Error(\n code === null\n ? 'Type check terminated before it finished'\n : `Type check failed with exit code ${code}`\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAM,0BAA0B;;AAGhC,IAAM,eAAe;;;;;;;AAQrB,IAAM,uBAAuB,CAAC,kBAAkB,cAAc;;;;;;;;;AAkE9D,SAAgB,iBACd,MACA,eAA4D,MAAM,cAChE,cAAc,IAAI,CAAC,CAAC,QAAQ,SAAS,GAC/B;CAIR,MAAM,aAAa,CAAC,YAAY,KAAK,KAAK,MAAM,cAAc,CAAC;CAC/D,IAAI;CAEJ,KAAK,MAAM,QAAQ,YACjB,IAAI;EAGF,MAAM,WAAW,YAAY,MAAM,GAAG,aAA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R,8CAA8C,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,GAC/F;CACF;CAEA,IAAI,SAAS,GAAG;CAIhB,MAAM,IAAI,MACR,SAAS,OACL,6CACA,oCAAoC,MAC1C;AACF"}
@@ -526,6 +526,7 @@ function lintConventions(tree, appDir) {
526
526
  checkClientLayouts(tree.root, warnings);
527
527
  checkClientBoundaryFiles(tree.root, warnings);
528
528
  if (tree.globalError) checkFileUseClientDirective(tree.globalError, "global-error", warnings);
529
+ checkSlotMiddleware(tree.root, warnings);
529
530
  return warnings;
530
531
  }
531
532
  function checkClientLayouts(node, warnings) {
@@ -746,6 +747,39 @@ function checkFileUseClientDirective(file, convention, warnings) {
746
747
  });
747
748
  }
748
749
  /**
750
+ * Error when middleware.ts appears inside a parallel slot subtree.
751
+ *
752
+ * Middleware is collected from the main matched segment chain only
753
+ * (route-matcher.ts `collectMiddlewareChain`). The slot resolver never
754
+ * walks `middleware` on its matched chain, so a middleware.ts under any
755
+ * `@slot/` directory silently never executes. `access.ts` in slot chains
756
+ * DOES run (via SlotAccessGate), making the asymmetry invisible unless
757
+ * you know to look.
758
+ *
759
+ * This is a build error rather than a warning: the file provably cannot
760
+ * run and its presence misleads the author into thinking the slot is
761
+ * middleware-protected.
762
+ *
763
+ * See design/07-routing.md §"Parallel Routes"
764
+ */
765
+ function checkSlotMiddleware(node, warnings) {
766
+ for (const [slotName, slotRoot] of Object.entries(node.slots)) collectSlotMiddleware(slotRoot, slotName, warnings);
767
+ for (const child of node.children) checkSlotMiddleware(child, warnings);
768
+ }
769
+ /**
770
+ * Walk a slot subtree and report every middleware.ts found.
771
+ */
772
+ function collectSlotMiddleware(node, slotName, warnings) {
773
+ if (node.middleware) warnings.push({
774
+ id: `SLOT_MIDDLEWARE:${node.middleware.filePath}`,
775
+ summary: `middleware.ts inside slot @${slotName} never executes: ${node.middleware.filePath}`,
776
+ details: ` File: ${node.middleware.filePath}\n\n Middleware is collected from the main route chain only.\n The slot resolver does not run middleware — this file is silently dead.\n (access.ts in slots does run via SlotAccessGate; middleware.ts does not.)\n\n To fix: Move the middleware logic into access.ts for slot-scoped auth,\n or into a middleware.ts on the main route chain outside the slot.\n`,
777
+ level: "error"
778
+ });
779
+ for (const child of node.children) collectSlotMiddleware(child, slotName, warnings);
780
+ for (const [nestedSlotName, nestedSlot] of Object.entries(node.slots)) collectSlotMiddleware(nestedSlot, nestedSlotName, warnings);
781
+ }
782
+ /**
749
783
  * Check if the app/ directory exists. Called before scanning.
750
784
  * Returns a warning if missing, or null if the directory exists.
751
785
  */
@@ -800,4 +834,4 @@ function formatConventionWarnings(warnings, options = {}) {
800
834
  //#endregion
801
835
  export { CODEGEN_OUTPUT as a, writeRouteCodegen as c, getPrerenderExport as i, buildDirToRouteMap as l, formatConventionWarnings as n, ENV_DTS_FILENAME as o, lintConventions as r, flushCodegenWrites as s, checkAppDirExists as t };
802
836
 
803
- //# sourceMappingURL=convention-lint-BnO5TyHD.js.map
837
+ //# sourceMappingURL=convention-lint-5KzoMg_A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convention-lint-5KzoMg_A.js","names":[],"sources":["../../src/routing/segment-codegen.ts","../../src/routing/codegen-write.ts","../../src/routing/export-detect.ts","../../src/routing/convention-lint.ts"],"sourcesContent":["/**\n * $segment type generation and directory-to-route mapping.\n *\n * Generates per-route $segment.d.ts files in .timber/types/ that mirror\n * the app/ directory structure. TypeScript's rootDirs feature makes these\n * importable as './$segment' from route files.\n *\n * Design doc: design/41-global-params.md §The $segment Module\n */\n\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { RouteTree, SegmentNode } from './types.ts';\n\n/** Info carried per directory for type generation. */\nexport interface SegmentInfo {\n /** The URL route pattern (groups and slots stripped). e.g. '/[artistSlug]/[year]' */\n route: string;\n /** The full tree path including groups and slots — uniquely identifies a segment.\n * e.g. '/(browse)/[artistSlug]/@shows/[year]' */\n segmentPath: string;\n}\n\n/**\n * Build a map of absolute filesystem directory → segment info.\n * Used by resolveId to map a $segment import's importer to the correct route,\n * and by writeSegmentTypes to generate per-route $segment.d.ts files.\n *\n * Walks every segment (not just leaves) so layouts and middleware\n * at any depth can import $segment.\n */\nexport function buildDirToRouteMap(tree: RouteTree, appDir: string): Map<string, SegmentInfo> {\n const map = new Map<string, SegmentInfo>();\n\n function walk(node: SegmentNode, fsPath: string, treePath: string): void {\n map.set(fsPath, {\n route: node.urlPath || '/',\n segmentPath: treePath || '/',\n });\n\n for (const child of node.children) {\n const childDir = join(fsPath, child.segmentName);\n const childTreePath = `${treePath}/${child.segmentName}`;\n walk(child, childDir, childTreePath);\n }\n for (const [slotName, slotNode] of Object.entries(node.slots)) {\n const slotDir = join(fsPath, `@${slotName}`);\n const slotTreePath = `${treePath}/@${slotName}`;\n walk(slotNode, slotDir, slotTreePath);\n }\n }\n\n walk(tree.root, appDir, '');\n return map;\n}\n\n/**\n * Generate the full $segment.d.ts content for a segment.\n */\nexport function generateSegmentDts(info: SegmentInfo): string {\n return [\n `export const ROUTE: '${info.route}';`,\n `export const SEGMENT_PATH: '${info.segmentPath}';`,\n '',\n ].join('\\n');\n}\n\n/**\n * Generate per-route $segment.d.ts files in .timber/types/ mirroring\n * the app/ directory structure. These files are importable via TypeScript's\n * rootDirs feature.\n */\nexport async function writeSegmentTypes(\n routeTree: RouteTree,\n appDir: string,\n root: string\n): Promise<void> {\n // Compute the relative prefix from project root to appDir.\n // e.g. if appDir is /project/src/app, relative is 'src/app'\n const relative = appDir.slice(root.length + 1);\n const typesBase = join(root, '.timber', 'types', relative);\n const map = buildDirToRouteMap(routeTree, appDir);\n\n const writes: Promise<void>[] = [];\n for (const [fsDir, info] of map) {\n // Mirror the app/ structure under .timber/types/\n const relDir = fsDir.slice(appDir.length); // e.g. '/[artistSlug]/[year]'\n const segmentDir = join(typesBase, relDir);\n const segmentFile = join(segmentDir, '$segment.d.ts');\n const content = generateSegmentDts(info);\n\n writes.push(\n mkdir(segmentDir, { recursive: true }).then(() => writeFile(segmentFile, content, 'utf-8'))\n );\n }\n\n await Promise.all(writes);\n}\n","/**\n * Route-map codegen writer.\n *\n * Materializes the generated route types on disk: `.timber/timber-routes.d.ts`,\n * `.timber/segment-types.d.ts` (via `writeSegmentTypes`), and the root\n * `timber-env.d.ts` that references them.\n *\n * Lives outside `plugins/routing.ts` because it has two callers with two\n * different failure policies: the dev/build plugin starts the write off the hot\n * path and logs failures, while `timber check` awaits it and treats a failure as\n * fatal — a type check run against absent or stale route types reports errors\n * about code that is fine. One implementation, two policies, so the bytes on\n * disk cannot drift between the two commands.\n *\n * Design docs: 09-typescript.md §\"Typed Routes\", 18-build-system.md\n */\n\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { generateRouteMap } from './codegen.ts';\nimport { writeSegmentTypes } from './segment-codegen.ts';\nimport type { RouteTree } from './types.ts';\n\n/**\n * Path (relative to the project root) of the generated route map declaration\n * file, and the name of the root file that `/// <reference>`s it.\n *\n * Exported because `timber check` has to answer whether the user's tsconfig\n * pulls these into the program — a question about these exact paths. It derives\n * them from here rather than restating them, so a rename cannot leave the check\n * looking for a file nothing writes.\n */\nexport const CODEGEN_OUTPUT = '.timber/timber-routes.d.ts';\n\n/** Root-level file that references the generated declarations. */\nexport const ENV_DTS_FILENAME = 'timber-env.d.ts';\n\n/**\n * Content of the timber-env.d.ts file written to the project root.\n *\n * Uses a triple-slash reference so TypeScript auto-discovers the generated\n * route map without the user needing to edit tsconfig.json — same pattern\n * as Next.js's next-env.d.ts.\n *\n * Also references `vite/client` so side-effect imports like\n * `import './globals.css'` type-check without ts(2882), and so\n * `import.meta.env`, `import.meta.hot`, `import.meta.glob`, asset\n * imports (`*.png`, `*.svg`, …), CSS modules, and `?url`/`?raw`/\n * `?inline` query variants all resolve without the user editing\n * tsconfig.json themselves. Next.js's next-env.d.ts plays the same\n * role via `next/types/global`.\n *\n * `vite` is a peer dep of `@timber-js/app`, so the reference always\n * resolves in a correctly-installed project.\n */\nconst TIMBER_ENV_DTS = [\n '// This file is auto-generated by timber.js. Do not edit.',\n '// It ensures TypeScript picks up the generated route types and',\n '// Vite-provided ambient types (CSS, assets, import.meta.env, HMR).',\n '/* eslint-disable @typescript-eslint/triple-slash-reference */',\n '/// <reference path=\".timber/timber-routes.d.ts\" />',\n '/// <reference types=\"vite/client\" />',\n '/// <reference types=\"react/canary\" />',\n '/// <reference types=\"react-dom/canary\" />',\n '',\n].join('\\n');\n\n/**\n * Codegen writes that have been started but have not yet landed on disk.\n *\n * `writeRouteCodegen` is deliberately unawaited on the dev/build hot path,\n * which leaves that caller no way to know the files exist yet. Anything that\n * tears down the project root — a build process exiting, a test removing its\n * temp root — then races the writes: `rmSync` empties a directory that a\n * pending `mkdir` immediately recreates, and the removal fails with ENOTEMPTY.\n *\n * Every started write registers here and deregisters when it settles, so\n * `flushCodegenWrites()` can await them instead of guessing at a delay.\n */\nconst pendingCodegenWrites = new Set<Promise<void>>();\n\n/**\n * Resolve once every codegen write started so far has landed on disk.\n *\n * Safe to call at any time and from anywhere — writes are tracked per process,\n * not per plugin instance, so a caller does not need a handle on the plugin\n * that started them. Never rejects: the tracked copy of each write has its\n * rejection swallowed, so a failing write cannot turn a teardown barrier into\n * an unhandled rejection. Callers that care about failure await the promise\n * `writeRouteCodegen` returned instead.\n */\nexport async function flushCodegenWrites(): Promise<void> {\n // Loop rather than a single Promise.all: a write started while we were\n // awaiting would otherwise be missed, and the set would still be non-empty\n // on return.\n //\n // Each round drops what it awaited rather than trusting the per-write\n // `finally` to have run, so the two removal paths are independent — a\n // deregistration that stopped firing would leak memory in dev, but it can\n // never turn this into a spin.\n while (pendingCodegenWrites.size > 0) {\n const inFlight = [...pendingCodegenWrites];\n await Promise.all(inFlight);\n for (const write of inFlight) pendingCodegenWrites.delete(write);\n }\n}\n\n/**\n * Write the generated route map, segment types, and the timber-env.d.ts\n * reference file for `tree`.\n *\n * Returns a promise that **rejects** if any write fails. The dev/build plugin\n * does not await it (types are a developer convenience there, not a runtime\n * dependency) and logs instead; `timber check` awaits it and fails the command.\n * Either way the write is registered with `flushCodegenWrites()`.\n */\nexport function writeRouteCodegen(tree: RouteTree, appDir: string, root: string): Promise<void> {\n const timberDir = join(root, '.timber');\n const content = generateRouteMap(tree, { appDir, outputDir: timberDir });\n const routesPath = join(root, CODEGEN_OUTPUT);\n const envPath = join(root, ENV_DTS_FILENAME);\n\n const done = mkdir(timberDir, { recursive: true })\n .then(() =>\n Promise.all([\n writeFile(routesPath, content, 'utf-8'),\n writeFile(envPath, TIMBER_ENV_DTS, 'utf-8'),\n writeSegmentTypes(tree, appDir, root),\n ])\n )\n .then(() => undefined);\n\n // The tracked copy swallows rejection so `flushCodegenWrites` — a teardown\n // barrier — never rejects and never leaves an unhandled rejection behind.\n // The returned promise keeps its rejection for callers that want it.\n const tracked = done.catch(() => undefined);\n pendingCodegenWrites.add(tracked);\n void tracked.finally(() => pendingCodegenWrites.delete(tracked));\n\n return done;\n}\n","/**\n * AST-based export detection for route files.\n *\n * Uses Vite's `parseAst` (backed by oxc) to precisely detect named and\n * default exports, replacing the regex-based approach that was fragile\n * with TypeScript syntax (type exports, `as` aliases, comments, etc.).\n */\n\nimport { existsSync } from 'node:fs';\nimport { parseAst } from 'vite';\nimport { readFileCached } from './file-cache.ts';\n\ninterface AstNode {\n type: string;\n exportKind?: string;\n declaration?: AstNode;\n specifiers?: Array<{\n exported?: { name: string };\n local?: { name: string };\n exportKind?: string;\n }>;\n id?: { name: string };\n declarations?: Array<{ id?: { name: string }; init?: AstNode }>;\n /** Set on re-exports: `export { X } from './y'`. Absent on local exports. */\n source?: { value?: string } | null;\n /** Set on runtime-transparent wrappers: `X as T`, `X satisfies T`, `(X)`, `X!`. */\n expression?: AstNode;\n /** Set on `Identifier` nodes. */\n name?: string;\n}\n\ninterface ProgramNode {\n body: AstNode[];\n}\n\nfunction tryParse(source: string): ProgramNode | null {\n try {\n return parseAst(source, { lang: 'tsx' }) as unknown as ProgramNode;\n } catch {\n return null;\n }\n}\n\n/**\n * Collect all named export identifiers from a parsed program.\n * Handles: `export function X`, `export const X`, `export { X }`,\n * `export { X } from '...'`, `export { Y as X }`.\n */\nfunction collectNamedExports(program: ProgramNode): Set<string> {\n const names = new Set<string>();\n for (const stmt of program.body) {\n if (stmt.type !== 'ExportNamedDeclaration') continue;\n // Skip `export type ...` declarations — they're erased at runtime\n if (stmt.exportKind === 'type') continue;\n\n if (stmt.declaration) {\n if (stmt.declaration.id?.name) {\n names.add(stmt.declaration.id.name);\n }\n if (stmt.declaration.declarations) {\n for (const decl of stmt.declaration.declarations) {\n if (decl.id?.name) names.add(decl.id.name);\n }\n }\n }\n\n if (stmt.specifiers) {\n for (const spec of stmt.specifiers) {\n // Skip `export { type X }` — per-specifier type exports\n if (spec.exportKind === 'type') continue;\n if (spec.exported?.name && spec.exported.name !== 'default') {\n names.add(spec.exported.name);\n }\n }\n }\n }\n return names;\n}\n\n/**\n * The specifier exporting a *runtime* default from this statement, if any.\n *\n * Type-only exports erase, so they are not default exports at runtime — and\n * TypeScript spells that two ways, on two different nodes: `export type { X as\n * default }` marks the **statement**, `export { type X as default }` marks the\n * **specifier**. Both have to be checked, or a type alias reads as a component:\n * a status file whose only default is a type has nothing for the error boundary\n * to receive (the renderer's `mod?.default` skips it), so treating it as one\n * would fail a build over a file that cannot break anything.\n *\n * One implementation because two callers must agree on what \"has a default\n * export\" means: `hasDefaultExport` decides whether to warn that a page has\n * none, and `fileDefaultExportIsLocalValue` decides whether to fail the build.\n */\nfunction defaultSpecifier(stmt: AstNode): NonNullable<AstNode['specifiers']>[number] | null {\n if (stmt.type !== 'ExportNamedDeclaration' || !stmt.specifiers) return null;\n if (stmt.exportKind === 'type') return null;\n for (const spec of stmt.specifiers) {\n if (spec.exportKind === 'type') continue;\n if (spec.exported?.name === 'default') return spec;\n }\n return null;\n}\n\n/**\n * Check whether a program has a default export.\n * Handles: `export default ...`, `export { X as default }`,\n * `export { default } from '...'`. Type-only defaults do not count —\n * see `defaultSpecifier`.\n */\nfunction hasDefaultExport(program: ProgramNode): boolean {\n for (const stmt of program.body) {\n if (stmt.type === 'ExportDefaultDeclaration') return true;\n if (defaultSpecifier(stmt)) return true;\n }\n return false;\n}\n\n/**\n * Check whether a program has any bare `export * from '...'` declarations.\n * Excludes `export * as X from '...'` (namespace re-exports) since those\n * create a namespace object, not individual top-level exports.\n */\nfunction hasStarExport(program: ProgramNode): boolean {\n return program.body.some(\n (stmt) =>\n stmt.type === 'ExportAllDeclaration' && !(stmt as any).exported && stmt.exportKind !== 'type'\n );\n}\n\n/**\n * Check if a file exports a specific named export.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasExport(filePath: string, exportName: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return collectNamedExports(program).has(exportName);\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file has any of the given named exports.\n * Returns the set of matching export names.\n */\nexport function fileHasAnyExport(filePath: string, exportNames: readonly string[]): Set<string> {\n const matches = new Set<string>();\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return matches;\n const exports = collectNamedExports(program);\n for (const name of exportNames) {\n if (exports.has(name)) matches.add(name);\n }\n } catch {\n // Graceful fallback: return empty set\n }\n return matches;\n}\n\n/**\n * Check if a file has a default export.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasDefaultExport(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return hasDefaultExport(program);\n } catch {\n return false;\n }\n}\n\n/** Node types whose value is unambiguously constructed by this module. */\nconst FUNCTION_LIKE = new Set([\n 'FunctionDeclaration',\n 'FunctionExpression',\n 'ArrowFunctionExpression',\n 'ClassDeclaration',\n 'ClassExpression',\n]);\n\n/**\n * Expression wrappers that erase at runtime and so cannot change where a value\n * was constructed: `X as T`, `X satisfies T`, `<T>X`, `X!`, `X<T>`, `(X)`.\n */\nconst TRANSPARENT_WRAPPERS = new Set([\n 'TSAsExpression',\n 'TSSatisfiesExpression',\n 'TSTypeAssertion',\n 'TSNonNullExpression',\n 'TSInstantiationExpression',\n 'ParenthesizedExpression',\n]);\n\n/**\n * Strip runtime-transparent wrappers so the node underneath can be classified.\n *\n * Without this, `(() => <h1 />) satisfies React.FC` reads as a\n * `TSSatisfiesExpression` rather than the arrow function it compiles to, and a\n * provably-local component is misread as one whose origin cannot be\n * determined — turning a build error into a warning.\n */\nfunction unwrapTransparent(node: AstNode): AstNode {\n let current = node;\n while (TRANSPARENT_WRAPPERS.has(current.type) && current.expression) {\n current = current.expression;\n }\n return current;\n}\n\n/**\n * Whether `name` is bound at module top level to a function or class written\n * in this file. An imported binding can never match: imports are\n * `ImportDeclaration` specifiers, not function/class/variable declarations,\n * and a module-level name cannot be both.\n */\nfunction bindsLocalFunction(program: ProgramNode, name: string): boolean {\n for (const stmt of program.body) {\n // `export function X() {}` binds X locally too — unwrap the export.\n const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;\n if (!decl) continue;\n if (\n (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') &&\n decl.id?.name === name\n ) {\n return true;\n }\n if (decl.type === 'VariableDeclaration') {\n for (const d of decl.declarations ?? []) {\n if (d.id?.name === name && d.init && FUNCTION_LIKE.has(unwrapTransparent(d.init).type)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Whether the default export is *provably* a value constructed by this module:\n * `export default function/class/() => {}`, or a name bound to a function or\n * class declared here — whether it leaves via `export default Name` or\n * `export { Name as default }`. Both spellings are the same fact about where\n * the value was built, so both must answer the same way.\n *\n * This is the sound half of \"is this a server component?\". A file with no\n * `'use client'` directive whose default export is built here is a server\n * component, full stop. Everything else — `export { default } from\n * './client-thing'`, `export default Imported`, `export default memo(X)`,\n * an unparseable file — returns false, because the exported value may have\n * been minted in a module that *does* carry the directive. Callers must not\n * infer \"server component\" from a missing directive alone.\n */\nexport function fileDefaultExportIsLocalValue(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n for (const stmt of program.body) {\n if (stmt.type === 'ExportDefaultDeclaration') {\n const decl = stmt.declaration && unwrapTransparent(stmt.declaration);\n if (!decl) return false;\n if (FUNCTION_LIKE.has(decl.type)) return true;\n if (decl.type === 'Identifier' && decl.name) {\n return bindsLocalFunction(program, decl.name);\n }\n return false;\n }\n\n // `export { Name as default }` — the same default export by another\n // spelling. `hasDefaultExport` already counts it, so an analysis that\n // skipped it here would let the exact defect this powers slip through\n // as a warning.\n const spec = defaultSpecifier(stmt);\n if (spec) {\n // `export { X as default } from './client-thing'` re-exports another\n // module's value — the directive governing it lives over there.\n if (stmt.source) return false;\n return spec.local?.name ? bindsLocalFunction(program, spec.local.name) : false;\n }\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file has any `export * from '...'` declarations.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasStarExport(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return hasStarExport(program);\n } catch {\n return false;\n }\n}\n\n/**\n * Parsed value of `export const prerender` from a route file.\n *\n * - `true` / `false` — literal boolean\n * - `{ ttl?, tags? }` — ISR options object (prerender: true is implied)\n * - `undefined` — no `export const prerender` found\n *\n * See design/45-cache-lifetimes.md §\"Route-Level Static\".\n */\nexport type PrerenderExportValue = boolean | { ttl?: number; tags?: string[] };\n\nfunction extractLiteralValue(node: AstNode): unknown {\n if (!node) return undefined;\n const n = node as any;\n if (n.type === 'Literal') return n.value;\n if (n.type === 'UnaryExpression' && n.operator === '-' && n.argument?.type === 'Literal') {\n return -(n.argument.value as number);\n }\n if (n.type === 'ArrayExpression') {\n const elements = n.elements as AstNode[] | undefined;\n if (!elements) return undefined;\n const result: unknown[] = [];\n for (const el of elements) {\n const v = extractLiteralValue(el);\n if (v === undefined) return undefined;\n result.push(v);\n }\n return result;\n }\n return undefined;\n}\n\nfunction extractObjectLiteral(node: AstNode): Record<string, unknown> | undefined {\n if ((node as any).type !== 'ObjectExpression') return undefined;\n const props = (node as any).properties as AstNode[] | undefined;\n if (!props) return undefined;\n const result: Record<string, unknown> = {};\n for (const prop of props) {\n const p = prop as any;\n if (p.type === 'SpreadElement') return undefined;\n if (p.type !== 'Property' || p.computed) return undefined;\n const key =\n p.key?.type === 'Identifier'\n ? p.key.name\n : p.key?.type === 'Literal'\n ? String(p.key.value)\n : undefined;\n if (!key) return undefined;\n const value = extractLiteralValue(p.value);\n if (value === undefined) return undefined;\n result[key] = value;\n }\n return result;\n}\n\n/**\n * Extract the value of `export const prerender` from a file.\n * Returns undefined if the file doesn't export `prerender` or can't be parsed.\n *\n * Supports:\n * export const prerender = true;\n * export const prerender = false;\n * export const prerender = { ttl: 3600, tags: ['docs'] };\n */\nexport function getPrerenderExport(filePath: string): PrerenderExportValue | undefined {\n if (!existsSync(filePath)) return undefined;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return undefined;\n\n for (const stmt of program.body) {\n if (stmt.type !== 'ExportNamedDeclaration') continue;\n if (stmt.exportKind === 'type') continue;\n if (!stmt.declaration) continue;\n const decl = stmt.declaration;\n if (decl.type !== 'VariableDeclaration') continue;\n const declarations = decl.declarations as\n | Array<{\n id?: { name?: string };\n init?: AstNode;\n }>\n | undefined;\n if (!declarations) continue;\n for (const d of declarations) {\n if (d.id?.name !== 'prerender' || !d.init) continue;\n const init = d.init as any;\n if (init.type === 'Literal' && typeof init.value === 'boolean') {\n return init.value;\n }\n if (init.type === 'ObjectExpression') {\n const obj = extractObjectLiteral(init);\n if (!obj) return undefined;\n const result: { ttl?: number; tags?: string[] } = {};\n if ('ttl' in obj && typeof obj.ttl === 'number') result.ttl = obj.ttl;\n if (\n 'tags' in obj &&\n Array.isArray(obj.tags) &&\n obj.tags.every((t: unknown) => typeof t === 'string')\n ) {\n result.tags = obj.tags as string[];\n }\n return result;\n }\n return undefined;\n }\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Check if a file starts with a specific directive (e.g. \"use client\").\n * Directives are string literal expression statements at the top of the file.\n */\nexport function fileHasDirective(filePath: string, directive: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n for (const stmt of program.body) {\n if (stmt.type !== 'ExpressionStatement') break;\n const expr = (stmt as any).expression;\n if (expr?.type !== 'Literal' || typeof expr.value !== 'string') break;\n if (expr.value === directive) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n","/**\n * Convention linter — validates common misconfigurations in the route tree.\n *\n * Runs at scan time (build and dev startup). Each check produces a warning\n * with the file path, what's wrong, and what to do about it.\n *\n * Most checks are warnings — they don't block the build. The goal is to catch\n * issues that would otherwise produce cryptic runtime behavior (silent 404s,\n * empty pages, confusing React errors).\n *\n * A check emits `level: 'error'` only when the misconfiguration is *proven*\n * (never inferred from an absence the analysis cannot see through) and fatal\n * to rendering. `plugins/routing.ts` turns those into a thrown build error,\n * so a false positive there refuses a working app — see\n * `classifyClientBoundaryFile` for how that bar is met.\n *\n * Design doc: 07-routing.md, 10-error-handling.md\n */\n\nimport { existsSync } from 'node:fs';\nimport type { RouteFile, RouteTree, SegmentNode } from './types.ts';\nimport { swallow } from '../server/logger.ts';\nimport {\n fileDefaultExportIsLocalValue,\n fileHasAnyExport,\n fileHasDefaultExport,\n fileHasDirective,\n fileHasStarExport,\n} from './export-detect.ts';\n\n// ─── Types ──────────────────────────────────────────────────────────────────\n\nexport interface ConventionWarning {\n /** Warning ID for deduplication and filtering. */\n id: string;\n /** Human-readable single-line summary. */\n summary: string;\n /** Multi-line details with file path and fix suggestion. */\n details: string;\n /** Severity: 'warn' for potential issues, 'error' for definite misconfigurations. */\n level: 'warn' | 'error';\n}\n\n// ─── Lint Rules ─────────────────────────────────────────────────────────────\n\n/**\n * Run all convention lint checks on a route tree.\n *\n * Returns an array of warnings. Empty array means everything looks good.\n */\nexport function lintConventions(tree: RouteTree, appDir: string): ConventionWarning[] {\n const warnings: ConventionWarning[] = [];\n\n // Check 1: app/ directory exists (caller should check before scanning,\n // but we validate the root has at least one routable file)\n checkEmptyApp(tree.root, appDir, warnings);\n\n // Check 2: route.ts without recognized HTTP method exports\n checkRouteExports(tree.root, warnings);\n\n // Check 3: Segments with layout but no page/route anywhere in subtree\n // (not a misconfiguration per se — layouts without pages are valid for\n // route groups. Skip this check.)\n\n // Check 4: Root segment has no layout.tsx (no HTML shell)\n checkRootLayout(tree.root, warnings);\n\n // Check 5: page.tsx / layout.tsx without default export\n checkDefaultExports(tree.root, warnings);\n\n // Check 6: Client layouts cannot suppress server children before Flight\n // serializes them. They remain valid UI boundaries, but not authorization\n // or data-hiding boundaries.\n checkClientLayouts(tree.root, warnings);\n\n // Check 7: error.tsx / 404.tsx / 4xx.tsx / … without 'use client' directive\n checkClientBoundaryFiles(tree.root, warnings);\n if (tree.globalError) {\n checkFileUseClientDirective(tree.globalError, 'global-error', warnings);\n }\n\n // Check 8: middleware.ts inside a parallel slot subtree (silently dead)\n checkSlotMiddleware(tree.root, warnings);\n\n return warnings;\n}\n\nfunction checkClientLayouts(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.layout && isScriptExtension(node.layout.extension)) {\n try {\n const isClient = fileHasDirective(node.layout.filePath, 'use client');\n const isProvablyServer = fileDefaultExportIsLocalValue(node.layout.filePath);\n if (isClient || !isProvablyServer) {\n const certainty = isClient\n ? `This layout is a client component.`\n : `Timber cannot prove this layout is a server component because its default export comes from another module or an opaque expression.`;\n warnings.push({\n id: `CLIENT_LAYOUT_NOT_AUTH_BOUNDARY:${node.layout.filePath}`,\n summary: isClient\n ? `Client layout cannot securely suppress server children: ${node.layout.filePath}`\n : `Layout may resolve to a client component and cannot be trusted as an auth boundary: ${node.layout.filePath}`,\n details:\n ` File: ${node.layout.filePath}\\n\\n` +\n ` ${certainty}\\n` +\n ` React Flight resolves server content passed to a client layout before the layout runs in the browser.\\n` +\n ` Conditionally omitting children here does not prevent descendant server components from executing or being serialized.\\n\\n` +\n ` To fix: Put authorization in access.ts or a provably server layout with a locally defined default component, and keep client components inside that boundary.\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable layout file ${node.layout.filePath}`);\n }\n }\n for (const child of node.children) checkClientLayouts(child, warnings);\n for (const slot of Object.values(node.slots)) checkClientLayouts(slot, warnings);\n}\n\n// ─── Check: Empty App ───────────────────────────────────────────────────────\n\n/**\n * Warn when the app/ directory has no routable files at all.\n *\n * This catches the \"I created app/ but didn't add any pages\" case where\n * every request silently 404s with no guidance.\n */\nfunction checkEmptyApp(root: SegmentNode, appDir: string, warnings: ConventionWarning[]): void {\n if (hasAnyRoutable(root)) return;\n\n warnings.push({\n id: 'EMPTY_APP',\n summary: 'No pages or route handlers found in app/',\n details:\n ` Directory: ${appDir}\\n\\n` +\n ' Your app/ directory has no page.tsx or route.ts files.\\n' +\n ' Every request will return 404.\\n\\n' +\n ' To fix: Create app/page.tsx with a default export:\\n\\n' +\n ' export default function Home() {\\n return <h1>Hello</h1>;\\n }\\n',\n level: 'warn',\n });\n}\n\n/**\n * Check if a segment tree has any routable files (page or route) anywhere.\n */\nfunction hasAnyRoutable(node: SegmentNode): boolean {\n if (node.page || node.route) return true;\n for (const child of node.children) {\n if (hasAnyRoutable(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyRoutable(slot)) return true;\n }\n return false;\n}\n\n/**\n * Check if a segment tree has any page files (not just route handlers).\n * Used by checkRootLayout to avoid false positives for API-only apps (TIM-794).\n * API-only apps (just route.ts handlers) don't need a root layout.\n */\nfunction hasAnyPage(node: SegmentNode): boolean {\n if (node.page) return true;\n for (const child of node.children) {\n if (hasAnyPage(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyPage(slot)) return true;\n }\n return false;\n}\n\n// ─── Check: Route Exports ───────────────────────────────────────────────────\n\n/** HTTP methods that route.ts can export. */\nconst HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const;\n\n/**\n * Warn when a route.ts file doesn't appear to export any recognized HTTP methods.\n *\n * Uses AST-based detection via parseAst for precise matching.\n * Falls back silently when the file can't be parsed (syntax errors produce\n * no spurious warning — the TS compiler will catch those).\n */\nfunction checkRouteExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.route) {\n const filePath = node.route.filePath;\n try {\n const methods = fileHasAnyExport(filePath, HTTP_METHODS);\n if (methods.size === 0 && !fileHasStarExport(filePath)) {\n const hasDefault = fileHasDefaultExport(filePath);\n const hint = hasDefault\n ? ' It looks like you have a default export. route.ts uses named exports\\n' +\n ' for HTTP methods (GET, POST, etc.), not a default export.\\n'\n : '';\n\n warnings.push({\n id: 'ROUTE_NO_METHODS',\n summary: `route.ts has no HTTP method exports: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ' route.ts files must export named HTTP method handlers.\\n' +\n ' Without them, the route matches but returns 405 Method Not Allowed.\\n\\n' +\n hint +\n ' Example:\\n\\n' +\n ' export function GET(ctx: RouteContext) {\\n' +\n \" return Response.json({ hello: 'world' });\\n\" +\n ' }\\n',\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable route.ts ${filePath}`);\n }\n }\n\n // Recurse\n for (const child of node.children) {\n checkRouteExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkRouteExports(slot, warnings);\n }\n}\n\n// ─── Check: Root Layout ─────────────────────────────────────────────────────\n\n/**\n * Warn when the root segment has no layout.tsx.\n *\n * Without a root layout, there's no HTML shell (<html>, <body>).\n * The page will render but may have hydration issues or no proper document structure.\n */\nfunction checkRootLayout(root: SegmentNode, warnings: ConventionWarning[]): void {\n if (root.layout) return;\n\n // Only warn if there are pages — API-only apps (just route.ts handlers)\n // don't need a root layout (TIM-794).\n if (!hasAnyPage(root)) return;\n\n warnings.push({\n id: 'NO_ROOT_LAYOUT',\n summary: 'No root layout.tsx found',\n details:\n ' Your app has pages but no root layout.\\n' +\n ' Without app/layout.tsx, pages have no <html> or <body> wrapper.\\n\\n' +\n ' To fix: Create app/layout.tsx:\\n\\n' +\n ' export default function RootLayout({ children }: { children: React.ReactNode }) {\\n' +\n ' return (\\n' +\n ' <html lang=\"en\">\\n' +\n ' <body>{children}</body>\\n' +\n ' </html>\\n' +\n ' );\\n' +\n ' }\\n',\n level: 'warn',\n });\n}\n\n// ─── Check: Default Exports ───────────────────────────────────────────\n\n/**\n * Warn when page.tsx or layout.tsx files don't have a default export.\n *\n * Without a default export:\n * - page.tsx: the page renders nothing (empty content)\n * - layout.tsx: the layout module loads but has no component to render\n *\n * Uses AST-based detection via parseAst for precise matching. Falls back\n * silently when the file can't be parsed (no spurious warning on syntax errors).\n */\nfunction checkDefaultExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n // Check page files (tsx/ts/jsx/js only — not mdx, which is default-exported by the mdx compiler)\n if (node.page && isScriptExtension(node.page.extension)) {\n checkFileDefaultExport(node.page.filePath, 'page', warnings);\n }\n\n // Check layout files\n if (node.layout && isScriptExtension(node.layout.extension)) {\n checkFileDefaultExport(node.layout.filePath, 'layout', warnings);\n }\n\n // Recurse\n for (const child of node.children) {\n checkDefaultExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkDefaultExports(slot, warnings);\n }\n}\n\nfunction isScriptExtension(ext: string): boolean {\n return ext === 'tsx' || ext === 'ts' || ext === 'jsx' || ext === 'js';\n}\n\nfunction checkFileDefaultExport(\n filePath: string,\n fileType: string,\n warnings: ConventionWarning[]\n): void {\n try {\n if (!fileHasDefaultExport(filePath)) {\n warnings.push({\n id: `NO_DEFAULT_EXPORT:${filePath}`,\n summary: `${fileType}.tsx has no default export: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${fileType}.tsx files must export a default React component.\\n` +\n ` Without a default export, the ${fileType === 'page' ? 'page renders nothing' : 'layout has no component to wrap children'}.\\n\\n` +\n ` To fix: Add a default export:\\n\\n` +\n ` export default function My${fileType === 'page' ? 'Page' : 'Layout'}(${fileType === 'layout' ? '{ children }' : ''}) {\\n` +\n ` return ${fileType === 'layout' ? '<div>{children}</div>' : '<h1>Hello</h1>'};\\n` +\n ` }\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${fileType} file ${filePath}`);\n }\n}\n\n// ─── Check: Client Boundary Directive ───────────────────────────────────────\n\n/**\n * Check every file the renderer hands to `TimberErrorBoundary` as a component\n * prop: `error.tsx`, `global-error.tsx`, and the status-code family\n * (`404.tsx`, `4xx.tsx`, `503.tsx`, …).\n *\n * `TimberErrorBoundary` is a client component, so a server component passed as\n * `fallbackComponent` is a function crossing the RSC → client boundary. React\n * Flight refuses to serialize it, and because the boundary wraps the segment's\n * *children*, the failure hits every page under that segment — not just the\n * error path. The raw message (\"Functions cannot be passed directly to Client\n * Components\") names neither the file nor the fix (TIM-1329).\n *\n * `.json` status files never reach React at all, and are not in `statusFiles`.\n */\nfunction checkClientBoundaryFiles(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.error) {\n checkFileUseClientDirective(node.error, 'error', warnings);\n }\n\n for (const [key, file] of Object.entries(node.statusFiles ?? {})) {\n checkFileUseClientDirective(file, key, warnings);\n }\n\n for (const child of node.children) {\n checkClientBoundaryFiles(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkClientBoundaryFiles(slot, warnings);\n }\n}\n\n/**\n * `'client'` — carries the directive.\n * `'server'` — proven server component: no directive, and the default export is\n * a function or class built by this very module, so no other file's directive\n * can be governing it.\n * `'unknown'` — no directive, but the exported value may come from elsewhere\n * (`export { default } from './client-thing'`), or the file could not be\n * read or parsed. Never escalated to a build error.\n */\ntype ClientBoundaryVerdict = 'client' | 'server' | 'unknown';\n\nfunction classifyClientBoundaryFile(filePath: string): ClientBoundaryVerdict {\n if (fileHasDirective(filePath, 'use client')) return 'client';\n if (fileDefaultExportIsLocalValue(filePath)) return 'server';\n return 'unknown';\n}\n\n/** Example component name for the fix snippet, keyed by convention name. */\nfunction exampleComponentName(convention: string): string {\n if (convention === 'global-error') return 'GlobalError';\n if (convention === 'error') return 'ErrorBoundary';\n if (convention === '404') return 'NotFound';\n return 'StatusPage';\n}\n\n/**\n * @param file the route file (its extension decides whether the check applies)\n * @param convention the convention name — `error`, `global-error`, `404`, `4xx`, …\n */\nfunction checkFileUseClientDirective(\n file: RouteFile,\n convention: string,\n warnings: ConventionWarning[]\n): void {\n // Only script extensions need the 'use client' check — .json status files\n // never reach React at all, and are not in `statusFiles`.\n if (!isScriptExtension(file.extension)) return;\n\n const filePath = file.filePath;\n const label = `${convention}.${file.extension}`;\n let verdict: ClientBoundaryVerdict;\n try {\n verdict = classifyClientBoundaryFile(filePath);\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${label} file ${filePath}`);\n return;\n }\n if (verdict === 'client') return;\n\n const isError = verdict === 'server';\n const name = exampleComponentName(convention);\n const props =\n convention === 'error' || convention === 'global-error' ? '{ error, reset }' : '{ status }';\n\n warnings.push({\n id: `NEEDS_USE_CLIENT:${filePath}`,\n summary: isError\n ? `${label} is a server component and must be a client component: ${filePath}`\n : `${label} may be missing 'use client': ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${label} is handed to timber's error boundary — a client\\n` +\n ' component — as a prop. A server component cannot cross that boundary:\\n' +\n ' React fails with \"Functions cannot be passed directly to Client\\n' +\n ' Components\", and every page under this segment fails to render.\\n\\n' +\n (isError\n ? \" To fix: Add 'use client' as the first line of the file:\\n\\n\" +\n \" 'use client';\\n\\n\" +\n ` export default function ${name}(${props}) {\\n` +\n ' return <h1>…</h1>;\\n' +\n ' }\\n'\n : // The default export comes from somewhere this analysis cannot follow\n // — a re-export, an imported binding, a wrapper call. It may well\n // already be a client component, so say what was checked rather than\n // assert a break.\n \" This file has no 'use client' directive, and its default export\\n\" +\n ' comes from elsewhere, so timber cannot tell which it is. If the\\n' +\n \" module it re-exports starts with 'use client', nothing is wrong\\n\" +\n ' and you can ignore this. Otherwise add the directive there.\\n'),\n level: isError ? 'error' : 'warn',\n });\n}\n\n// ─── Check: Slot Middleware ─────────────────────────────────────────────────\n\n/**\n * Error when middleware.ts appears inside a parallel slot subtree.\n *\n * Middleware is collected from the main matched segment chain only\n * (route-matcher.ts `collectMiddlewareChain`). The slot resolver never\n * walks `middleware` on its matched chain, so a middleware.ts under any\n * `@slot/` directory silently never executes. `access.ts` in slot chains\n * DOES run (via SlotAccessGate), making the asymmetry invisible unless\n * you know to look.\n *\n * This is a build error rather than a warning: the file provably cannot\n * run and its presence misleads the author into thinking the slot is\n * middleware-protected.\n *\n * See design/07-routing.md §\"Parallel Routes\"\n */\nfunction checkSlotMiddleware(node: SegmentNode, warnings: ConventionWarning[]): void {\n for (const [slotName, slotRoot] of Object.entries(node.slots)) {\n collectSlotMiddleware(slotRoot, slotName, warnings);\n }\n for (const child of node.children) {\n checkSlotMiddleware(child, warnings);\n }\n}\n\n/**\n * Walk a slot subtree and report every middleware.ts found.\n */\nfunction collectSlotMiddleware(\n node: SegmentNode,\n slotName: string,\n warnings: ConventionWarning[]\n): void {\n if (node.middleware) {\n warnings.push({\n id: `SLOT_MIDDLEWARE:${node.middleware.filePath}`,\n summary: `middleware.ts inside slot @${slotName} never executes: ${node.middleware.filePath}`,\n details:\n ` File: ${node.middleware.filePath}\\n\\n` +\n ` Middleware is collected from the main route chain only.\\n` +\n ` The slot resolver does not run middleware — this file is silently dead.\\n` +\n ` (access.ts in slots does run via SlotAccessGate; middleware.ts does not.)\\n\\n` +\n ` To fix: Move the middleware logic into access.ts for slot-scoped auth,\\n` +\n ` or into a middleware.ts on the main route chain outside the slot.\\n`,\n level: 'error',\n });\n }\n for (const child of node.children) {\n collectSlotMiddleware(child, slotName, warnings);\n }\n for (const [nestedSlotName, nestedSlot] of Object.entries(node.slots)) {\n collectSlotMiddleware(nestedSlot, nestedSlotName, warnings);\n }\n}\n\n// ─── Check: App Directory Exists ────────────────────────────────────────────\n\n/**\n * Check if the app/ directory exists. Called before scanning.\n * Returns a warning if missing, or null if the directory exists.\n */\nexport function checkAppDirExists(appDir: string): ConventionWarning | null {\n if (existsSync(appDir)) return null;\n\n return {\n id: 'NO_APP_DIR',\n summary: 'No app/ directory found',\n details:\n ` Expected: ${appDir}\\n\\n` +\n ' timber.js requires an app/ directory for file-system routing.\\n' +\n ' Every request will return 404 until you create it.\\n\\n' +\n ' To fix: Create the app/ directory with a page:\\n\\n' +\n ' mkdir -p app\\n' +\n ' # Create app/layout.tsx and app/page.tsx\\n',\n level: 'error',\n };\n}\n\n// ─── Formatting ─────────────────────────────────────────────────────────────\n\nimport type { InspectColor } from 'node:util';\nimport { styleText } from 'node:util';\n\ntype Format = InspectColor | readonly InspectColor[];\nconst noValidate = { validateStream: false } as const;\n\nexport interface FormatOptions {\n /**\n * Emit ANSI escapes. Off when the text becomes an `Error` message —\n * whoever prints it decides its formatting, and colored escapes inside\n * an exception leak into logs and stack traces.\n */\n color?: boolean;\n}\n\n/**\n * Format warnings for terminal output.\n *\n * Groups by severity, uses colors, and includes fix suggestions.\n */\nexport function formatConventionWarnings(\n warnings: ConventionWarning[],\n options: FormatOptions = {}\n): string {\n const { color = true } = options;\n const style = (fmt: Format, text: string) => (color ? styleText(fmt, text, noValidate) : text);\n if (warnings.length === 0) return '';\n\n const errors = warnings.filter((w) => w.level === 'error');\n const warns = warnings.filter((w) => w.level === 'warn');\n\n const lines: string[] = [];\n\n if (errors.length > 0) {\n lines.push(\n `${style(['red', 'bold'], '[timber]')} ${style('red', `${errors.length} configuration error${errors.length !== 1 ? 's' : ''}:`)}`\n );\n for (const e of errors) {\n lines.push('');\n lines.push(` ${style('red', '✗')} ${e.summary}`);\n lines.push(style('dim', e.details));\n }\n }\n\n if (warns.length > 0) {\n if (errors.length > 0) lines.push('');\n lines.push(\n `${style(['yellow', 'bold'], '[timber]')} ${style('yellow', `${warns.length} configuration warning${warns.length !== 1 ? 's' : ''}:`)}`\n );\n for (const w of warns) {\n lines.push('');\n lines.push(` ${style('yellow', '⚠')} ${w.summary}`);\n lines.push(style('dim', w.details));\n }\n }\n\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,mBAAmB,MAAiB,QAA0C;CAC5F,MAAM,sBAAM,IAAI,IAAyB;CAEzC,SAAS,KAAK,MAAmB,QAAgB,UAAwB;EACvE,IAAI,IAAI,QAAQ;GACd,OAAO,KAAK,WAAW;GACvB,aAAa,YAAY;EAC3B,CAAC;EAED,KAAK,MAAM,SAAS,KAAK,UAGvB,KAAK,OAFY,KAAK,QAAQ,MAAM,WAExB,GAAU,GADG,SAAS,GAAG,MAAM,aACR;EAErC,KAAK,MAAM,CAAC,UAAU,aAAa,OAAO,QAAQ,KAAK,KAAK,GAG1D,KAAK,UAFW,KAAK,QAAQ,IAAI,UAElB,GAAS,GADA,SAAS,IAAI,UACD;CAExC;CAEA,KAAK,KAAK,MAAM,QAAQ,EAAE;CAC1B,OAAO;AACT;;;;AAKA,SAAgB,mBAAmB,MAA2B;CAC5D,OAAO;EACL,wBAAwB,KAAK,MAAM;EACnC,+BAA+B,KAAK,YAAY;EAChD;CACF,CAAC,CAAC,KAAK,IAAI;AACb;;;;;;AAOA,eAAsB,kBACpB,WACA,QACA,MACe;CAGf,MAAM,WAAW,OAAO,MAAM,KAAK,SAAS,CAAC;CAC7C,MAAM,YAAY,KAAK,MAAM,WAAW,SAAS,QAAQ;CACzD,MAAM,MAAM,mBAAmB,WAAW,MAAM;CAEhD,MAAM,SAA0B,CAAC;CACjC,KAAK,MAAM,CAAC,OAAO,SAAS,KAAK;EAE/B,MAAM,SAAS,MAAM,MAAM,OAAO,MAAM;EACxC,MAAM,aAAa,KAAK,WAAW,MAAM;EACzC,MAAM,cAAc,KAAK,YAAY,eAAe;EACpD,MAAM,UAAU,mBAA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AAW,IAAI,MAAM,GAAG,EAAE,GACtI;EACA,KAAK,MAAM,KAAK,OAAO;GACrB,MAAM,KAAK,EAAE;GACb,MAAM,KAAK,KAAK,MAAM,UAAU,GAAG,EAAE,GAAG,EAAE,SAAS;GACnD,MAAM,KAAK,MAAM,OAAO,EAAE,OAAO,CAAC;EACpC;CACF;CAEA,OAAO,MAAM,KAAK,IAAI;AACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"schema-bridge-C83xa9lT.js","names":[],"sources":["../../src/schema-bridge.ts"],"sourcesContent":["/**\n * Standard Schema bridge — shared helpers for bridging Standard Schema-compatible\n * validation libraries (Zod, Valibot, ArkType) to the Codec<T> protocol.\n *\n * This module is the single source of truth for:\n * - StandardSchemaV1 interface (subset of the Standard Schema spec)\n * - validateSync() helper\n * - fromSchema() — search-param bridge; scalar shape first, array second\n * - fromArraySchema() — same loop, array shape first\n * - fromCookieSchema() — scalar shape only; a cookie has no array shape\n * - fromParamSchema() — route params; throws on failure (invalid param → 404)\n *\n * One parse loop, four candidate orders. Which shapes a bridge offers, and\n * in what order, is the ONLY thing that differs — see §\"Shape tolerance\"\n * below and in design/23-search-params.md. `serialize` is deliberately NOT\n * shared: `null` means \"omit the key\" for a search param and \"delete the\n * cookie\" for a cookie, so unifying it silently changed what\n * `cookie.set([])` did (TIM-1352).\n *\n * These are re-exported from @timber-js/app/search-params, @timber-js/app/segment-params,\n * and @timber-js/app/cookies for convenience. The canonical import is\n * @timber-js/app/codec.\n *\n * Design doc: design/23a-search-params-triage.md §\"Unify Codec<T> type\"\n */\n\nimport type { Codec } from './codec.ts';\n\n// ---------------------------------------------------------------------------\n// Standard Schema interface (subset)\n//\n// Standard Schema (https://github.com/standard-schema/standard-schema) defines\n// a minimal interface that Zod ≥3.24, Valibot ≥1.0, and ArkType all implement.\n// We depend only on `~standard.validate` to avoid coupling to any specific lib.\n// ---------------------------------------------------------------------------\n\n/** Minimal Standard Schema interface for auto-detection. */\nexport interface StandardSchemaV1<Output = unknown> {\n '~standard': {\n validate(value: unknown): StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;\n };\n}\n\nexport type StandardSchemaResult<Output> =\n | { value: Output; issues?: undefined }\n | { value?: undefined; issues: ReadonlyArray<{ message: string }> };\n\n// ---------------------------------------------------------------------------\n// Sync validate helper\n// ---------------------------------------------------------------------------\n\n/**\n * Run a Standard Schema's `~standard.validate()` synchronously.\n *\n * Zod v4's signature includes `Promise` in the return union to satisfy the\n * Standard Schema spec, but in practice Zod always validates synchronously\n * for the schema types we use. We assert the result is sync and throw if\n * it isn't — codec parsing must be synchronous.\n */\nexport function validateSync<Output>(\n schema: StandardSchemaV1<Output>,\n value: unknown\n): StandardSchemaResult<Output> {\n const result = schema['~standard'].validate(value);\n if (result instanceof Promise) {\n throw new Error(\n '[timber] fromSchema: schema returned a Promise — only sync schemas are supported.'\n );\n }\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Type guards\n// ---------------------------------------------------------------------------\n\n/** Check if a value is a Standard Schema object. */\nexport function isStandardSchema(value: unknown): value is StandardSchemaV1 {\n return (\n typeof value === 'object' &&\n value !== null &&\n '~standard' in value &&\n typeof (value as StandardSchemaV1)['~standard']?.validate === 'function'\n );\n}\n\n/** Check if a value is a Codec (has parse + serialize methods). */\nexport function isCodec(value: unknown): value is Codec<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Codec<unknown>).parse === 'function' &&\n typeof (value as Codec<unknown>).serialize === 'function'\n );\n}\n\n// ---------------------------------------------------------------------------\n// fromParamSchema — bridge from Standard Schema to Codec<T> for route params\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema to a Codec for route params.\n * Parse throws on failure (invalid param → 404). Serialize returns string.\n */\nexport function fromParamSchema<T>(fieldName: string, schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse(value: string | string[] | undefined): T {\n const result = validateSync(schema, value);\n if (!result.issues) {\n return result.value;\n }\n const messages = result.issues.map((i) => i.message).join(', ');\n throw new Error(`[timber] Param '${fieldName}' coercion failed: ${messages}`);\n },\n serialize(value: T): string | null {\n if (value === null || value === undefined) return null;\n if (Array.isArray(value)) return value.join('/');\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// resolveCodecOrSchema — generic resolver for any codec-or-schema field\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a field value to a Codec. Accepts Codec<T>, StandardSchemaV1<T>,\n * or (for route params) auto-wraps via fromParamSchema.\n *\n * @param fieldName - used in error messages\n * @param value - the codec or schema to resolve\n * @param mode - 'param' uses fromParamSchema (throws on parse failure),\n * 'search' uses fromSchema (falls back to default on failure,\n * tolerant of the repeated-key array shape),\n * 'cookie' uses fromCookieSchema (same, minus the array shape,\n * which a cookie value cannot have)\n */\nexport function resolveCodecOrSchema(\n fieldName: string,\n value: unknown,\n mode: 'param' | 'search' | 'cookie' = 'search'\n): Codec<unknown> {\n if (isCodec(value)) return value;\n if (isStandardSchema(value)) {\n if (mode === 'param') return fromParamSchema(fieldName, value);\n if (mode === 'cookie') return fromCookieSchema(value) as Codec<unknown>;\n return fromSchema(value) as Codec<unknown>;\n }\n throw new Error(\n `[timber] Field '${fieldName}' is not a valid codec or Standard Schema. ` +\n `Expected an object with { parse, serialize } methods, or a Standard Schema object ` +\n `(Zod, Valibot, ArkType).`\n );\n}\n\n// ---------------------------------------------------------------------------\n// fromSchema — bridge from Standard Schema to Codec<T>\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Shape tolerance — the shared parse loop for both bridges\n//\n// A URL value is `string | string[] | undefined`, but a schema is written\n// against ONE of those: `z.string()` wants `'a'`, `z.array(z.string())`\n// wants `['a']`. Nothing in Standard Schema says which — `~standard.types`\n// exists at the type level only, and probing at runtime is not reliable\n// (design/23-search-params.md §\"Shape tolerance\"). So a bridge tries BOTH\n// shapes rather than committing to one and discarding the value when it\n// guessed wrong.\n//\n// Each bridge only chooses WHICH candidates, and in what order. The first\n// candidate is always the shape that bridge already passed, so nothing that\n// parses today changes meaning; a later one is reached only where the old\n// code fell through to the default. `fromCookieSchema` offers ONE candidate,\n// because a cookie has no array shape at all.\n// ---------------------------------------------------------------------------\n\n/**\n * The scalar shape, and only it. A value that cannot be repeated — a cookie —\n * has no array shape to tolerate, so its bridge stays exactly where it was.\n */\nfunction scalarOnly(value: string | string[] | undefined): unknown[] {\n return [Array.isArray(value) ? value[0] : value];\n}\n\n/** Candidate inputs for the scalar bridge: scalar first, array second. */\nfunction scalarFirst(value: string | string[] | undefined): unknown[] {\n if (value === undefined) return [undefined];\n if (typeof value === 'string') return [value, [value]];\n // Repeated keys: `value[0]` matches URLSearchParams.get().\n //\n // A raw `[]` carries no value at all. `value[0]` is `undefined`, which is\n // the shape the scalar bridge has always passed for it, so `undefined`\n // stays FIRST — an empty array must keep meaning \"absent\" and land on the\n // schema's default. Only `defineSearchParams().parse({ tags: [] })`, the\n // record form, can produce one: URLSearchParams never yields an empty list.\n return value.length > 0 ? [value[0], value] : [undefined, value];\n}\n\n/** Candidate inputs for the array bridge: array first, scalar second. */\nfunction arrayFirst(value: string | string[] | undefined): unknown[] {\n if (value === undefined) return [undefined];\n if (typeof value === 'string') return [[value], value];\n // `[]` first here for the same reason, inverted: the array bridge has\n // always passed the empty array straight through.\n return value.length > 0 ? [value, value[0]] : [value, undefined];\n}\n\n/**\n * Validate `value` against `schema` in each candidate shape, then fall back\n * to the schema's default. Shared by every bridge — they differ only in\n * which candidates they offer, and in what order.\n */\nfunction parseThroughSchema<T>(\n schema: StandardSchemaV1<T>,\n candidates: (value: string | string[] | undefined) => unknown[],\n value: string | string[] | undefined\n): T {\n const inputs = candidates(value);\n for (let i = 0; i < inputs.length; i++) {\n // A throw from the FIRST candidate propagates, unchanged: that is the\n // shape the schema was written against, and a throw from it is the\n // deliberate signal design/23 protects — an app schema may `redirect()`\n // or `notFound()` on a value it refuses, and `validateSync` throws on\n // an async schema.\n //\n // A throw from a LATER candidate is ours, not the app's. We invented\n // that shape; the schema never agreed to receive it. A scalar-only\n // hand-written validator doing `value.toUpperCase()`, or a schema that\n // is async for the array shape only, would turn a field that used to\n // fall back to its default into a render-phase 500. Treat it as \"this\n // shape does not fit\" and keep going.\n let result: StandardSchemaResult<T>;\n try {\n result = validateSync(schema, inputs[i]);\n } catch (error) {\n if (i === 0) throw error;\n continue;\n }\n if (!result.issues) {\n return result.value;\n }\n }\n\n // No shape validated — try parsing undefined to get the default.\n // Re-validate each time so factory defaults (e.g. .default(() => []))\n // produce fresh values.\n const defaultResult = validateSync(schema, undefined);\n if (!defaultResult.issues) {\n return defaultResult.value;\n }\n\n // No default available — the field is implicitly optional. Return\n // undefined; defineSearchParams widens the field's inferred type to\n // T | undefined via InferField so this doesn't lie.\n // design/23-search-params.md §\"Implicit Optionality\"\n return undefined as T;\n}\n\n/**\n * Bridge a Standard Schema-compatible schema (Zod, Valibot, ArkType) to a\n * Codec<T>.\n *\n * Parse: coerces the raw URL value through the schema, trying the scalar\n * shape and then the array shape (see `scalarFirst`), so an array schema\n * works bare: `z.array(z.string()).default([])` yields `[]` when absent,\n * `['a']` for `?tags=a`, and `['a','b']` for `?tags=a&tags=b`. When no\n * shape validates, parses `undefined` to get the schema's default (the\n * schema should have a `.default()` call). If that also fails, returns\n * `undefined`.\n *\n * Serialize: `String()` for primitives, `null` for null/undefined. Note\n * that `String(['a','b'])` is `'a,b'` — the same string `fromArraySchema`\n * writes — so a bare array schema round-trips exactly as design/09\n * §\"Array params\" describes.\n *\n * This is the SEARCH-PARAM bridge. Cookies use `fromCookieSchema`; a\n * cookie has no array shape (see below).\n *\n * ```ts\n * import { z } from 'zod/v4'\n *\n * const pageCodec = fromSchema(z.coerce.number().int().min(1).default(1))\n * const tagsCodec = fromSchema(z.array(z.string()).default([]))\n * ```\n */\nexport function fromSchema<T>(schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, scalarFirst, value),\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// fromCookieSchema — bridge for cookie values\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema for a COOKIE value.\n *\n * Identical to `fromSchema` minus the array shape, because a cookie cannot\n * carry one: `Cookie:` headers and `document.cookie` yield a single string\n * per name, and there is no repeated-key concept to be tolerant of. Sharing\n * the search-param bridge here meant a cookie written by this very codec —\n * `serialize(['a','b'])` → `a,b` — read back as the one-element array\n * `['a,b']` instead of failing to its default: no repeated key in sight,\n * just a delimiter reinterpreted as data.\n *\n * The `serialize` contract also differs by domain and must not be unified:\n * for a search param `null` means \"omit the key\", for a cookie it means\n * **delete the cookie** (design/29-cookies.md).\n */\nexport function fromCookieSchema<T>(schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, scalarOnly, value),\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// fromArraySchema — bridge for array-valued codecs\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema for array values. Handles both single strings\n * and repeated query keys (`?tag=a&tag=b`).\n *\n * ```ts\n * import { fromArraySchema } from '@timber-js/app/codec'\n * import { z } from 'zod/v4'\n *\n * const tagsCodec = fromArraySchema(z.array(z.string()).default([]))\n * ```\n *\n * Since TIM-1352 a bare array schema works through `fromSchema` too, so\n * this is no longer required to make an array field parse. Two cases still\n * want it, both listed in design/23 §\"Shape tolerance\":\n *\n * 1. A **permissive** schema meant as an array — one that accepts a string\n * as readily as an array (`z.any()`, a hand-written coercing validator)\n * — where scalar-first ordering would settle on the scalar shape.\n * 2. An array schema wrapped in `.catch([])`, which swallows the failure\n * that would otherwise trigger the array attempt.\n *\n * It also serializes an empty array to `null` (omitting the key) where\n * `fromSchema` writes `''`.\n */\nexport function fromArraySchema<T>(schema: StandardSchemaV1<T>): {\n parse(value: string | string[] | undefined): T;\n serialize(value: T): string | string[] | null;\n} {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, arrayFirst, value),\n serialize(value: T): string | string[] | null {\n if (value === null || value === undefined) {\n return null;\n }\n // TIM-1353: return string[] so buildSearchParams emits repeated keys\n // (?tag=a&tag=b) instead of comma-joining into one key (?tag=a%2Cb).\n if (Array.isArray(value)) {\n return value.length === 0 ? null : value.map(String);\n }\n return String(value);\n },\n };\n}\n"],"mappings":";;;;;;;;;AA2DA,SAAgB,aACd,QACA,OAC8B;CAC9B,MAAM,SAAS,OAAO,YAAY,CAAC,SAAS,KAAK;CACjD,IAAI,kBAAkB,SACpB,MAAM,IAAI,MACR,mFACF;CAEF,OAAO;AACT;;AAOA,SAAgB,iBAAiB,OAA2C;CAC1E,OACE,OAAO,UAAU,YACjB,UAAU,QACV,eAAe,SACf,OAAQ,MAA2B,YAAY,EAAE,aAAa;AAElE;;AAGA,SAAgB,QAAQ,OAAyC;CAC/D,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAyB,UAAU,cAC3C,OAAQ,MAAyB,cAAc;AAEnD;;;;;AAUA,SAAgB,gBAAmB,WAAmB,QAAuC;CAC3F,OAAO;EACL,MAAM,OAAyC;GAC7C,MAAM,SAAS,aAAa,QAAQ,KAAK;GACzC,IAAI,CAAC,OAAO,QACV,OAAO,OAAO;GAEhB,MAAM,WAAW,OAAO,OAAO,KAAK,MAAM,EAAE,OAAO,CAAC,CAAC,KAAK,IAAI;GAC9D,MAAM,IAAI,MAAM,mBAAmB,UAAU,qBAAqB,UAAU;EAC9E;EACA,UAAU,OAAyB;GACjC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;GAClD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,KAAK,GAAG;GAC/C,OAAO,OAAO,KAAK;EACrB;CACF;AACF;;;;;;;;;;;;;AAkBA,SAAgB,qBACd,WACA,OACA,OAAsC,UACtB;CAChB,IAAI,QA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,SAAgB,WAAc,QAAuC;CACnE,OAAO;EACL,QAAQ,UACN,mBAAmB,QAAQ,aAAa,KAAK;EAC/C,UAAU,OAAyB;GACjC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;GAET,OAAO,OAAO,KAAK;EACrB;CACF;AACF;;;;;;;;;;;;;;;;AAqBA,SAAgB,iBAAoB,QAAuC;CACzE,OAAO;EACL,QAAQ,UACN,mBAAmB,QAAQ,YAAY,KAAK;EAC9C,UAAU,OAAyB;GACjC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;GAET,OAAO,OAAO,KAAK;EACrB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,gBAAmB,QAGjC;CACA,OAAO;EACL,QAAQ,UACN,mBAAmB,QAAQ,YAAY,KAAK;EAC9C,UAAU,OAAoC;GAC5C,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;GAIT,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,WAAW,IAAI,OAAO,MAAM,IAAI,MAAM;GAErD,OAAO,OAAO,KAAK;EACrB;CACF;AACF"}
1
+ {"version":3,"file":"schema-bridge-C83xa9lT.js","names":[],"sources":["../../src/schema-bridge.ts"],"sourcesContent":["/**\n * Standard Schema bridge — shared helpers for bridging Standard Schema-compatible\n * validation libraries (Zod, Valibot, ArkType) to the Codec<T> protocol.\n *\n * This module is the single source of truth for:\n * - StandardSchemaV1 interface (subset of the Standard Schema spec)\n * - validateSync() helper\n * - fromSchema() — search-param bridge; scalar shape first, array second\n * - fromArraySchema() — same loop, array shape first\n * - fromCookieSchema() — scalar shape only; a cookie has no array shape\n * - fromParamSchema() — route params; throws on failure (invalid param → 404)\n *\n * One parse loop, four candidate orders. Which shapes a bridge offers, and\n * in what order, is the ONLY thing that differs — see §\"Shape tolerance\"\n * below and in design/23-search-params.md. `serialize` is deliberately NOT\n * shared: `null` means \"omit the key\" for a search param and \"delete the\n * cookie\" for a cookie, so unifying it silently changed what\n * `cookie.set([])` did (TIM-1352).\n *\n * These are re-exported from @timber-js/app/search-params, @timber-js/app/segment-params,\n * and @timber-js/app/cookies for convenience. The canonical import is\n * @timber-js/app/codec.\n *\n * Design doc: design/23a-search-params-triage.md §\"Unify Codec<T> type\"\n */\n\nimport type { Codec } from './codec.ts';\n\n// ---------------------------------------------------------------------------\n// Standard Schema interface (subset)\n//\n// Standard Schema (https://github.com/standard-schema/standard-schema) defines\n// a minimal interface that Zod ≥3.24, Valibot ≥1.0, and ArkType all implement.\n// We depend only on `~standard.validate` to avoid coupling to any specific lib.\n// ---------------------------------------------------------------------------\n\n/** Minimal Standard Schema interface for auto-detection. */\nexport interface StandardSchemaV1<Output = unknown> {\n readonly '~standard': {\n readonly validate: (\n value: unknown\n ) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;\n };\n}\n\nexport type StandardSchemaResult<Output> =\n | { value: Output; issues?: undefined }\n | { value?: undefined; issues: ReadonlyArray<{ message: string }> };\n\n// ---------------------------------------------------------------------------\n// Sync validate helper\n// ---------------------------------------------------------------------------\n\n/**\n * Run a Standard Schema's `~standard.validate()` synchronously.\n *\n * Zod v4's signature includes `Promise` in the return union to satisfy the\n * Standard Schema spec, but in practice Zod always validates synchronously\n * for the schema types we use. We assert the result is sync and throw if\n * it isn't — codec parsing must be synchronous.\n */\nexport function validateSync<Output>(\n schema: StandardSchemaV1<Output>,\n value: unknown\n): StandardSchemaResult<Output> {\n const result = schema['~standard'].validate(value);\n if (result instanceof Promise) {\n throw new Error(\n '[timber] fromSchema: schema returned a Promise — only sync schemas are supported.'\n );\n }\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Type guards\n// ---------------------------------------------------------------------------\n\n/** Check if a value is a Standard Schema object. */\nexport function isStandardSchema(value: unknown): value is StandardSchemaV1 {\n return (\n typeof value === 'object' &&\n value !== null &&\n '~standard' in value &&\n typeof (value as StandardSchemaV1)['~standard']?.validate === 'function'\n );\n}\n\n/** Check if a value is a Codec (has parse + serialize methods). */\nexport function isCodec(value: unknown): value is Codec<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Codec<unknown>).parse === 'function' &&\n typeof (value as Codec<unknown>).serialize === 'function'\n );\n}\n\n// ---------------------------------------------------------------------------\n// fromParamSchema — bridge from Standard Schema to Codec<T> for route params\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema to a Codec for route params.\n * Parse throws on failure (invalid param → 404). Serialize returns string.\n */\nexport function fromParamSchema<T>(fieldName: string, schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse(value: string | string[] | undefined): T {\n const result = validateSync(schema, value);\n if (!result.issues) {\n return result.value;\n }\n const messages = result.issues.map((i) => i.message).join(', ');\n throw new Error(`[timber] Param '${fieldName}' coercion failed: ${messages}`);\n },\n serialize(value: T): string | null {\n if (value === null || value === undefined) return null;\n if (Array.isArray(value)) return value.join('/');\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// resolveCodecOrSchema — generic resolver for any codec-or-schema field\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a field value to a Codec. Accepts Codec<T>, StandardSchemaV1<T>,\n * or (for route params) auto-wraps via fromParamSchema.\n *\n * @param fieldName - used in error messages\n * @param value - the codec or schema to resolve\n * @param mode - 'param' uses fromParamSchema (throws on parse failure),\n * 'search' uses fromSchema (falls back to default on failure,\n * tolerant of the repeated-key array shape),\n * 'cookie' uses fromCookieSchema (same, minus the array shape,\n * which a cookie value cannot have)\n */\nexport function resolveCodecOrSchema(\n fieldName: string,\n value: unknown,\n mode: 'param' | 'search' | 'cookie' = 'search'\n): Codec<unknown> {\n if (isCodec(value)) return value;\n if (isStandardSchema(value)) {\n if (mode === 'param') return fromParamSchema(fieldName, value);\n if (mode === 'cookie') return fromCookieSchema(value) as Codec<unknown>;\n return fromSchema(value) as Codec<unknown>;\n }\n throw new Error(\n `[timber] Field '${fieldName}' is not a valid codec or Standard Schema. ` +\n `Expected an object with { parse, serialize } methods, or a Standard Schema object ` +\n `(Zod, Valibot, ArkType).`\n );\n}\n\n// ---------------------------------------------------------------------------\n// fromSchema — bridge from Standard Schema to Codec<T>\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Shape tolerance — the shared parse loop for both bridges\n//\n// A URL value is `string | string[] | undefined`, but a schema is written\n// against ONE of those: `z.string()` wants `'a'`, `z.array(z.string())`\n// wants `['a']`. Nothing in Standard Schema says which — `~standard.types`\n// exists at the type level only, and probing at runtime is not reliable\n// (design/23-search-params.md §\"Shape tolerance\"). So a bridge tries BOTH\n// shapes rather than committing to one and discarding the value when it\n// guessed wrong.\n//\n// Each bridge only chooses WHICH candidates, and in what order. The first\n// candidate is always the shape that bridge already passed, so nothing that\n// parses today changes meaning; a later one is reached only where the old\n// code fell through to the default. `fromCookieSchema` offers ONE candidate,\n// because a cookie has no array shape at all.\n// ---------------------------------------------------------------------------\n\n/**\n * The scalar shape, and only it. A value that cannot be repeated — a cookie —\n * has no array shape to tolerate, so its bridge stays exactly where it was.\n */\nfunction scalarOnly(value: string | string[] | undefined): unknown[] {\n return [Array.isArray(value) ? value[0] : value];\n}\n\n/** Candidate inputs for the scalar bridge: scalar first, array second. */\nfunction scalarFirst(value: string | string[] | undefined): unknown[] {\n if (value === undefined) return [undefined];\n if (typeof value === 'string') return [value, [value]];\n // Repeated keys: `value[0]` matches URLSearchParams.get().\n //\n // A raw `[]` carries no value at all. `value[0]` is `undefined`, which is\n // the shape the scalar bridge has always passed for it, so `undefined`\n // stays FIRST — an empty array must keep meaning \"absent\" and land on the\n // schema's default. Only `defineSearchParams().parse({ tags: [] })`, the\n // record form, can produce one: URLSearchParams never yields an empty list.\n return value.length > 0 ? [value[0], value] : [undefined, value];\n}\n\n/** Candidate inputs for the array bridge: array first, scalar second. */\nfunction arrayFirst(value: string | string[] | undefined): unknown[] {\n if (value === undefined) return [undefined];\n if (typeof value === 'string') return [[value], value];\n // `[]` first here for the same reason, inverted: the array bridge has\n // always passed the empty array straight through.\n return value.length > 0 ? [value, value[0]] : [value, undefined];\n}\n\n/**\n * Validate `value` against `schema` in each candidate shape, then fall back\n * to the schema's default. Shared by every bridge — they differ only in\n * which candidates they offer, and in what order.\n */\nfunction parseThroughSchema<T>(\n schema: StandardSchemaV1<T>,\n candidates: (value: string | string[] | undefined) => unknown[],\n value: string | string[] | undefined\n): T {\n const inputs = candidates(value);\n for (let i = 0; i < inputs.length; i++) {\n // A throw from the FIRST candidate propagates, unchanged: that is the\n // shape the schema was written against, and a throw from it is the\n // deliberate signal design/23 protects — an app schema may `redirect()`\n // or `notFound()` on a value it refuses, and `validateSync` throws on\n // an async schema.\n //\n // A throw from a LATER candidate is ours, not the app's. We invented\n // that shape; the schema never agreed to receive it. A scalar-only\n // hand-written validator doing `value.toUpperCase()`, or a schema that\n // is async for the array shape only, would turn a field that used to\n // fall back to its default into a render-phase 500. Treat it as \"this\n // shape does not fit\" and keep going.\n let result: StandardSchemaResult<T>;\n try {\n result = validateSync(schema, inputs[i]);\n } catch (error) {\n if (i === 0) throw error;\n continue;\n }\n if (!result.issues) {\n return result.value;\n }\n }\n\n // No shape validated — try parsing undefined to get the default.\n // Re-validate each time so factory defaults (e.g. .default(() => []))\n // produce fresh values.\n const defaultResult = validateSync(schema, undefined);\n if (!defaultResult.issues) {\n return defaultResult.value;\n }\n\n // No default available — the field is implicitly optional. Return\n // undefined; defineSearchParams widens the field's inferred type to\n // T | undefined via InferField so this doesn't lie.\n // design/23-search-params.md §\"Implicit Optionality\"\n return undefined as T;\n}\n\n/**\n * Bridge a Standard Schema-compatible schema (Zod, Valibot, ArkType) to a\n * Codec<T>.\n *\n * Parse: coerces the raw URL value through the schema, trying the scalar\n * shape and then the array shape (see `scalarFirst`), so an array schema\n * works bare: `z.array(z.string()).default([])` yields `[]` when absent,\n * `['a']` for `?tags=a`, and `['a','b']` for `?tags=a&tags=b`. When no\n * shape validates, parses `undefined` to get the schema's default (the\n * schema should have a `.default()` call). If that also fails, returns\n * `undefined`.\n *\n * Serialize: `String()` for primitives, `null` for null/undefined. Note\n * that `String(['a','b'])` is `'a,b'` — the same string `fromArraySchema`\n * writes — so a bare array schema round-trips exactly as design/09\n * §\"Array params\" describes.\n *\n * This is the SEARCH-PARAM bridge. Cookies use `fromCookieSchema`; a\n * cookie has no array shape (see below).\n *\n * ```ts\n * import { z } from 'zod/v4'\n *\n * const pageCodec = fromSchema(z.coerce.number().int().min(1).default(1))\n * const tagsCodec = fromSchema(z.array(z.string()).default([]))\n * ```\n */\nexport function fromSchema<T>(schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, scalarFirst, value),\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// fromCookieSchema — bridge for cookie values\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema for a COOKIE value.\n *\n * Identical to `fromSchema` minus the array shape, because a cookie cannot\n * carry one: `Cookie:` headers and `document.cookie` yield a single string\n * per name, and there is no repeated-key concept to be tolerant of. Sharing\n * the search-param bridge here meant a cookie written by this very codec —\n * `serialize(['a','b'])` → `a,b` — read back as the one-element array\n * `['a,b']` instead of failing to its default: no repeated key in sight,\n * just a delimiter reinterpreted as data.\n *\n * The `serialize` contract also differs by domain and must not be unified:\n * for a search param `null` means \"omit the key\", for a cookie it means\n * **delete the cookie** (design/29-cookies.md).\n */\nexport function fromCookieSchema<T>(schema: StandardSchemaV1<T>): Codec<T> {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, scalarOnly, value),\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return String(value);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// fromArraySchema — bridge for array-valued codecs\n// ---------------------------------------------------------------------------\n\n/**\n * Bridge a Standard Schema for array values. Handles both single strings\n * and repeated query keys (`?tag=a&tag=b`).\n *\n * ```ts\n * import { fromArraySchema } from '@timber-js/app/codec'\n * import { z } from 'zod/v4'\n *\n * const tagsCodec = fromArraySchema(z.array(z.string()).default([]))\n * ```\n *\n * Since TIM-1352 a bare array schema works through `fromSchema` too, so\n * this is no longer required to make an array field parse. Two cases still\n * want it, both listed in design/23 §\"Shape tolerance\":\n *\n * 1. A **permissive** schema meant as an array — one that accepts a string\n * as readily as an array (`z.any()`, a hand-written coercing validator)\n * — where scalar-first ordering would settle on the scalar shape.\n * 2. An array schema wrapped in `.catch([])`, which swallows the failure\n * that would otherwise trigger the array attempt.\n *\n * It also serializes an empty array to `null` (omitting the key) where\n * `fromSchema` writes `''`.\n */\nexport function fromArraySchema<T>(schema: StandardSchemaV1<T>): {\n parse(value: string | string[] | undefined): T;\n serialize(value: T): string | string[] | null;\n} {\n return {\n parse: (value: string | string[] | undefined): T =>\n parseThroughSchema(schema, arrayFirst, value),\n serialize(value: T): string | string[] | null {\n if (value === null || value === undefined) {\n return null;\n }\n // TIM-1353: return string[] so buildSearchParams emits repeated keys\n // (?tag=a&tag=b) instead of comma-joining into one key (?tag=a%2Cb).\n if (Array.isArray(value)) {\n return value.length === 0 ? null : value.map(String);\n }\n return String(value);\n },\n };\n}\n"],"mappings":";;;;;;;;;AA6DA,SAAgB,aACd,QACA,OAC8B;CAC9B,MAAM,SAAS,OAAO,YAAY,CAAC,SAAS,KAAK;CACjD,IAAI,kBAAkB,SACpB,MAAM,IAAI,MACR,mFACF;CAEF,OAAO;AACT;;AAOA,SAAgB,iBAAiB,OAA2C;CAC1E,OACE,OAAO,UAAU,YACjB,UAAU,QACV,eAAe,SACf,OAAQ,MAA2B,YAAY,EAAE,aAAa;AAElE;;AAGA,SAAgB,QAAQ,OAAyC;CAC/D,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAyB,UAAU,cAC3C,OAAQ,MAAyB,cAAc;AAEnD;;;;;AAUA,SAAgB,gBAAmB,WAAmB,QAAuC;CAC3F,OAAO;EACL,MAAM,O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_deps) {
173
173
  * `--project` names the tsconfig handed to tsgo.
174
174
  */
175
175
  async function runCheck(options, _deps) {
176
- const { checkRoutes, runTypeCheck } = await import("./_chunks/cli-check-BqOylm-3.js");
176
+ const { checkRoutes, runTypeCheck } = await import("./_chunks/cli-check-G8o30ldg.js");
177
177
  const { root } = await checkRoutes({ viteConfigFile: options.config }, _deps);
178
178
  await runTypeCheck({
179
179
  root,
@@ -1 +1 @@
1
- {"version":3,"file":"action-dispatch.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/action-dispatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAwBH,wBAAgB,kBAAkB,IAAI,IAAI,CAwKzC"}
1
+ {"version":3,"file":"action-dispatch.d.ts","sourceRoot":"","sources":["../../../src/client/browser-entry/action-dispatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAwBH,wBAAgB,kBAAkB,IAAI,IAAI,CA8KzC"}
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import { a as formatMissingPeers, i as formatConfigErrors, n as timberDevServer,
2
2
  import { a as isDynamicMetadataExtension } from "./_chunks/metadata-routes-DSDjM_hJ.js";
3
3
  import { n as scanRoutes, r as collectInterceptionRewrites } from "./_chunks/scanner-BQ5sPIJ7.js";
4
4
  import { h as swallow } from "./_chunks/logger-k2DQ4EUf.js";
5
- import { c as writeRouteCodegen, i as getPrerenderExport, l as buildDirToRouteMap, n as formatConventionWarnings, r as lintConventions, s as flushCodegenWrites, t as checkAppDirExists } from "./_chunks/convention-lint-BnO5TyHD.js";
5
+ import { c as writeRouteCodegen, i as getPrerenderExport, l as buildDirToRouteMap, n as formatConventionWarnings, r as lintConventions, s as flushCodegenWrites, t as checkAppDirExists } from "./_chunks/convention-lint-5KzoMg_A.js";
6
6
  import { c as resolveClientJavascript, i as mergeFileConfig, l as createNoopTimer, o as resolveAppDir, r as loadTimberConfigFile, s as resolveBuildDir, t as createPluginContext } from "./_chunks/plugin-context-8idfR3UZ.js";
7
7
  import { r as validateSchemaAgainstRoutes, t as collectLeafRoutes } from "./_chunks/walkers-CN2N_bA-.js";
8
8
  import { i as poisonPillSource, r as markerFor, t as EXPLICIT_MARKERS } from "./_chunks/poison-rules-DoEhbqaY.js";
@@ -662,7 +662,7 @@ var SEGMENT_PREFIX = "\0$segment:";
662
662
  /**
663
663
  * File convention names we track for changes that require manifest regeneration.
664
664
  */
665
- var ROUTE_FILE_PATTERNS = /\/(page|layout|middleware|access|route|error|global-error|default|denied|schema|\d{3}|[45]xx|sitemap|robots|manifest|favicon|icon|opengraph-image|apple-icon)\./;
665
+ var ROUTE_FILE_PATTERNS = /\/(page|layout|middleware|access|route|error|global-error|default|denied|schema|proxy|\d{3}|[45]xx|sitemap|robots|manifest|favicon|icon|opengraph-image|apple-icon)\./;
666
666
  /**
667
667
  * Create the timber-routing Vite plugin.
668
668
  *