@timber-js/app 0.2.0-alpha.209 → 0.2.0-alpha.210
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.
- package/dist/_chunks/{actions-BerlqoXA.js → actions-Rjk4htmA.js} +19 -25
- package/dist/_chunks/{actions-BerlqoXA.js.map → actions-Rjk4htmA.js.map} +1 -1
- package/dist/_chunks/als-registry-DaxkVjt5.js.map +1 -1
- package/dist/_chunks/{cache-api-CR23J_NC.js → cache-api-DGdYfNJn.js} +4 -4
- package/dist/_chunks/{cache-api-CR23J_NC.js.map → cache-api-DGdYfNJn.js.map} +1 -1
- package/dist/_chunks/{chains-CpFg56UB.js → chains-BoO51joc.js} +2 -2
- package/dist/_chunks/{chains-CpFg56UB.js.map → chains-BoO51joc.js.map} +1 -1
- package/dist/_chunks/{cli-check-C6Ev6wBO.js → cli-check-ajNY3B2e.js} +3 -3
- package/dist/_chunks/{cli-check-C6Ev6wBO.js.map → cli-check-ajNY3B2e.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-CbT2AUUI.js → cli-schema-sync-D2eI8jEg.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-CbT2AUUI.js.map → cli-schema-sync-D2eI8jEg.js.map} +1 -1
- package/dist/_chunks/{file-cache-Dw6BJPG7.js → codegen-Bps1sLKJ.js} +3 -29
- package/dist/_chunks/codegen-Bps1sLKJ.js.map +1 -0
- package/dist/_chunks/{convention-lint-jKTwKwPe.js → convention-lint-DLmhGsRS.js} +54 -316
- package/dist/_chunks/convention-lint-DLmhGsRS.js.map +1 -0
- package/dist/_chunks/{dev-server-C4WZdB7L.js → dev-server-v97rQH4b.js} +99 -9
- package/dist/_chunks/dev-server-v97rQH4b.js.map +1 -0
- package/dist/_chunks/{error-boundary-tA7kVfs4.js → error-boundary-DsNScGRM.js} +4 -4
- package/dist/_chunks/{error-boundary-tA7kVfs4.js.map → error-boundary-DsNScGRM.js.map} +1 -1
- package/dist/_chunks/{json-lossy-check-ip0Qi0MT.js → json-lossy-check-CVuRs2hG.js} +2 -2
- package/dist/_chunks/{json-lossy-check-ip0Qi0MT.js.map → json-lossy-check-CVuRs2hG.js.map} +1 -1
- package/dist/_chunks/{live-graph-Dv-JJCZw.js → live-graph-9cSnn_h9.js} +3 -3
- package/dist/_chunks/{live-graph-Dv-JJCZw.js.map → live-graph-9cSnn_h9.js.map} +1 -1
- package/dist/_chunks/{logger-DiDt5ppH.js → logger-BP0LN6vP.js} +17 -2
- package/dist/_chunks/{logger-DiDt5ppH.js.map → logger-BP0LN6vP.js.map} +1 -1
- package/dist/_chunks/metadata-routes-DSDjM_hJ.js.map +1 -1
- package/dist/_chunks/navigation-root-BQfo1-kG.js.map +1 -1
- package/dist/_chunks/{poison-scan-CpeT6_OJ.js → poison-scan-vGV7Re0B.js} +2 -2
- package/dist/_chunks/{poison-scan-CpeT6_OJ.js.map → poison-scan-vGV7Re0B.js.map} +1 -1
- package/dist/_chunks/{scanner-Bw0oq1HB.js → scanner-DmqdxzbW.js} +392 -7
- package/dist/_chunks/scanner-DmqdxzbW.js.map +1 -0
- package/dist/_chunks/segment-classify-C539Pa2O.js.map +1 -1
- package/dist/_chunks/{sizeof-UwzwB1uM.js → sizeof-BM1409x2.js} +2 -2
- package/dist/_chunks/{sizeof-UwzwB1uM.js.map → sizeof-BM1409x2.js.map} +1 -1
- package/dist/_chunks/{status-page-marker-gaihi0KZ.js → status-page-marker-BRX9Ib-d.js} +1 -45
- package/dist/_chunks/status-page-marker-BRX9Ib-d.js.map +1 -0
- package/dist/_chunks/{walkers-BXExhzzk.js → walkers-Czu2jXFq.js} +3 -3
- package/dist/_chunks/{walkers-BXExhzzk.js.map → walkers-Czu2jXFq.js.map} +1 -1
- package/dist/adapters/cloudflare-kv-cache.js +1 -1
- package/dist/analyze/crawl-entry.js +2 -2
- package/dist/analyze/graph-command.js +2 -2
- package/dist/cache/index.js +2 -2
- package/dist/cache/stores/memory.js +1 -1
- package/dist/cli.js +3 -3
- package/dist/client/browser-entry/post-hydration.d.ts.map +1 -1
- package/dist/client/browser-entry/router-init.d.ts.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/history.d.ts +0 -9
- package/dist/client/history.d.ts.map +1 -1
- package/dist/client/index.d.ts +2 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +9 -3
- package/dist/client/index.js.map +1 -1
- package/dist/client/internal.js +25 -38
- package/dist/client/internal.js.map +1 -1
- package/dist/client/link.d.ts +22 -0
- package/dist/client/link.d.ts.map +1 -1
- package/dist/client/navigation-api.d.ts +14 -2
- package/dist/client/navigation-api.d.ts.map +1 -1
- package/dist/client/navigation-root.d.ts +9 -1
- package/dist/client/navigation-root.d.ts.map +1 -1
- package/dist/client/navigation-transition.d.ts +6 -1
- package/dist/client/navigation-transition.d.ts.map +1 -1
- package/dist/client/react-root.d.ts.map +1 -1
- package/dist/client/router-effects.d.ts +10 -3
- package/dist/client/router-effects.d.ts.map +1 -1
- package/dist/client/router-pipeline.d.ts +3 -1
- package/dist/client/router-pipeline.d.ts.map +1 -1
- package/dist/client/router-types.d.ts +65 -9
- package/dist/client/router-types.d.ts.map +1 -1
- package/dist/client/router.d.ts.map +1 -1
- package/dist/client/segment-cache.d.ts +0 -15
- package/dist/client/segment-cache.d.ts.map +1 -1
- package/dist/client/use-router.d.ts +13 -6
- package/dist/client/use-router.d.ts.map +1 -1
- package/dist/config-validation.d.ts +19 -2
- package/dist/config-validation.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/routing/convention-lint.d.ts.map +1 -1
- package/dist/routing/export-detect.d.ts +19 -0
- package/dist/routing/export-detect.d.ts.map +1 -1
- package/dist/routing/index.js +3 -3
- package/dist/routing/manifest-codegen.d.ts.map +1 -1
- package/dist/routing/scanner.d.ts.map +1 -1
- package/dist/routing/types.d.ts +7 -0
- package/dist/routing/types.d.ts.map +1 -1
- package/dist/server/action-handler.d.ts +1 -1
- package/dist/server/action-handler.d.ts.map +1 -1
- package/dist/server/actions.d.ts +9 -4
- package/dist/server/actions.d.ts.map +1 -1
- package/dist/server/csrf.d.ts +38 -19
- package/dist/server/csrf.d.ts.map +1 -1
- package/dist/server/error-boundary-wrapper.d.ts +8 -4
- package/dist/server/error-boundary-wrapper.d.ts.map +1 -1
- package/dist/server/fallback-error.d.ts.map +1 -1
- package/dist/server/form-flash.d.ts +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/server/internal.js +249 -16
- package/dist/server/internal.js.map +1 -1
- package/dist/server/logger.d.ts +16 -3
- package/dist/server/logger.d.ts.map +1 -1
- package/dist/server/metadata-collector.d.ts +2 -0
- package/dist/server/metadata-collector.d.ts.map +1 -1
- package/dist/server/metadata-routes.d.ts +12 -1
- package/dist/server/metadata-routes.d.ts.map +1 -1
- package/dist/server/pipeline-helpers.d.ts +29 -1
- package/dist/server/pipeline-helpers.d.ts.map +1 -1
- package/dist/server/pipeline.d.ts +8 -1
- package/dist/server/pipeline.d.ts.map +1 -1
- package/dist/server/route-element-builder.d.ts.map +1 -1
- package/dist/server/route-matcher.d.ts +8 -0
- package/dist/server/route-matcher.d.ts.map +1 -1
- package/dist/server/rsc-entry/{wrap-action-dispatch.d.ts → action-dispatcher.d.ts} +18 -40
- package/dist/server/rsc-entry/action-dispatcher.d.ts.map +1 -0
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/safe-load.d.ts +5 -12
- package/dist/server/safe-load.d.ts.map +1 -1
- package/docs/api/30-api-server.mdx +1 -1
- package/docs/api/31-api-client.mdx +23 -20
- package/docs/api/34-api-config.mdx +4 -2
- package/package.json +1 -1
- package/src/client/browser-entry/action-dispatch.ts +28 -28
- package/src/client/browser-entry/post-hydration.ts +11 -1
- package/src/client/browser-entry/router-init.ts +10 -4
- package/src/client/history.ts +0 -22
- package/src/client/index.ts +2 -1
- package/src/client/link.tsx +30 -1
- package/src/client/navigation-api.ts +36 -3
- package/src/client/navigation-root.tsx +13 -1
- package/src/client/navigation-transition.ts +17 -7
- package/src/client/react-root.ts +11 -2
- package/src/client/router-effects.ts +11 -4
- package/src/client/router-pipeline.ts +4 -0
- package/src/client/router-types.ts +80 -6
- package/src/client/router.ts +36 -24
- package/src/client/segment-cache.ts +0 -65
- package/src/client/use-router.ts +25 -6
- package/src/config-validation.ts +121 -5
- package/src/index.ts +5 -8
- package/src/routing/convention-lint.ts +75 -0
- package/src/routing/export-detect.ts +88 -0
- package/src/routing/manifest-codegen.ts +6 -0
- package/src/routing/scanner.ts +9 -0
- package/src/routing/types.ts +7 -0
- package/src/server/action-handler.ts +14 -11
- package/src/server/actions.ts +37 -42
- package/src/server/als-registry.ts +1 -1
- package/src/server/csrf.ts +100 -72
- package/src/server/error-boundary-wrapper.ts +11 -12
- package/src/server/fallback-error.ts +13 -21
- package/src/server/form-flash.ts +1 -1
- package/src/server/logger.ts +19 -3
- package/src/server/metadata-collector.ts +4 -1
- package/src/server/metadata-routes.ts +23 -8
- package/src/server/pipeline-helpers.ts +89 -8
- package/src/server/pipeline.ts +27 -2
- package/src/server/route-element-builder.ts +1 -0
- package/src/server/route-matcher.ts +11 -0
- package/src/server/rsc-entry/{wrap-action-dispatch.ts → action-dispatcher.ts} +20 -62
- package/src/server/rsc-entry/index.ts +14 -27
- package/src/server/safe-load.ts +5 -12
- package/dist/_chunks/convention-lint-jKTwKwPe.js.map +0 -1
- package/dist/_chunks/dev-server-C4WZdB7L.js.map +0 -1
- package/dist/_chunks/file-cache-Dw6BJPG7.js.map +0 -1
- package/dist/_chunks/scanner-Bw0oq1HB.js.map +0 -1
- package/dist/_chunks/status-page-marker-gaihi0KZ.js.map +0 -1
- package/dist/server/rsc-entry/wrap-action-dispatch.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chains-CpFg56UB.js","names":[],"sources":["../../src/analyze/classify.ts","../../src/analyze/chains.ts"],"sourcesContent":["/**\n * classify — environment-graph classification for project modules.\n *\n * The one classification module every frontend shares (design/47): the\n * `timber graph` CLI, the dev-server endpoint, the VS Code extension,\n * and the cold crawl must never disagree about a file's environment.\n * Classification intersects RSC/SSR module-graph membership with\n * first-directive detection to produce the decided taxonomy:\n *\n * - `server` — RSC graph only\n * - `client-boundary` — has `'use client'`\n * - `client-internal` — reachable only behind a boundary, no directive\n * - `shared` — instantiated in both environments; INFO, never a\n * warning — shared-by-design is a legitimate pattern\n * - `server-action` — has `'use server'`\n * - `unreferenced` — in no graph and no provisional signal; files with\n * a directive or filename convention get that\n * provisional kind instead, marked `pending`\n *\n * The browser (`client`) Vite graph stays empty until a real browser\n * requests modules, so membership is RSC × SSR — the SSR graph is a\n * faithful proxy for the client tree (design/47 §8, with the frontier\n * caveat below).\n *\n * Design docs: 47-module-environment-tooling.md (taxonomy, §8),\n * 43-analyze-cli.md (directive detection rules).\n */\n\nimport { basename, extname } from 'node:path';\nimport { parseAst, normalizePath } from 'vite';\nimport { hasDirective } from '../rsc-runtime/transforms.ts';\nimport { isRouteConventionFile } from '../routing/scanner.ts';\nimport {\n isDynamicMetadataExtension,\n isStaticMetadataExtension,\n} from '../server/metadata-routes.ts';\n\n/** The statement-list shape hasDirective consumes (estree Program body). */\ntype DirectiveBody = Parameters<typeof hasDirective>[0];\n\nexport type ModuleKind =\n | 'server'\n | 'client-boundary'\n | 'client-internal'\n | 'shared'\n | 'server-action'\n | 'unreferenced';\n\nexport type Directive = 'use client' | 'use server' | null;\n\n/**\n * What a frontend observed about one project module. Graph membership\n * comes from the live dev-server graphs or the cold crawl; the directive\n * comes from the module's original source (never the transformed output,\n * where the RSC plugin has already stripped or proxied it).\n */\nexport interface ModuleObservation {\n /** Absolute path of the source file. */\n file: string;\n /** Present in the RSC environment's module graph. */\n inRsc: boolean;\n /** Present in the SSR environment's module graph. */\n inSsr: boolean;\n /**\n * Present in the browser (`client`) environment's module graph. Only a\n * live dev server with a real connected browser can confirm this — the\n * client graph stays empty otherwise (design/47 §8) — so the cold\n * crawl always observes false. Defaults to false.\n */\n inClient?: boolean;\n /**\n * False when the SSR graph has a node for this file but Vite never\n * transformed it — the §8 signature of a module behind an unexecuted\n * dynamic import (`transformResult == null`). Its own membership is\n * trustworthy; its subtree is not. Defaults to true.\n */\n ssrTransformed?: boolean;\n /** First directive of the original source, or null. */\n directive: Directive;\n}\n\nexport interface ModuleClassification {\n file: string;\n kind: ModuleKind;\n /**\n * Raw per-environment graph membership, in doc 43's classification\n * vocabulary (`{ client, ssr, rsc }`). `kind` is the interpreted\n * answer; this is the evidence. `client` is confirmable only by a\n * live browser graph — static scans always report false.\n */\n envs: { rsc: boolean; ssr: boolean; client: boolean };\n /**\n * True when no graph has confirmed this module — the kind is\n * provisional, derived from directive + filename convention, and\n * frontends must visibly mark it \"pending\" (design/47 §2).\n */\n pending: boolean;\n /**\n * §8 frontier: the module is reachable (it ships to the browser) but\n * was never transformed, so modules behind it may be missing from the\n * graphs entirely. Consumers should transform-on-demand or surface\n * \"reachable, subtree unknown\".\n */\n subtreeUnknown: boolean;\n}\n\n/** File extensions eligible for directive detection. */\nconst PARSEABLE_EXTENSIONS = /\\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;\n\n/**\n * Parse language for a source file, from its extension. Never force\n * `tsx` onto plain `.ts`: JSX-ambiguous TypeScript such as\n * `const identity = <T>(value: T) => value` is valid TS but rejected\n * by a TSX parse, and the resulting parse failure would silently drop\n * the file's directive and poison signals. Plain JS parses as `jsx`\n * (JSX-in-.js is common in Vite projects and JS has no generic-arrow\n * ambiguity for the x-syntax to break).\n */\nexport function langForFile(file: string): 'ts' | 'tsx' | 'jsx' {\n if (/\\.tsx$/.test(file)) return 'tsx';\n if (/\\.[mc]?ts$/.test(file)) return 'ts';\n return 'jsx';\n}\n\n/**\n * Detect the first directive of a module's original source.\n *\n * Never string-match or regex directives (design/43): `hasDirective`\n * from @vitejs/plugin-rsc checks for the `directive` property on\n * ExpressionStatements — the same check the RSC plugin runs to decide\n * boundaries, so classification agrees with what the framework actually\n * does with the file. The directive must be in prologue position (before\n * any import or statement) per the ECMAScript spec. Non-JS sources\n * (CSS, MDX, assets) and sources that fail to parse return null — no\n * directive is a safe default; classification then falls back to graph\n * membership.\n */\nexport function detectDirective(code: string, file: string): Directive {\n if (!PARSEABLE_EXTENSIONS.test(file)) return null;\n let body: DirectiveBody;\n try {\n // Vite's parseAst returns oxc-typed nodes; hasDirective expects the\n // estree shapes. They are structurally identical for the top-level\n // statement scan — the same bridge the rest of the codebase uses\n // (plugin-context.ts parse memo, routing/export-detect.ts).\n body = parseAst(code, { lang: langForFile(file) }).body as unknown as DirectiveBody;\n } catch {\n return null;\n }\n if (hasDirective(body, 'use client')) return 'use client';\n if (hasDirective(body, 'use server')) return 'use server';\n return null;\n}\n\n/** Optional context for classification. */\nexport interface ClassifyContext {\n /**\n * Absolute path of the app directory. When provided, convention-based\n * provisional classification only applies to files inside it — a\n * `lib/page.tsx` is not a route file, and the scanner would never\n * recognize it there.\n */\n appDir?: string;\n /**\n * Configured pageExtensions, when the caller has resolved the app\n * config. Omitted → scanner defaults.\n */\n pageExtensions?: readonly string[];\n}\n\n/**\n * Whether a file is a route-convention source the framework itself\n * imports (page/layout/route/… plus metadata routes). Conventions are\n * derived from the routing scanner and the metadata route table — never\n * a local duplicate list (drift lesson). Each family carries the\n * scanner's own extension rules.\n *\n * Shared by the provisional classifier below and by chains.ts, whose\n * RSC-side walks terminate at the first route-convention file\n * (design/47 §7) — the two must never disagree about what counts.\n *\n * `pageExtensions` mirrors the scanner's parameter: callers that have\n * resolved the app config pass the configured set (a `page.mdx` app);\n * callers without config access fall back to the defaults and tolerate\n * the mismatch.\n */\nexport function isConventionSourceFile(file: string, pageExtensions?: readonly string[]): boolean {\n const ext = extname(file).slice(1);\n const base = basename(file, `.${ext}`);\n return (\n isRouteConventionFile(base, ext, pageExtensions) ||\n isStaticMetadataExtension(base, ext) ||\n isDynamicMetadataExtension(base, ext)\n );\n}\n\n/**\n * Provisional kind for a file no graph has confirmed (design/47 §2):\n * directive first, then filename convention, else `unreferenced`.\n */\nfunction provisionalKind(file: string, directive: Directive, ctx?: ClassifyContext): ModuleKind {\n if (directive === 'use client') return 'client-boundary';\n if (directive === 'use server') return 'server-action';\n // Normalize both sides before the containment check: on Windows,\n // `file` may arrive slash-normalized (Vite module-node paths are)\n // while appDir comes from node:path with backslashes — comparing raw\n // would misreport every provisional route file as unreferenced.\n if (ctx?.appDir && !normalizePath(file).startsWith(normalizePath(ctx.appDir) + '/')) {\n return 'unreferenced';\n }\n if (isConventionSourceFile(file, ctx?.pageExtensions)) return 'server';\n return 'unreferenced';\n}\n\n/**\n * Classify one module from its observation. Pure — all frontends call\n * this with membership data from their own graph source.\n */\nexport function classifyModule(\n obs: ModuleObservation,\n ctx?: ClassifyContext\n): ModuleClassification {\n const referenced = obs.inRsc || obs.inSsr || obs.inClient === true;\n const subtreeUnknown = obs.inSsr && obs.ssrTransformed === false;\n const envs = { rsc: obs.inRsc, ssr: obs.inSsr, client: obs.inClient === true };\n\n if (!referenced) {\n return {\n file: obs.file,\n kind: provisionalKind(obs.file, obs.directive, ctx),\n envs,\n pending: true,\n subtreeUnknown: false,\n };\n }\n\n // Directive wins over membership: a 'use client' file also has an RSC\n // graph node (the client-reference proxy), and a 'use server' module\n // appears in the SSR graph when referenced from client forms — the\n // directive is what those memberships mean.\n let kind: ModuleKind;\n if (obs.directive === 'use client') kind = 'client-boundary';\n else if (obs.directive === 'use server') kind = 'server-action';\n else if (obs.inRsc && obs.inSsr) kind = 'shared';\n else if (obs.inRsc) kind = 'server';\n else kind = 'client-internal';\n\n return { file: obs.file, kind, envs, pending: false, subtreeUnknown };\n}\n\n/** Classify a batch of observations, sorted by file for stable output. */\nexport function classifyModules(\n observations: Iterable<ModuleObservation>,\n ctx?: ClassifyContext\n): ModuleClassification[] {\n return [...observations]\n .map((obs) => classifyModule(obs, ctx))\n .sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));\n}\n","/**\n * chains — boundary-aware import-chain stitching (the \"why\" answer).\n *\n * The human-meaningful import chain for a client-reachable module is a\n * JOIN of two graphs: RSC-graph importers ABOVE the `'use client'`\n * boundary and SSR-graph importers BELOW it. Walking `importers` naively\n * in one graph produces virtual-entry noise (`virtual:vite-rsc/css`)\n * instead of semantic importers — the design/47 §7 findings this module\n * bakes in:\n *\n * - RSC-side walks terminate at `virtual:timber-route-manifest` or the\n * first route-convention file (page/layout/…), never the literal RSC\n * entry — route files' importer is the manifest, whose importers are\n * framework internals; the manifest is the semantic root.\n * - `\\0virtual:vite-rsc/*` importers are filtered so they can never\n * surface in a chain.\n * - When multiple boundaries import the target, one chain is reported\n * PER BOUNDARY — a single BFS shortest path would pick arbitrarily.\n *\n * The chain/hop shapes and text formatting are shared with doc 43's\n * `timber why` so both commands emit the same contract: hops carry\n * `{ id, directive, boundary }`, and one shortest chain is emitted per\n * (boundary, reaching route entry) pair — doc 43's \"one shortest path\n * per reaching entry\", crossed with §7's per-boundary rule.\n *\n * Design docs: 47-module-environment-tooling.md §7, 43-analyze-cli.md\n * §Output Formats.\n */\n\nimport { relative, isAbsolute } from 'node:path';\nimport { normalizePath } from 'vite';\nimport { isConventionSourceFile, type Directive } from './classify.ts';\n\n/**\n * Duck-typed view of a Vite environment module node — a supertype of\n * `EnvironmentModuleNode` for the members the walk reads, so live\n * dev-server graphs and crawl graphs both satisfy it structurally.\n */\nexport interface ChainModuleNode {\n id: string | null;\n url: string;\n file: string | null;\n importers: Set<ChainModuleNode>;\n}\n\n/** Duck-typed view of a Vite environment module graph. */\nexport interface ChainGraph {\n getModulesByFile(file: string): Set<ChainModuleNode> | undefined;\n}\n\n/** Per-hop directive in doc 43's JSON vocabulary. */\nexport type HopDirective = 'client' | 'server' | null;\n\nexport interface ChainHop {\n /** Absolute file path, or a virtual module id printed verbatim. */\n id: string;\n directive: HopDirective;\n /** True only on the hop that crosses the server→client boundary. */\n boundary: boolean;\n}\n\nexport interface ImportChain {\n /**\n * Semantic root: a route-convention file, or the route-manifest\n * virtual id when the walk reached it without passing one. Null when\n * the RSC-side walk dead-ended (no root found) — the chain then\n * starts at its deepest known importer and consumers must present it\n * as partial.\n */\n entry: string | null;\n /**\n * The `'use client'` file this chain crosses; null for a pure\n * server-side chain.\n */\n boundary: string | null;\n /** Hops in forward import order, entry → … → target. */\n hops: ChainHop[];\n}\n\nexport interface ChainContext {\n rsc: ChainGraph;\n ssr: ChainGraph;\n /** Absolute app directory — scopes route-convention root detection. */\n appDir: string;\n /**\n * Configured pageExtensions, when the caller has resolved the app\n * config — a `page.mdx` app's route files are only roots with it.\n * Omitted → scanner defaults.\n */\n pageExtensions?: readonly string[];\n /**\n * First directive of a file's ORIGINAL source (design/43: never the\n * transformed output, where directives are stripped/proxied).\n */\n getDirective(file: string): Directive;\n}\n\n/**\n * The route manifest appears under several ids depending on environment\n * and build phase: `virtual:timber-route-manifest`,\n * `\\0virtual:timber-route-manifest`, and a root-prefixed form\n * (plugins/routing.ts) — match by substring.\n */\nfunction isRouteManifest(key: string): boolean {\n return key.includes('virtual:timber-route-manifest');\n}\n\n/** plugin-rsc internal virtuals (observed: virtual:vite-rsc/css). */\nfunction isViteRscInternal(key: string): boolean {\n return key.includes('virtual:vite-rsc/');\n}\n\n/**\n * File-level vertex key for a node: the file path when Vite resolved\n * one, else the virtual id. Multiple nodes can exist per file (query\n * variants); collapsing to the file keeps chains at source granularity.\n */\nfunction vertexKey(node: ChainModuleNode): string | null {\n return node.file ?? node.id ?? node.url ?? null;\n}\n\n/**\n * Separator for path signatures. Sorts below every printable character\n * so comparing joined signatures equals comparing key sequences.\n */\nconst SIG_SEP = '\\u0000';\n\n/**\n * Backwards level-order BFS over `importers` from `start`, collapsing\n * nodes to file-level vertices and filtering plugin-rsc internals.\n *\n * Shortest-path ties are broken GLOBALLY: each vertex's predecessor is\n * the candidate whose full path signature (the id sequence from the\n * target outward) is lexicographically smallest — per-frontier\n * candidate selection, not merely per-parent importer sorting, so\n * reconverging equal-length branches still yield the advertised\n * representative path (doc 43 §Tie-Breaking).\n *\n * `stopAt` marks terminal vertices. By default their importers are not\n * expanded (RSC walks must not proceed past a route root into\n * framework internals); with `continuePastTerminals` the traversal\n * records the terminal and keeps walking — the SSR walk needs this so\n * an outer boundary that imports an inner boundary is still\n * discovered (one chain per boundary).\n */\nfunction walkImporters(\n graph: ChainGraph,\n start: string,\n stopAt: (key: string) => boolean,\n continuePastTerminals = false\n): { predecessors: Map<string, string | null>; terminals: string[] } {\n const startNodes = graph.getModulesByFile(start);\n const predecessors = new Map<string, string | null>();\n const terminals: string[] = [];\n if (!startNodes || startNodes.size === 0) return { predecessors, terminals };\n\n predecessors.set(start, null);\n const signatures = new Map<string, string>([[start, start]]);\n const nodesOf = new Map<string, ChainModuleNode[]>([[start, [...startNodes]]]);\n let frontier = [start];\n\n while (frontier.length > 0) {\n interface Candidate {\n sig: string;\n parent: string;\n observed: ChainModuleNode[];\n }\n const candidates = new Map<string, Candidate>();\n for (const key of frontier) {\n if (stopAt(key)) {\n terminals.push(key);\n if (!continuePastTerminals) continue;\n }\n for (const node of nodesOf.get(key) ?? []) {\n for (const importer of node.importers) {\n const importerKey = vertexKey(importer);\n if (!importerKey || isViteRscInternal(importerKey)) continue;\n if (predecessors.has(importerKey)) continue;\n // Every frontier vertex has a signature (set when its level\n // was fixed); the fallback only satisfies the type.\n const sig = (signatures.get(key) ?? key) + SIG_SEP + importerKey;\n const existing = candidates.get(importerKey);\n if (!existing) {\n candidates.set(importerKey, { sig, parent: key, observed: [importer] });\n } else {\n // Keep every observed node object (virtual ids have no file\n // index to re-fetch from), but the smallest signature wins\n // the predecessor slot.\n existing.observed.push(importer);\n if (sig < existing.sig) {\n existing.sig = sig;\n existing.parent = key;\n }\n }\n }\n }\n }\n // Fix the next level, ordered by signature so terminal discovery\n // order — and therefore chain order — is deterministic.\n const next = [...candidates.entries()].sort(([, a], [, b]) =>\n a.sig < b.sig ? -1 : a.sig > b.sig ? 1 : 0\n );\n frontier = [];\n for (const [importerKey, candidate] of next) {\n predecessors.set(importerKey, candidate.parent);\n signatures.set(importerKey, candidate.sig);\n // Re-fetch the file's FULL node set from the graph: the importer\n // edges seen so far may cover only one of several nodes per file\n // (query variants — ?direct, ?v=…), and expanding a partial set\n // would silently drop the sibling nodes' importers and dead-end\n // the chain. Virtual ids have no file index; use observed nodes.\n const fullNodes = graph.getModulesByFile(importerKey);\n nodesOf.set(\n importerKey,\n fullNodes && fullNodes.size > 0 ? [...fullNodes] : candidate.observed\n );\n frontier.push(importerKey);\n }\n }\n return { predecessors, terminals };\n}\n\n/** Follow predecessors from `from` back to the walk's start vertex. */\nfunction pathToStart(predecessors: Map<string, string | null>, from: string): string[] {\n const path: string[] = [];\n for (let key: string | null = from; key !== null; key = predecessors.get(key) ?? null) {\n path.push(key);\n }\n return path;\n}\n\nfunction isRouteRoot(key: string, ctx: ChainContext): boolean {\n // Manifest matching applies to virtual ids only — a real file whose\n // path happens to contain the substring must not become a root.\n if (!isAbsolute(key) && isRouteManifest(key)) return true;\n if (!isAbsolute(key)) return false;\n if (key !== ctx.appDir && !key.startsWith(ctx.appDir + '/')) return false;\n return isConventionSourceFile(key, ctx.pageExtensions);\n}\n\n/**\n * RSC-side walk: importers of `file` in the RSC graph up to the\n * semantic roots. Returns one chain PER reaching route entry (doc 43:\n * \"one shortest path per reaching entry\"), each with hops in forward\n * order (root → … → file), in discovery order (shallowest first,\n * signature tie-break). When no root was reached, a single partial\n * result (entry: null) carrying the deepest known path.\n */\nfunction rscSideChains(\n file: string,\n ctx: ChainContext\n): Array<{ entry: string | null; files: string[] }> {\n const { predecessors, terminals } = walkImporters(ctx.rsc, file, (key) => isRouteRoot(key, ctx));\n if (terminals.length > 0) {\n return terminals.map((root) => ({ entry: root, files: pathToStart(predecessors, root) }));\n }\n if (predecessors.size <= 1) {\n // Nothing above the file at all (or file absent from the graph).\n return [{ entry: null, files: [file] }];\n }\n // Dead end — no root found. Report from the deepest vertex on the\n // last-discovered shortest path so the partial chain is still useful.\n const keys = [...predecessors.keys()];\n const deepest = keys[keys.length - 1];\n return [{ entry: null, files: pathToStart(predecessors, deepest) }];\n}\n\n/** Map a source directive onto the doc-43 hop vocabulary. */\nfunction hopDirective(key: string, ctx: ChainContext): HopDirective {\n if (!isAbsolute(key)) return null;\n const directive = ctx.getDirective(key);\n if (directive === 'use client') return 'client';\n if (directive === 'use server') return 'server';\n return null;\n}\n\nfunction toChain(\n entry: string | null,\n boundary: string | null,\n files: string[],\n ctx: ChainContext\n): ImportChain {\n return {\n entry,\n boundary,\n hops: files.map((key) => ({\n id: key,\n directive: hopDirective(key, ctx),\n boundary: boundary !== null && key === boundary,\n })),\n };\n}\n\n/**\n * Stitch the import chain(s) for a target file.\n *\n * - Target in the SSR graph (client-side): walk SSR importers up to\n * each `'use client'` boundary that the RSC graph knows (nested\n * boundaries only reachable from other client components are walked\n * THROUGH — they exist in no RSC graph, so the chain must continue\n * to a boundary a server component actually references), then walk\n * RSC importers from that boundary to the semantic root. One chain\n * per boundary.\n * - Target in the RSC graph without `'use client'`: a pure server\n * chain (boundary: null). Shared modules get both kinds.\n * - Target IS an RSC-known boundary: an RSC-side chain from the target\n * itself, PLUS any outer-boundary chains the SSR walk finds — a\n * boundary imported by another boundary is pulled in by both. A\n * nested `'use client'` target the RSC graph does NOT know is\n * handled like any client-internal file — the SSR walk continues to\n * the boundary a server component references.\n */\nexport function stitchImportChains(rawTargetFile: string, rawCtx: ChainContext): ImportChain[] {\n // Vite module-node `file` values are slash-normalized even on\n // Windows, while node:path targets/appDir arrive backslashed there —\n // normalize both once so graph lookups and containment checks agree\n // (normalizePath only rewrites separators on Windows, so posix paths\n // pass through untouched).\n const targetFile = normalizePath(rawTargetFile);\n const ctx: ChainContext = { ...rawCtx, appDir: normalizePath(rawCtx.appDir) };\n\n const chains: ImportChain[] = [];\n const targetDirective = ctx.getDirective(targetFile);\n const targetInRsc = (ctx.rsc.getModulesByFile(targetFile)?.size ?? 0) > 0;\n\n if (targetDirective === 'use client' && targetInRsc) {\n for (const above of rscSideChains(targetFile, ctx)) {\n chains.push(toChain(above.entry, targetFile, above.files, ctx));\n }\n }\n\n // Client-side chains: one per RSC-known boundary above the target.\n const isRscKnownBoundary = (key: string): boolean =>\n isAbsolute(key) &&\n ctx.getDirective(key) === 'use client' &&\n (ctx.rsc.getModulesByFile(key)?.size ?? 0) > 0;\n\n // continuePastTerminals: an outer boundary that imports an inner\n // boundary must still be discovered — one chain per boundary.\n const ssrWalk = walkImporters(ctx.ssr, targetFile, isRscKnownBoundary, true);\n for (const boundary of [...ssrWalk.terminals].sort()) {\n // A boundary target records itself as a terminal; its own chain is\n // the RSC-side one already pushed above.\n if (boundary === targetFile) continue;\n const below = pathToStart(ssrWalk.predecessors, boundary);\n for (const above of rscSideChains(boundary, ctx)) {\n // Stitch, dropping the duplicated boundary vertex from the RSC side.\n chains.push(toChain(above.entry, boundary, [...above.files.slice(0, -1), ...below], ctx));\n }\n }\n\n // Pure server chains when the RSC graph reaches the target directly.\n if (targetInRsc && targetDirective !== 'use client') {\n for (const above of rscSideChains(targetFile, ctx)) {\n chains.push(toChain(above.entry, null, above.files, ctx));\n }\n }\n\n // SSR-side dead end with nothing else to show: mirror the RSC side's\n // honesty and emit a partial chain from the deepest importer instead\n // of returning [] as if the file were in no graph. A singleton walk\n // (target in the SSR graph with no importers at all) still emits its\n // one-hop partial — graph membership is information.\n if (chains.length === 0 && ssrWalk.predecessors.size > 0) {\n const keys = [...ssrWalk.predecessors.keys()];\n const deepest = keys[keys.length - 1];\n chains.push(toChain(null, null, pathToStart(ssrWalk.predecessors, deepest), ctx));\n }\n\n return chains;\n}\n\n/**\n * Render chains in doc 43's text shape — shared by `timber graph` and\n * `timber why` so both commands print identically:\n *\n * ```\n * app/page.tsx\n * → app/nav.tsx ← 'use client' [boundary]\n * → src/lib/icons/chevron.ts\n * ```\n *\n * Paths under `projectRoot` print relative; virtual ids print verbatim\n * (doc 43 §Relative-vs-Absolute Paths). A partial chain (entry: null)\n * is prefixed with an honest marker instead of silently posing as\n * complete.\n */\nexport function formatChains(chains: ImportChain[], projectRoot: string): string {\n const root = normalizePath(projectRoot);\n const lines: string[] = [];\n for (const chain of chains) {\n if (lines.length > 0) lines.push('');\n if (chain.entry === null) {\n lines.push(' (partial chain — no route root found)');\n }\n chain.hops.forEach((hop, index) => {\n const display =\n isAbsolute(hop.id) && hop.id.startsWith(root + '/') ? relative(root, hop.id) : hop.id;\n const indent = ' '.repeat(index + 1);\n const arrow = index === 0 ? '' : '→ ';\n let annotation = '';\n if (hop.directive === 'client') {\n annotation = ` ← 'use client'${hop.boundary ? ' [boundary]' : ''}`;\n } else if (hop.directive === 'server') {\n annotation = ` ← 'use server'`;\n }\n lines.push(`${indent}${arrow}${display}${annotation}`);\n });\n }\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,IAAM,uBAAuB;;;;;;;;;;AAW7B,SAAgB,YAAY,MAAoC;CAC9D,IAAI,SAAS,KAAK,IAAI,GAAG,OAAO;CAChC,IAAI,aAAa,KAAK,IAAI,GAAG,OAAO;CACpC,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,gBAAgB,MAAc,MAAyB;CACrE,IAAI,CAAC,qBAAqB,KAAK,IAAI,GAAG,OAAO;CAC7C,IAAI;CACJ,IAAI;EAKF,OAAO,SAAS,MAAM,EAAE,MAAM,YAAY,IAAI,EAAE,CAAC,CAAC,CAAC;CACrD,QAAQ;EACN,OAAO;CACT;CACA,IAAI,aAAa,MAAM,YAAY,GAAG,OAAO;CAC7C,IAAI,aAAa,MAAM,YAAY,GAAG,OAAO;CAC7C,OAAO;AACT;;;;;;;;;;;;;;;;;AAkCA,SAAgB,uBAAuB,MAAc,gBAA6C;CAChG,MAAM,MAAM,QAAQ,IAAI,CAAC,CAAC,MAAM,CAAC;CACjC,MAAM,OAAO,SAAS,MAAM,IAAI,KAAK;CACrC,OACE,sBAAsB,MAAM,KAAK,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AC;GACpC,MAAM,QAAQ,UAAU,IAAI,KAAK;GACjC,IAAI,aAAa;GACjB,IAAI,IAAI,cAAc,UACpB,aAAa,mBAAmB,IAAI,WAAW,gBAAgB;QAC1D,IAAI,IAAI,cAAc,UAC3B,aAAa;GAEf,MAAM,KAAK,GAAG,SAAS,QAAQ,UAAU,YAAY;EACvD,CAAC;CACH;CACA,OAAO,MAAM,KAAK,IAAI;AACxB"}
|
|
1
|
+
{"version":3,"file":"chains-BoO51joc.js","names":[],"sources":["../../src/analyze/classify.ts","../../src/analyze/chains.ts"],"sourcesContent":["/**\n * classify — environment-graph classification for project modules.\n *\n * The one classification module every frontend shares (design/47): the\n * `timber graph` CLI, the dev-server endpoint, the VS Code extension,\n * and the cold crawl must never disagree about a file's environment.\n * Classification intersects RSC/SSR module-graph membership with\n * first-directive detection to produce the decided taxonomy:\n *\n * - `server` — RSC graph only\n * - `client-boundary` — has `'use client'`\n * - `client-internal` — reachable only behind a boundary, no directive\n * - `shared` — instantiated in both environments; INFO, never a\n * warning — shared-by-design is a legitimate pattern\n * - `server-action` — has `'use server'`\n * - `unreferenced` — in no graph and no provisional signal; files with\n * a directive or filename convention get that\n * provisional kind instead, marked `pending`\n *\n * The browser (`client`) Vite graph stays empty until a real browser\n * requests modules, so membership is RSC × SSR — the SSR graph is a\n * faithful proxy for the client tree (design/47 §8, with the frontier\n * caveat below).\n *\n * Design docs: 47-module-environment-tooling.md (taxonomy, §8),\n * 43-analyze-cli.md (directive detection rules).\n */\n\nimport { basename, extname } from 'node:path';\nimport { parseAst, normalizePath } from 'vite';\nimport { hasDirective } from '../rsc-runtime/transforms.ts';\nimport { isRouteConventionFile } from '../routing/scanner.ts';\nimport {\n isDynamicMetadataExtension,\n isStaticMetadataExtension,\n} from '../server/metadata-routes.ts';\n\n/** The statement-list shape hasDirective consumes (estree Program body). */\ntype DirectiveBody = Parameters<typeof hasDirective>[0];\n\nexport type ModuleKind =\n | 'server'\n | 'client-boundary'\n | 'client-internal'\n | 'shared'\n | 'server-action'\n | 'unreferenced';\n\nexport type Directive = 'use client' | 'use server' | null;\n\n/**\n * What a frontend observed about one project module. Graph membership\n * comes from the live dev-server graphs or the cold crawl; the directive\n * comes from the module's original source (never the transformed output,\n * where the RSC plugin has already stripped or proxied it).\n */\nexport interface ModuleObservation {\n /** Absolute path of the source file. */\n file: string;\n /** Present in the RSC environment's module graph. */\n inRsc: boolean;\n /** Present in the SSR environment's module graph. */\n inSsr: boolean;\n /**\n * Present in the browser (`client`) environment's module graph. Only a\n * live dev server with a real connected browser can confirm this — the\n * client graph stays empty otherwise (design/47 §8) — so the cold\n * crawl always observes false. Defaults to false.\n */\n inClient?: boolean;\n /**\n * False when the SSR graph has a node for this file but Vite never\n * transformed it — the §8 signature of a module behind an unexecuted\n * dynamic import (`transformResult == null`). Its own membership is\n * trustworthy; its subtree is not. Defaults to true.\n */\n ssrTransformed?: boolean;\n /** First directive of the original source, or null. */\n directive: Directive;\n}\n\nexport interface ModuleClassification {\n file: string;\n kind: ModuleKind;\n /**\n * Raw per-environment graph membership, in doc 43's classification\n * vocabulary (`{ client, ssr, rsc }`). `kind` is the interpreted\n * answer; this is the evidence. `client` is confirmable only by a\n * live browser graph — static scans always report false.\n */\n envs: { rsc: boolean; ssr: boolean; client: boolean };\n /**\n * True when no graph has confirmed this module — the kind is\n * provisional, derived from directive + filename convention, and\n * frontends must visibly mark it \"pending\" (design/47 §2).\n */\n pending: boolean;\n /**\n * §8 frontier: the module is reachable (it ships to the browser) but\n * was never transformed, so modules behind it may be missing from the\n * graphs entirely. Consumers should transform-on-demand or surface\n * \"reachable, subtree unknown\".\n */\n subtreeUnknown: boolean;\n}\n\n/** File extensions eligible for directive detection. */\nconst PARSEABLE_EXTENSIONS = /\\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;\n\n/**\n * Parse language for a source file, from its extension. Never force\n * `tsx` onto plain `.ts`: JSX-ambiguous TypeScript such as\n * `const identity = <T>(value: T) => value` is valid TS but rejected\n * by a TSX parse, and the resulting parse failure would silently drop\n * the file's directive and poison signals. Plain JS parses as `jsx`\n * (JSX-in-.js is common in Vite projects and JS has no generic-arrow\n * ambiguity for the x-syntax to break).\n */\nexport function langForFile(file: string): 'ts' | 'tsx' | 'jsx' {\n if (/\\.tsx$/.test(file)) return 'tsx';\n if (/\\.[mc]?ts$/.test(file)) return 'ts';\n return 'jsx';\n}\n\n/**\n * Detect the first directive of a module's original source.\n *\n * Never string-match or regex directives (design/43): `hasDirective`\n * from @vitejs/plugin-rsc checks for the `directive` property on\n * ExpressionStatements — the same check the RSC plugin runs to decide\n * boundaries, so classification agrees with what the framework actually\n * does with the file. The directive must be in prologue position (before\n * any import or statement) per the ECMAScript spec. Non-JS sources\n * (CSS, MDX, assets) and sources that fail to parse return null — no\n * directive is a safe default; classification then falls back to graph\n * membership.\n */\nexport function detectDirective(code: string, file: string): Directive {\n if (!PARSEABLE_EXTENSIONS.test(file)) return null;\n let body: DirectiveBody;\n try {\n // Vite's parseAst returns oxc-typed nodes; hasDirective expects the\n // estree shapes. They are structurally identical for the top-level\n // statement scan — the same bridge the rest of the codebase uses\n // (plugin-context.ts parse memo, routing/export-detect.ts).\n body = parseAst(code, { lang: langForFile(file) }).body as unknown as DirectiveBody;\n } catch {\n return null;\n }\n if (hasDirective(body, 'use client')) return 'use client';\n if (hasDirective(body, 'use server')) return 'use server';\n return null;\n}\n\n/** Optional context for classification. */\nexport interface ClassifyContext {\n /**\n * Absolute path of the app directory. When provided, convention-based\n * provisional classification only applies to files inside it — a\n * `lib/page.tsx` is not a route file, and the scanner would never\n * recognize it there.\n */\n appDir?: string;\n /**\n * Configured pageExtensions, when the caller has resolved the app\n * config. Omitted → scanner defaults.\n */\n pageExtensions?: readonly string[];\n}\n\n/**\n * Whether a file is a route-convention source the framework itself\n * imports (page/layout/route/… plus metadata routes). Conventions are\n * derived from the routing scanner and the metadata route table — never\n * a local duplicate list (drift lesson). Each family carries the\n * scanner's own extension rules.\n *\n * Shared by the provisional classifier below and by chains.ts, whose\n * RSC-side walks terminate at the first route-convention file\n * (design/47 §7) — the two must never disagree about what counts.\n *\n * `pageExtensions` mirrors the scanner's parameter: callers that have\n * resolved the app config pass the configured set (a `page.mdx` app);\n * callers without config access fall back to the defaults and tolerate\n * the mismatch.\n */\nexport function isConventionSourceFile(file: string, pageExtensions?: readonly string[]): boolean {\n const ext = extname(file).slice(1);\n const base = basename(file, `.${ext}`);\n return (\n isRouteConventionFile(base, ext, pageExtensions) ||\n isStaticMetadataExtension(base, ext) ||\n isDynamicMetadataExtension(base, ext)\n );\n}\n\n/**\n * Provisional kind for a file no graph has confirmed (design/47 §2):\n * directive first, then filename convention, else `unreferenced`.\n */\nfunction provisionalKind(file: string, directive: Directive, ctx?: ClassifyContext): ModuleKind {\n if (directive === 'use client') return 'client-boundary';\n if (directive === 'use server') return 'server-action';\n // Normalize both sides before the containment check: on Windows,\n // `file` may arrive slash-normalized (Vite module-node paths are)\n // while appDir comes from node:path with backslashes — comparing raw\n // would misreport every provisional route file as unreferenced.\n if (ctx?.appDir && !normalizePath(file).startsWith(normalizePath(ctx.appDir) + '/')) {\n return 'unreferenced';\n }\n if (isConventionSourceFile(file, ctx?.pageExtensions)) return 'server';\n return 'unreferenced';\n}\n\n/**\n * Classify one module from its observation. Pure — all frontends call\n * this with membership data from their own graph source.\n */\nexport function classifyModule(\n obs: ModuleObservation,\n ctx?: ClassifyContext\n): ModuleClassification {\n const referenced = obs.inRsc || obs.inSsr || obs.inClient === true;\n const subtreeUnknown = obs.inSsr && obs.ssrTransformed === false;\n const envs = { rsc: obs.inRsc, ssr: obs.inSsr, client: obs.inClient === true };\n\n if (!referenced) {\n return {\n file: obs.file,\n kind: provisionalKind(obs.file, obs.directive, ctx),\n envs,\n pending: true,\n subtreeUnknown: false,\n };\n }\n\n // Directive wins over membership: a 'use client' file also has an RSC\n // graph node (the client-reference proxy), and a 'use server' module\n // appears in the SSR graph when referenced from client forms — the\n // directive is what those memberships mean.\n let kind: ModuleKind;\n if (obs.directive === 'use client') kind = 'client-boundary';\n else if (obs.directive === 'use server') kind = 'server-action';\n else if (obs.inRsc && obs.inSsr) kind = 'shared';\n else if (obs.inRsc) kind = 'server';\n else kind = 'client-internal';\n\n return { file: obs.file, kind, envs, pending: false, subtreeUnknown };\n}\n\n/** Classify a batch of observations, sorted by file for stable output. */\nexport function classifyModules(\n observations: Iterable<ModuleObservation>,\n ctx?: ClassifyContext\n): ModuleClassification[] {\n return [...observations]\n .map((obs) => classifyModule(obs, ctx))\n .sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));\n}\n","/**\n * chains — boundary-aware import-chain stitching (the \"why\" answer).\n *\n * The human-meaningful import chain for a client-reachable module is a\n * JOIN of two graphs: RSC-graph importers ABOVE the `'use client'`\n * boundary and SSR-graph importers BELOW it. Walking `importers` naively\n * in one graph produces virtual-entry noise (`virtual:vite-rsc/css`)\n * instead of semantic importers — the design/47 §7 findings this module\n * bakes in:\n *\n * - RSC-side walks terminate at `virtual:timber-route-manifest` or the\n * first route-convention file (page/layout/…), never the literal RSC\n * entry — route files' importer is the manifest, whose importers are\n * framework internals; the manifest is the semantic root.\n * - `\\0virtual:vite-rsc/*` importers are filtered so they can never\n * surface in a chain.\n * - When multiple boundaries import the target, one chain is reported\n * PER BOUNDARY — a single BFS shortest path would pick arbitrarily.\n *\n * The chain/hop shapes and text formatting are shared with doc 43's\n * `timber why` so both commands emit the same contract: hops carry\n * `{ id, directive, boundary }`, and one shortest chain is emitted per\n * (boundary, reaching route entry) pair — doc 43's \"one shortest path\n * per reaching entry\", crossed with §7's per-boundary rule.\n *\n * Design docs: 47-module-environment-tooling.md §7, 43-analyze-cli.md\n * §Output Formats.\n */\n\nimport { relative, isAbsolute } from 'node:path';\nimport { normalizePath } from 'vite';\nimport { isConventionSourceFile, type Directive } from './classify.ts';\n\n/**\n * Duck-typed view of a Vite environment module node — a supertype of\n * `EnvironmentModuleNode` for the members the walk reads, so live\n * dev-server graphs and crawl graphs both satisfy it structurally.\n */\nexport interface ChainModuleNode {\n id: string | null;\n url: string;\n file: string | null;\n importers: Set<ChainModuleNode>;\n}\n\n/** Duck-typed view of a Vite environment module graph. */\nexport interface ChainGraph {\n getModulesByFile(file: string): Set<ChainModuleNode> | undefined;\n}\n\n/** Per-hop directive in doc 43's JSON vocabulary. */\nexport type HopDirective = 'client' | 'server' | null;\n\nexport interface ChainHop {\n /** Absolute file path, or a virtual module id printed verbatim. */\n id: string;\n directive: HopDirective;\n /** True only on the hop that crosses the server→client boundary. */\n boundary: boolean;\n}\n\nexport interface ImportChain {\n /**\n * Semantic root: a route-convention file, or the route-manifest\n * virtual id when the walk reached it without passing one. Null when\n * the RSC-side walk dead-ended (no root found) — the chain then\n * starts at its deepest known importer and consumers must present it\n * as partial.\n */\n entry: string | null;\n /**\n * The `'use client'` file this chain crosses; null for a pure\n * server-side chain.\n */\n boundary: string | null;\n /** Hops in forward import order, entry → … → target. */\n hops: ChainHop[];\n}\n\nexport interface ChainContext {\n rsc: ChainGraph;\n ssr: ChainGraph;\n /** Absolute app directory — scopes route-convention root detection. */\n appDir: string;\n /**\n * Configured pageExtensions, when the caller has resolved the app\n * config — a `page.mdx` app's route files are only roots with it.\n * Omitted → scanner defaults.\n */\n pageExtensions?: readonly string[];\n /**\n * First directive of a file's ORIGINAL source (design/43: never the\n * transformed output, where directives are stripped/proxied).\n */\n getDirective(file: string): Directive;\n}\n\n/**\n * The route manifest appears under several ids depending on environment\n * and build phase: `virtual:timber-route-manifest`,\n * `\\0virtual:timber-route-manifest`, and a root-prefixed form\n * (plugins/routing.ts) — match by substring.\n */\nfunction isRouteManifest(key: string): boolean {\n return key.includes('virtual:timber-route-manifest');\n}\n\n/** plugin-rsc internal virtuals (observed: virtual:vite-rsc/css). */\nfunction isViteRscInternal(key: string): boolean {\n return key.includes('virtual:vite-rsc/');\n}\n\n/**\n * File-level vertex key for a node: the file path when Vite resolved\n * one, else the virtual id. Multiple nodes can exist per file (query\n * variants); collapsing to the file keeps chains at source granularity.\n */\nfunction vertexKey(node: ChainModuleNode): string | null {\n return node.file ?? node.id ?? node.url ?? null;\n}\n\n/**\n * Separator for path signatures. Sorts below every printable character\n * so comparing joined signatures equals comparing key sequences.\n */\nconst SIG_SEP = '\\u0000';\n\n/**\n * Backwards level-order BFS over `importers` from `start`, collapsing\n * nodes to file-level vertices and filtering plugin-rsc internals.\n *\n * Shortest-path ties are broken GLOBALLY: each vertex's predecessor is\n * the candidate whose full path signature (the id sequence from the\n * target outward) is lexicographically smallest — per-frontier\n * candidate selection, not merely per-parent importer sorting, so\n * reconverging equal-length branches still yield the advertised\n * representative path (doc 43 §Tie-Breaking).\n *\n * `stopAt` marks terminal vertices. By default their importers are not\n * expanded (RSC walks must not proceed past a route root into\n * framework internals); with `continuePastTerminals` the traversal\n * records the terminal and keeps walking — the SSR walk needs this so\n * an outer boundary that imports an inner boundary is still\n * discovered (one chain per boundary).\n */\nfunction walkImporters(\n graph: ChainGraph,\n start: string,\n stopAt: (key: string) => boolean,\n continuePastTerminals = false\n): { predecessors: Map<string, string | null>; terminals: string[] } {\n const startNodes = graph.getModulesByFile(start);\n const predecessors = new Map<string, string | null>();\n const terminals: string[] = [];\n if (!startNodes || startNodes.size === 0) return { predecessors, terminals };\n\n predecessors.set(start, null);\n const signatures = new Map<string, string>([[start, start]]);\n const nodesOf = new Map<string, ChainModuleNode[]>([[start, [...startNodes]]]);\n let frontier = [start];\n\n while (frontier.length > 0) {\n interface Candidate {\n sig: string;\n parent: string;\n observed: ChainModuleNode[];\n }\n const candidates = new Map<string, Candidate>();\n for (const key of frontier) {\n if (stopAt(key)) {\n terminals.push(key);\n if (!continuePastTerminals) continue;\n }\n for (const node of nodesOf.get(key) ?? []) {\n for (const importer of node.importers) {\n const importerKey = vertexKey(importer);\n if (!importerKey || isViteRscInternal(importerKey)) continue;\n if (predecessors.has(importerKey)) continue;\n // Every frontier vertex has a signature (set when its level\n // was fixed); the fallback only satisfies the type.\n const sig = (signatures.get(key) ?? key) + SIG_SEP + importerKey;\n const existing = candidates.get(importerKey);\n if (!existing) {\n candidates.set(importerKey, { sig, parent: key, observed: [importer] });\n } else {\n // Keep every observed node object (virtual ids have no file\n // index to re-fetch from), but the smallest signature wins\n // the predecessor slot.\n existing.observed.push(importer);\n if (sig < existing.sig) {\n existing.sig = sig;\n existing.parent = key;\n }\n }\n }\n }\n }\n // Fix the next level, ordered by signature so terminal discovery\n // order — and therefore chain order — is deterministic.\n const next = [...candidates.entries()].sort(([, a], [, b]) =>\n a.sig < b.sig ? -1 : a.sig > b.sig ? 1 : 0\n );\n frontier = [];\n for (const [importerKey, candidate] of next) {\n predecessors.set(importerKey, candidate.parent);\n signatures.set(importerKey, candidate.sig);\n // Re-fetch the file's FULL node set from the graph: the importer\n // edges seen so far may cover only one of several nodes per file\n // (query variants — ?direct, ?v=…), and expanding a partial set\n // would silently drop the sibling nodes' importers and dead-end\n // the chain. Virtual ids have no file index; use observed nodes.\n const fullNodes = graph.getModulesByFile(importerKey);\n nodesOf.set(\n importerKey,\n fullNodes && fullNodes.size > 0 ? [...fullNodes] : candidate.observed\n );\n frontier.push(importerKey);\n }\n }\n return { predecessors, terminals };\n}\n\n/** Follow predecessors from `from` back to the walk's start vertex. */\nfunction pathToStart(predecessors: Map<string, string | null>, from: string): string[] {\n const path: string[] = [];\n for (let key: string | null = from; key !== null; key = predecessors.get(key) ?? null) {\n path.push(key);\n }\n return path;\n}\n\nfunction isRouteRoot(key: string, ctx: ChainContext): boolean {\n // Manifest matching applies to virtual ids only — a real file whose\n // path happens to contain the substring must not become a root.\n if (!isAbsolute(key) && isRouteManifest(key)) return true;\n if (!isAbsolute(key)) return false;\n if (key !== ctx.appDir && !key.startsWith(ctx.appDir + '/')) return false;\n return isConventionSourceFile(key, ctx.pageExtensions);\n}\n\n/**\n * RSC-side walk: importers of `file` in the RSC graph up to the\n * semantic roots. Returns one chain PER reaching route entry (doc 43:\n * \"one shortest path per reaching entry\"), each with hops in forward\n * order (root → … → file), in discovery order (shallowest first,\n * signature tie-break). When no root was reached, a single partial\n * result (entry: null) carrying the deepest known path.\n */\nfunction rscSideChains(\n file: string,\n ctx: ChainContext\n): Array<{ entry: string | null; files: string[] }> {\n const { predecessors, terminals } = walkImporters(ctx.rsc, file, (key) => isRouteRoot(key, ctx));\n if (terminals.length > 0) {\n return terminals.map((root) => ({ entry: root, files: pathToStart(predecessors, root) }));\n }\n if (predecessors.size <= 1) {\n // Nothing above the file at all (or file absent from the graph).\n return [{ entry: null, files: [file] }];\n }\n // Dead end — no root found. Report from the deepest vertex on the\n // last-discovered shortest path so the partial chain is still useful.\n const keys = [...predecessors.keys()];\n const deepest = keys[keys.length - 1];\n return [{ entry: null, files: pathToStart(predecessors, deepest) }];\n}\n\n/** Map a source directive onto the doc-43 hop vocabulary. */\nfunction hopDirective(key: string, ctx: ChainContext): HopDirective {\n if (!isAbsolute(key)) return null;\n const directive = ctx.getDirective(key);\n if (directive === 'use client') return 'client';\n if (directive === 'use server') return 'server';\n return null;\n}\n\nfunction toChain(\n entry: string | null,\n boundary: string | null,\n files: string[],\n ctx: ChainContext\n): ImportChain {\n return {\n entry,\n boundary,\n hops: files.map((key) => ({\n id: key,\n directive: hopDirective(key, ctx),\n boundary: boundary !== null && key === boundary,\n })),\n };\n}\n\n/**\n * Stitch the import chain(s) for a target file.\n *\n * - Target in the SSR graph (client-side): walk SSR importers up to\n * each `'use client'` boundary that the RSC graph knows (nested\n * boundaries only reachable from other client components are walked\n * THROUGH — they exist in no RSC graph, so the chain must continue\n * to a boundary a server component actually references), then walk\n * RSC importers from that boundary to the semantic root. One chain\n * per boundary.\n * - Target in the RSC graph without `'use client'`: a pure server\n * chain (boundary: null). Shared modules get both kinds.\n * - Target IS an RSC-known boundary: an RSC-side chain from the target\n * itself, PLUS any outer-boundary chains the SSR walk finds — a\n * boundary imported by another boundary is pulled in by both. A\n * nested `'use client'` target the RSC graph does NOT know is\n * handled like any client-internal file — the SSR walk continues to\n * the boundary a server component references.\n */\nexport function stitchImportChains(rawTargetFile: string, rawCtx: ChainContext): ImportChain[] {\n // Vite module-node `file` values are slash-normalized even on\n // Windows, while node:path targets/appDir arrive backslashed there —\n // normalize both once so graph lookups and containment checks agree\n // (normalizePath only rewrites separators on Windows, so posix paths\n // pass through untouched).\n const targetFile = normalizePath(rawTargetFile);\n const ctx: ChainContext = { ...rawCtx, appDir: normalizePath(rawCtx.appDir) };\n\n const chains: ImportChain[] = [];\n const targetDirective = ctx.getDirective(targetFile);\n const targetInRsc = (ctx.rsc.getModulesByFile(targetFile)?.size ?? 0) > 0;\n\n if (targetDirective === 'use client' && targetInRsc) {\n for (const above of rscSideChains(targetFile, ctx)) {\n chains.push(toChain(above.entry, targetFile, above.files, ctx));\n }\n }\n\n // Client-side chains: one per RSC-known boundary above the target.\n const isRscKnownBoundary = (key: string): boolean =>\n isAbsolute(key) &&\n ctx.getDirective(key) === 'use client' &&\n (ctx.rsc.getModulesByFile(key)?.size ?? 0) > 0;\n\n // continuePastTerminals: an outer boundary that imports an inner\n // boundary must still be discovered — one chain per boundary.\n const ssrWalk = walkImporters(ctx.ssr, targetFile, isRscKnownBoundary, true);\n for (const boundary of [...ssrWalk.terminals].sort()) {\n // A boundary target records itself as a terminal; its own chain is\n // the RSC-side one already pushed above.\n if (boundary === targetFile) continue;\n const below = pathToStart(ssrWalk.predecessors, boundary);\n for (const above of rscSideChains(boundary, ctx)) {\n // Stitch, dropping the duplicated boundary vertex from the RSC side.\n chains.push(toChain(above.entry, boundary, [...above.files.slice(0, -1), ...below], ctx));\n }\n }\n\n // Pure server chains when the RSC graph reaches the target directly.\n if (targetInRsc && targetDirective !== 'use client') {\n for (const above of rscSideChains(targetFile, ctx)) {\n chains.push(toChain(above.entry, null, above.files, ctx));\n }\n }\n\n // SSR-side dead end with nothing else to show: mirror the RSC side's\n // honesty and emit a partial chain from the deepest importer instead\n // of returning [] as if the file were in no graph. A singleton walk\n // (target in the SSR graph with no importers at all) still emits its\n // one-hop partial — graph membership is information.\n if (chains.length === 0 && ssrWalk.predecessors.size > 0) {\n const keys = [...ssrWalk.predecessors.keys()];\n const deepest = keys[keys.length - 1];\n chains.push(toChain(null, null, pathToStart(ssrWalk.predecessors, deepest), ctx));\n }\n\n return chains;\n}\n\n/**\n * Render chains in doc 43's text shape — shared by `timber graph` and\n * `timber why` so both commands print identically:\n *\n * ```\n * app/page.tsx\n * → app/nav.tsx ← 'use client' [boundary]\n * → src/lib/icons/chevron.ts\n * ```\n *\n * Paths under `projectRoot` print relative; virtual ids print verbatim\n * (doc 43 §Relative-vs-Absolute Paths). A partial chain (entry: null)\n * is prefixed with an honest marker instead of silently posing as\n * complete.\n */\nexport function formatChains(chains: ImportChain[], projectRoot: string): string {\n const root = normalizePath(projectRoot);\n const lines: string[] = [];\n for (const chain of chains) {\n if (lines.length > 0) lines.push('');\n if (chain.entry === null) {\n lines.push(' (partial chain — no route root found)');\n }\n chain.hops.forEach((hop, index) => {\n const display =\n isAbsolute(hop.id) && hop.id.startsWith(root + '/') ? relative(root, hop.id) : hop.id;\n const indent = ' '.repeat(index + 1);\n const arrow = index === 0 ? '' : '→ ';\n let annotation = '';\n if (hop.directive === 'client') {\n annotation = ` ← 'use client'${hop.boundary ? ' [boundary]' : ''}`;\n } else if (hop.directive === 'server') {\n annotation = ` ← 'use server'`;\n }\n lines.push(`${indent}${arrow}${display}${annotation}`);\n });\n }\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,IAAM,uBAAuB;;;;;;;;;;AAW7B,SAAgB,YAAY,MAAoC;CAC9D,IAAI,SAAS,KAAK,IAAI,GAAG,OAAO;CAChC,IAAI,aAAa,KAAK,IAAI,GAAG,OAAO;CACpC,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,gBAAgB,MAAc,MAAyB;CACrE,IAAI,CAAC,qBAAqB,KAAK,IAAI,GAAG,OAAO;CAC7C,IAAI;CACJ,IAAI;EAKF,OAAO,SAAS,MAAM,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AAO,cAAc,WAAW;CACtC,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,MAAM,SAAS,GAAG,MAAM,KAAK,EAAE;EACnC,IAAI,MAAM,UAAU,MAClB,MAAM,KAAK,yCAAyC;EAEtD,MAAM,KAAK,SAAS,KAAK,UAAU;GACjC,MAAM,UACJ,WAAW,IAAI,EAAE,KAAK,IAAI,GAAG,WAAW,OAAO,GAAG,IAAI,SAAS,MAAM,IAAI,EAAE,IAAI,IAAI;GACrF,MAAM,SAAS,KAAK,OAAO,QAAQ,CAAC;GACpC,MAAM,QAAQ,UAAU,IAAI,KAAK;GACjC,IAAI,aAAa;GACjB,IAAI,IAAI,cAAc,UACpB,aAAa,mBAAmB,IAAI,WAAW,gBAAgB;QAC1D,IAAI,IAAI,cAAc,UAC3B,aAAa;GAEf,MAAM,KAAK,GAAG,SAAS,QAAQ,UAAU,YAAY;EACvD,CAAC;CACH;CACA,OAAO,MAAM,KAAK,IAAI;AACxB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as scanRoutes } from "./scanner-
|
|
2
|
-
import { a as
|
|
1
|
+
import { n as scanRoutes } from "./scanner-DmqdxzbW.js";
|
|
2
|
+
import { a as ENV_DTS_FILENAME, i as CODEGEN_OUTPUT, n as formatConventionWarnings, r as lintConventions, s as writeRouteCodegen } from "./convention-lint-DLmhGsRS.js";
|
|
3
3
|
import { resolveTimberContext } from "./cli-context-By7k2xVo.js";
|
|
4
4
|
import { dirname, join, resolve } from "node:path";
|
|
5
5
|
import { createRequire } from "node:module";
|
|
@@ -249,4 +249,4 @@ async function runTypeCheck(options = {}, deps = {}) {
|
|
|
249
249
|
//#endregion
|
|
250
250
|
export { checkRoutes, runTypeCheck };
|
|
251
251
|
|
|
252
|
-
//# sourceMappingURL=cli-check-
|
|
252
|
+
//# sourceMappingURL=cli-check-ajNY3B2e.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-check-C6Ev6wBO.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 { resolveTimberContext, type ResolveViteConfig } from './cli-context.ts';\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/** @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/**\n * Resolve root, appDir and pageExtensions the way `timber build` resolves them\n * — through Vite, never by re-reading `timber.config.ts` (see `cli-context.ts`).\n * Inline `timber({ pageExtensions: [...] })` is the case that bites: a scan\n * that re-read the file would silently use default page extensions and write a\n * route map missing the app's pages. `examples/next-playground-migration` is\n * exactly this shape.\n */\nexport async function resolveRouteInputs(\n options: RouteOptions = {},\n deps: CheckDeps = {}\n): Promise<RouteInputs> {\n const ctx = await resolveTimberContext('check', options.viteConfigFile, deps.resolveViteConfig);\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,eAAe;;;;;;;AAQrB,IAAM,uBAAuB,CAAC,kBAAkB,cAAc;;;;;;;;;AAiD9D,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;;;;;;;;;AA4BA,eAAsB,mBACpB,UAAwB,CAAC,GACzB,OAAkB,CAAC,GACG;CACtB,MAAM,MAAM,MAAM,qBAAqB,SAAS,QAAQ,gBAAgB,KAAK,iBAAiB;CAC9F,OAAO;EAAE,MAAM,IAAI;EAAM,QAAQ,IAAI;EAAQ,gBAAgB,IAAI,OAAO;CAAe;AACzF;;;;;;;;;;;;AAaA,eAAsB,YACpB,UAAwB,CAAC,GACzB,OAAkB,CAAC,GACG;CACtB,MAAM,SAAS,MAAM,mBAAmB,SAAS,IAAI;C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,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-ajNY3B2e.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 { resolveTimberContext, type ResolveViteConfig } from './cli-context.ts';\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/** @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/**\n * Resolve root, appDir and pageExtensions the way `timber build` resolves them\n * — through Vite, never by re-reading `timber.config.ts` (see `cli-context.ts`).\n * Inline `timber({ pageExtensions: [...] })` is the case that bites: a scan\n * that re-read the file would silently use default page extensions and write a\n * route map missing the app's pages. `examples/next-playground-migration` is\n * exactly this shape.\n */\nexport async function resolveRouteInputs(\n options: RouteOptions = {},\n deps: CheckDeps = {}\n): Promise<RouteInputs> {\n const ctx = await resolveTimberContext('check', options.viteConfigFile, deps.resolveViteConfig);\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,eAAe;;;;;;;AAQrB,IAAM,uBAAuB,CAAC,kBAAkB,cAAc;;;;;;;;;AAiD9D,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,wBAA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AAU,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,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
-
import { n as scanRoutes } from "./scanner-
|
|
2
|
+
import { n as scanRoutes } from "./scanner-DmqdxzbW.js";
|
|
3
3
|
import { c as resolveAppDir } from "./plugin-context-BPBPc3lL.js";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
@@ -296,4 +296,4 @@ function runSchemaSync(projectRoot) {
|
|
|
296
296
|
//#endregion
|
|
297
297
|
export { findSchemaFile as n, parseExistingSchemaKeys as r, cli_schema_sync_exports as t };
|
|
298
298
|
|
|
299
|
-
//# sourceMappingURL=cli-schema-sync-
|
|
299
|
+
//# sourceMappingURL=cli-schema-sync-D2eI8jEg.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-schema-sync-CbT2AUUI.js","names":[],"sources":["../../src/cli-schema-sync.ts"],"sourcesContent":["/**\n * `timber schema sync` — scan filesystem for dynamic segments, append\n * missing entries with `codec.string` defaults, and remove stale entries\n * whose segments no longer exist in the filesystem.\n *\n * Design doc: design/41-global-params.md §Auto-Scaffolding\n */\n\nimport { readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { scanRoutes } from './routing/scanner.ts';\nimport type { SegmentNode } from './routing/types.ts';\nimport { resolveAppDir } from './plugin-context.ts';\n\nfunction toBracketKey(node: SegmentNode): string {\n if (node.paramPrefix || node.paramSuffix) return `[${node.paramName}]`;\n switch (node.segmentType) {\n case 'catch-all':\n return `[...${node.paramName}]`;\n case 'optional-catch-all':\n return `[[...${node.paramName}]]`;\n default:\n return `[${node.paramName}]`;\n }\n}\n\n/**\n * Collect all unique bracket-keyed dynamic segment names from the route tree.\n * Returns entries like '[artistSlug]', '[...slug]', '[[...topic]]'.\n */\nexport function collectDynamicSegments(appDir: string): string[] {\n const tree = scanRoutes(appDir);\n const segments = new Set<string>();\n walkSegments(tree.root, segments);\n return [...segments].sort();\n}\n\nfunction walkSegments(node: SegmentNode, segments: Set<string>): void {\n if (node.paramName) {\n // Use bare bracket form for schema keys — affixed segments like\n // `img-[id].png` register as `[id]`, matching runtime codec lookup.\n segments.add(toBracketKey(node));\n }\n for (const child of node.children) {\n walkSegments(child, segments);\n }\n for (const slot of Object.values(node.slots)) {\n walkSegments(slot, segments);\n }\n}\n\n/**\n * Replace comment bodies (and optionally string contents) with spaces,\n * preserving length and newlines so every index maps 1:1 to the original.\n * Lets the structural scanning below ignore `segmentParams` mentions and\n * braces inside comments/strings without a TS parser (fine pre-alpha,\n * see TIM-1066).\n *\n * With `maskStrings`, string contents are blanked too — except literal\n * 'segmentParams' strings, kept so a quoted property key stays findable.\n */\nfunction maskSource(content: string, maskStrings: boolean): string {\n const out = content.split('');\n const n = content.length;\n let i = 0;\n\n const blank = (from: number, to: number): void => {\n for (let j = from; j < to; j++) {\n if (content[j] !== '\\n') out[j] = ' ';\n }\n };\n\n while (i < n) {\n const ch = content[i];\n const next = content[i + 1];\n if (ch === '/' && next === '/') {\n const start = i;\n while (i < n && content[i] !== '\\n') i++;\n blank(start, i);\n } else if (ch === '/' && next === '*') {\n const start = i;\n i += 2;\n while (i < n && !(content[i] === '*' && content[i + 1] === '/')) i++;\n i = Math.min(i + 2, n);\n blank(start, i);\n } else if (ch === '\"' || ch === \"'\" || ch === '`') {\n const start = i;\n i++;\n while (i < n && content[i] !== ch) {\n if (content[i] === '\\\\') i++;\n i++;\n }\n const end = i; // at closing quote (or n if unterminated)\n if (maskStrings && content.slice(start + 1, end) !== 'segmentParams') {\n blank(start + 1, end);\n }\n i++;\n } else {\n i++;\n }\n }\n return out.join('');\n}\n\n/**\n * Locate the `segmentParams: { ... }` block in a schema file.\n * Returns the indices of the opening and matching closing brace, or null\n * if no segmentParams property is found. Comments and strings are masked\n * first, so a JSDoc example mentioning `segmentParams: { ... }` above the\n * real defineSchema call is not mistaken for the block, and braces inside\n * comments/strings don't skew the depth count. The search is anchored to\n * the `defineSchema(` call when present, so helper objects with their own\n * segmentParams property earlier in the file are skipped.\n */\nexport function findSegmentParamsBlock(\n content: string\n): { openBrace: number; closeBrace: number } | null {\n const masked = maskSource(content, true);\n\n const defineCall = /\\bdefineSchema\\s*\\(/.exec(masked);\n const keyRe = /(['\"]?)segmentParams\\1\\s*:\\s*\\{/g;\n keyRe.lastIndex = defineCall ? defineCall.index + defineCall[0].length : 0;\n const keyMatch = keyRe.exec(masked);\n if (!keyMatch) return null;\n\n const openBrace = keyMatch.index + keyMatch[0].length - 1;\n let depth = 1;\n let i = openBrace + 1;\n while (i < masked.length && depth > 0) {\n if (masked[i] === '{') depth++;\n else if (masked[i] === '}') depth--;\n i++;\n }\n if (depth > 0) return null;\n // i now points to just after the closing brace\n return { openBrace, closeBrace: i - 1 };\n}\n\n/**\n * Parse existing bracket keys from an app/schema.ts file.\n * Scoped to the segmentParams: { ... } block — bracket keys elsewhere in\n * the file (unrelated objects, comments above defineSchema) are ignored.\n * Comments inside the block are masked, so a commented-out entry does not\n * count as registered.\n *\n * The key charset matches the route classifier (segment-classify.ts):\n * any character except `]`, so hyphenated params like '[my-param]' parse.\n */\nexport function parseExistingSchemaKeys(content: string): string[] {\n const block = findSegmentParamsBlock(content);\n if (!block) return [];\n\n const blockContent = maskSource(content, false).slice(block.openBrace, block.closeBrace);\n const keys: string[] = [];\n // Match quoted bracket keys like '[artistSlug]', '[...slug]', '[[...topic]]'\n const re = /['\"](\\[{1,2}(?:\\.{3})?[^\\]]+\\]{1,2})['\"]\\s*:/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(blockContent)) !== null) {\n keys.push(m[1]);\n }\n return keys;\n}\n\n/** Schema file extensions to check. */\nconst SCHEMA_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\n\n/**\n * Find the schema file path if it exists.\n */\nexport function findSchemaFile(appDir: string): string | undefined {\n for (const ext of SCHEMA_EXTENSIONS) {\n const p = join(appDir, `schema${ext}`);\n if (existsSync(p)) return p;\n }\n return undefined;\n}\n\nexport function defaultCodecForSegment(seg: string): string {\n if (seg.startsWith('[[...')) return 'codec.optionalCatchAll(codec.string)';\n if (seg.startsWith('[...')) return 'codec.stringArray';\n return 'codec.string';\n}\n\n/**\n * Generate the content for a new app/schema.ts with the given segment keys.\n */\nfunction generateNewSchema(segments: string[]): string {\n const lines: string[] = [];\n lines.push(\"import { defineSchema } from '@timber-js/app/params';\");\n lines.push(\"import { codec } from '@timber-js/app/codec';\");\n lines.push('');\n lines.push('export default defineSchema({');\n lines.push(' segmentParams: {');\n for (const seg of segments) {\n lines.push(` '${seg}': ${defaultCodecForSegment(seg)},`);\n }\n lines.push(' },');\n lines.push('});');\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Append missing segment entries to an existing schema file.\n * Inserts new entries before the closing `}` of segmentParams.\n */\nconst CODEC_IMPORT = \"import { codec } from '@timber-js/app/codec';\";\n\nfunction hasCodecImport(content: string): boolean {\n return /import\\s+\\{[^}]*\\bcodec\\b[^}]*\\}\\s+from\\s+['\"]@timber-js\\/app\\/codec['\"]/.test(content);\n}\n\nfunction ensureCodecImport(content: string): string {\n if (hasCodecImport(content)) return content;\n\n // Insert after the last existing import statement\n const lines = content.split('\\n');\n let lastImportIndex = -1;\n for (let i = 0; i < lines.length; i++) {\n if (/^\\s*import\\s/.test(lines[i])) lastImportIndex = i;\n }\n\n if (lastImportIndex === -1) {\n return CODEC_IMPORT + '\\n' + content;\n }\n\n lines.splice(lastImportIndex + 1, 0, CODEC_IMPORT);\n return lines.join('\\n');\n}\n\nfunction appendToSchema(content: string, newSegments: string[]): string {\n content = ensureCodecImport(content);\n\n const block = findSegmentParamsBlock(content);\n if (!block) {\n throw new Error(\n '[timber] Could not find segmentParams in schema file. ' +\n 'Expected a defineSchema({ segmentParams: { ... } }) call.'\n );\n }\n const { openBrace, closeBrace } = block;\n\n // Detect indentation from existing entries\n const existingLine = content.slice(openBrace, closeBrace).match(/^(\\s+)['\"]\\[/m);\n const indent = existingLine ? existingLine[1] : ' ';\n\n // Build insertion text\n const insertion = newSegments\n .map((seg) => `${indent}'${seg}': ${defaultCodecForSegment(seg)},`)\n .join('\\n');\n\n // Insert before the closing brace\n const before = content.slice(0, closeBrace);\n const after = content.slice(closeBrace);\n\n // Add newline if the content before doesn't end with one\n const separator = before.trimEnd().endsWith(',') ? '\\n' : '\\n';\n\n return before + separator + insertion + '\\n' + after;\n}\n\n/**\n * Remove entries from the segmentParams block whose keys match `staleSegments`.\n * Removes the entire entry including trailing comma/whitespace. Scoped to\n * the segmentParams block — identical keys in unrelated objects elsewhere\n * in the file are left untouched.\n */\nfunction removeFromSchema(content: string, staleSegments: string[]): string {\n const block = findSegmentParamsBlock(content);\n if (!block) return content;\n\n let blockContent = content.slice(block.openBrace, block.closeBrace);\n // Key matching and the entry walk run on a comment-masked copy (same\n // length, indices align) so commented-out entries are never removed.\n // Both copies are spliced in sync to keep indices valid.\n let blockMasked = maskSource(blockContent, false);\n\n for (const seg of staleSegments) {\n const escaped = seg.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const keyRe = new RegExp(`^[ \\t]*['\"]${escaped}['\"][ \\t]*:`, 'gm');\n let m: RegExpExecArray | null;\n while ((m = keyRe.exec(blockMasked)) !== null) {\n const start = m.index;\n let i = m.index + m[0].length;\n let depth = 0;\n let inString: string | null = null;\n\n while (i < blockMasked.length) {\n const ch = blockMasked[i];\n if (inString) {\n if (ch === '\\\\') {\n i++;\n } else if (ch === inString) {\n inString = null;\n }\n } else if (ch === '\"' || ch === \"'\" || ch === '`') {\n inString = ch;\n } else if (ch === '(' || ch === '{' || ch === '[') {\n depth++;\n } else if (ch === ')' || ch === '}' || ch === ']') {\n depth--;\n } else if (depth === 0 && ch === ',') {\n i++;\n break;\n } else if (depth === 0 && (ch === '\\n' || ch === '}')) {\n break;\n }\n i++;\n }\n\n // Consume trailing newline\n if (i < blockMasked.length && blockMasked[i] === '\\n') i++;\n\n blockContent = blockContent.slice(0, start) + blockContent.slice(i);\n blockMasked = blockMasked.slice(0, start) + blockMasked.slice(i);\n keyRe.lastIndex = start;\n }\n }\n\n return content.slice(0, block.openBrace) + blockContent + content.slice(block.closeBrace);\n}\n\nexport interface SchemaSyncResult {\n /** Segments found in the filesystem. */\n filesystemSegments: string[];\n /** Segments already defined in app/schema.ts. */\n existingSegments: string[];\n /** Segments that were added. */\n addedSegments: string[];\n /** Segments that were removed (no longer in filesystem). */\n removedSegments: string[];\n /** Whether a new schema file was created. */\n created: boolean;\n}\n\n/**\n * Run the schema sync: scan filesystem, diff against schema, append missing.\n */\nexport function runSchemaSync(projectRoot: string): SchemaSyncResult {\n const appDir = resolveAppDir(projectRoot);\n\n const filesystemSegments = collectDynamicSegments(appDir);\n\n const schemaPath = findSchemaFile(appDir);\n\n if (filesystemSegments.length === 0 && !schemaPath) {\n return {\n filesystemSegments: [],\n existingSegments: [],\n addedSegments: [],\n removedSegments: [],\n created: false,\n };\n }\n\n if (!schemaPath) {\n // Create new schema file\n const newPath = join(appDir, 'schema.ts');\n writeFileSync(newPath, generateNewSchema(filesystemSegments), 'utf-8');\n return {\n filesystemSegments,\n existingSegments: [],\n addedSegments: filesystemSegments,\n removedSegments: [],\n created: true,\n };\n }\n\n // Read existing schema and diff\n const content = readFileSync(schemaPath, 'utf-8');\n const existingSegments = parseExistingSchemaKeys(content);\n const missing = filesystemSegments.filter((seg) => !existingSegments.includes(seg));\n const stale = existingSegments.filter((seg) => !filesystemSegments.includes(seg));\n\n if (missing.length === 0 && stale.length === 0) {\n return {\n filesystemSegments,\n existingSegments,\n addedSegments: [],\n removedSegments: [],\n created: false,\n };\n }\n\n let updated = content;\n if (stale.length > 0) {\n updated = removeFromSchema(updated, stale);\n }\n if (missing.length > 0) {\n updated = appendToSchema(updated, missing);\n }\n writeFileSync(schemaPath, updated, 'utf-8');\n\n return {\n filesystemSegments,\n existingSegments,\n addedSegments: missing,\n removedSegments: stale,\n created: false,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,aAAa,MAA2B;CAC/C,IAAI,KAAK,eAAe,KAAK,aAAa,OAAO,IAAI,KAAK,UAAU;CACpE,QAAQ,KAAK,aAAb;EACE,KAAK,aACH,OAAO,OAAO,KAAK,UAAU;EAC/B,KAAK,sBACH,OAAO,QAAQ,KAAK,UAAU;EAChC,SACE,OAAO,IAAI,KAAK,UAAU;CAC9B;AACF;;;;;AAMA,SAAgB,uBAAuB,QAA0B;CAC/D,MAAM,OAAO,WAAW,MAAM;CAC9B,MAAM,2BAAW,IAAI,IAAY;CACjC,aAAa,KAAK,MAAM,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{"version":3,"file":"cli-schema-sync-D2eI8jEg.js","names":[],"sources":["../../src/cli-schema-sync.ts"],"sourcesContent":["/**\n * `timber schema sync` — scan filesystem for dynamic segments, append\n * missing entries with `codec.string` defaults, and remove stale entries\n * whose segments no longer exist in the filesystem.\n *\n * Design doc: design/41-global-params.md §Auto-Scaffolding\n */\n\nimport { readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { scanRoutes } from './routing/scanner.ts';\nimport type { SegmentNode } from './routing/types.ts';\nimport { resolveAppDir } from './plugin-context.ts';\n\nfunction toBracketKey(node: SegmentNode): string {\n if (node.paramPrefix || node.paramSuffix) return `[${node.paramName}]`;\n switch (node.segmentType) {\n case 'catch-all':\n return `[...${node.paramName}]`;\n case 'optional-catch-all':\n return `[[...${node.paramName}]]`;\n default:\n return `[${node.paramName}]`;\n }\n}\n\n/**\n * Collect all unique bracket-keyed dynamic segment names from the route tree.\n * Returns entries like '[artistSlug]', '[...slug]', '[[...topic]]'.\n */\nexport function collectDynamicSegments(appDir: string): string[] {\n const tree = scanRoutes(appDir);\n const segments = new Set<string>();\n walkSegments(tree.root, segments);\n return [...segments].sort();\n}\n\nfunction walkSegments(node: SegmentNode, segments: Set<string>): void {\n if (node.paramName) {\n // Use bare bracket form for schema keys — affixed segments like\n // `img-[id].png` register as `[id]`, matching runtime codec lookup.\n segments.add(toBracketKey(node));\n }\n for (const child of node.children) {\n walkSegments(child, segments);\n }\n for (const slot of Object.values(node.slots)) {\n walkSegments(slot, segments);\n }\n}\n\n/**\n * Replace comment bodies (and optionally string contents) with spaces,\n * preserving length and newlines so every index maps 1:1 to the original.\n * Lets the structural scanning below ignore `segmentParams` mentions and\n * braces inside comments/strings without a TS parser (fine pre-alpha,\n * see TIM-1066).\n *\n * With `maskStrings`, string contents are blanked too — except literal\n * 'segmentParams' strings, kept so a quoted property key stays findable.\n */\nfunction maskSource(content: string, maskStrings: boolean): string {\n const out = content.split('');\n const n = content.length;\n let i = 0;\n\n const blank = (from: number, to: number): void => {\n for (let j = from; j < to; j++) {\n if (content[j] !== '\\n') out[j] = ' ';\n }\n };\n\n while (i < n) {\n const ch = content[i];\n const next = content[i + 1];\n if (ch === '/' && next === '/') {\n const start = i;\n while (i < n && content[i] !== '\\n') i++;\n blank(start, i);\n } else if (ch === '/' && next === '*') {\n const start = i;\n i += 2;\n while (i < n && !(content[i] === '*' && content[i + 1] === '/')) i++;\n i = Math.min(i + 2, n);\n blank(start, i);\n } else if (ch === '\"' || ch === \"'\" || ch === '`') {\n const start = i;\n i++;\n while (i < n && content[i] !== ch) {\n if (content[i] === '\\\\') i++;\n i++;\n }\n const end = i; // at closing quote (or n if unterminated)\n if (maskStrings && content.slice(start + 1, end) !== 'segmentParams') {\n blank(start + 1, end);\n }\n i++;\n } else {\n i++;\n }\n }\n return out.join('');\n}\n\n/**\n * Locate the `segmentParams: { ... }` block in a schema file.\n * Returns the indices of the opening and matching closing brace, or null\n * if no segmentParams property is found. Comments and strings are masked\n * first, so a JSDoc example mentioning `segmentParams: { ... }` above the\n * real defineSchema call is not mistaken for the block, and braces inside\n * comments/strings don't skew the depth count. The search is anchored to\n * the `defineSchema(` call when present, so helper objects with their own\n * segmentParams property earlier in the file are skipped.\n */\nexport function findSegmentParamsBlock(\n content: string\n): { openBrace: number; closeBrace: number } | null {\n const masked = maskSource(content, true);\n\n const defineCall = /\\bdefineSchema\\s*\\(/.exec(masked);\n const keyRe = /(['\"]?)segmentParams\\1\\s*:\\s*\\{/g;\n keyRe.lastIndex = defineCall ? defineCall.index + defineCall[0].length : 0;\n const keyMatch = keyRe.exec(masked);\n if (!keyMatch) return null;\n\n const openBrace = keyMatch.index + keyMatch[0].length - 1;\n let depth = 1;\n let i = openBrace + 1;\n while (i < masked.length && depth > 0) {\n if (masked[i] === '{') depth++;\n else if (masked[i] === '}') depth--;\n i++;\n }\n if (depth > 0) return null;\n // i now points to just after the closing brace\n return { openBrace, closeBrace: i - 1 };\n}\n\n/**\n * Parse existing bracket keys from an app/schema.ts file.\n * Scoped to the segmentParams: { ... } block — bracket keys elsewhere in\n * the file (unrelated objects, comments above defineSchema) are ignored.\n * Comments inside the block are masked, so a commented-out entry does not\n * count as registered.\n *\n * The key charset matches the route classifier (segment-classify.ts):\n * any character except `]`, so hyphenated params like '[my-param]' parse.\n */\nexport function parseExistingSchemaKeys(content: string): string[] {\n const block = findSegmentParamsBlock(content);\n if (!block) return [];\n\n const blockContent = maskSource(content, false).slice(block.openBrace, block.closeBrace);\n const keys: string[] = [];\n // Match quoted bracket keys like '[artistSlug]', '[...slug]', '[[...topic]]'\n const re = /['\"](\\[{1,2}(?:\\.{3})?[^\\]]+\\]{1,2})['\"]\\s*:/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(blockContent)) !== null) {\n keys.push(m[1]);\n }\n return keys;\n}\n\n/** Schema file extensions to check. */\nconst SCHEMA_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\n\n/**\n * Find the schema file path if it exists.\n */\nexport function findSchemaFile(appDir: string): string | undefined {\n for (const ext of SCHEMA_EXTENSIONS) {\n const p = join(appDir, `schema${ext}`);\n if (existsSync(p)) return p;\n }\n return undefined;\n}\n\nexport function defaultCodecForSegment(seg: string): string {\n if (seg.startsWith('[[...')) return 'codec.optionalCatchAll(codec.string)';\n if (seg.startsWith('[...')) return 'codec.stringArray';\n return 'codec.string';\n}\n\n/**\n * Generate the content for a new app/schema.ts with the given segment keys.\n */\nfunction generateNewSchema(segments: string[]): string {\n const lines: string[] = [];\n lines.push(\"import { defineSchema } from '@timber-js/app/params';\");\n lines.push(\"import { codec } from '@timber-js/app/codec';\");\n lines.push('');\n lines.push('export default defineSchema({');\n lines.push(' segmentParams: {');\n for (const seg of segments) {\n lines.push(` '${seg}': ${defaultCodecForSegment(seg)},`);\n }\n lines.push(' },');\n lines.push('});');\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Append missing segment entries to an existing schema file.\n * Inserts new entries before the closing `}` of segmentParams.\n */\nconst CODEC_IMPORT = \"import { codec } from '@timber-js/app/codec';\";\n\nfunction hasCodecImport(content: string): boolean {\n return /import\\s+\\{[^}]*\\bcodec\\b[^}]*\\}\\s+from\\s+['\"]@timber-js\\/app\\/codec['\"]/.test(content);\n}\n\nfunction ensureCodecImport(content: string): string {\n if (hasCodecImport(content)) return content;\n\n // Insert after the last existing import statement\n const lines = content.split('\\n');\n let lastImportIndex = -1;\n for (let i = 0; i < lines.length; i++) {\n if (/^\\s*import\\s/.test(lines[i])) lastImportIndex = i;\n }\n\n if (lastImportIndex === -1) {\n return CODEC_IMPORT + '\\n' + content;\n }\n\n lines.splice(lastImportIndex + 1, 0, CODEC_IMPORT);\n return lines.join('\\n');\n}\n\nfunction appendToSchema(content: string, newSegments: string[]): string {\n content = ensureCodecImport(content);\n\n const block = findSegmentParamsBlock(content);\n if (!block) {\n throw new Error(\n '[timber] Could not find segmentParams in schema file. ' +\n 'Expected a defineSchema({ segmentParams: { ... } }) call.'\n );\n }\n const { openBrace, closeBrace } = block;\n\n // Detect indentation from existing entries\n const existingLine = content.slice(openBrace, closeBrace).match(/^(\\s+)['\"]\\[/m);\n const indent = existingLine ? existingLine[1] : ' ';\n\n // Build insertion text\n const insertion = newSegments\n .map((seg) => `${indent}'${seg}': ${defaultCodecForSegment(seg)},`)\n .join('\\n');\n\n // Insert before the closing brace\n const before = content.slice(0, closeBrace);\n const after = content.slice(closeBrace);\n\n // Add newline if the content before doesn't end with one\n const separator = before.trimEnd().endsWith(',') ? '\\n' : '\\n';\n\n return before + separator + insertion + '\\n' + after;\n}\n\n/**\n * Remove entries from the segmentParams block whose keys match `staleSegments`.\n * Removes the entire entry including trailing comma/whitespace. Scoped to\n * the segmentParams block — identical keys in unrelated objects elsewhere\n * in the file are left untouched.\n */\nfunction removeFromSchema(content: string, staleSegments: string[]): string {\n const block = findSegmentParamsBlock(content);\n if (!block) return content;\n\n let blockContent = content.slice(block.openBrace, block.closeBrace);\n // Key matching and the entry walk run on a comment-masked copy (same\n // length, indices align) so commented-out entries are never removed.\n // Both copies are spliced in sync to keep indices valid.\n let blockMasked = maskSource(blockContent, false);\n\n for (const seg of staleSegments) {\n const escaped = seg.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const keyRe = new RegExp(`^[ \\t]*['\"]${escaped}['\"][ \\t]*:`, 'gm');\n let m: RegExpExecArray | null;\n while ((m = keyRe.exec(blockMasked)) !== null) {\n const start = m.index;\n let i = m.index + m[0].length;\n let depth = 0;\n let inString: string | null = null;\n\n while (i < blockMasked.length) {\n const ch = blockMasked[i];\n if (inString) {\n if (ch === '\\\\') {\n i++;\n } else if (ch === inString) {\n inString = null;\n }\n } else if (ch === '\"' || ch === \"'\" || ch === '`') {\n inString = ch;\n } else if (ch === '(' || ch === '{' || ch === '[') {\n depth++;\n } else if (ch === ')' || ch === '}' || ch === ']') {\n depth--;\n } else if (depth === 0 && ch === ',') {\n i++;\n break;\n } else if (depth === 0 && (ch === '\\n' || ch === '}')) {\n break;\n }\n i++;\n }\n\n // Consume trailing newline\n if (i < blockMasked.length && blockMasked[i] === '\\n') i++;\n\n blockContent = blockContent.slice(0, start) + blockContent.slice(i);\n blockMasked = blockMasked.slice(0, start) + blockMasked.slice(i);\n keyRe.lastIndex = start;\n }\n }\n\n return content.slice(0, block.openBrace) + blockContent + content.slice(block.closeBrace);\n}\n\nexport interface SchemaSyncResult {\n /** Segments found in the filesystem. */\n filesystemSegments: string[];\n /** Segments already defined in app/schema.ts. */\n existingSegments: string[];\n /** Segments that were added. */\n addedSegments: string[];\n /** Segments that were removed (no longer in filesystem). */\n removedSegments: string[];\n /** Whether a new schema file was created. */\n created: boolean;\n}\n\n/**\n * Run the schema sync: scan filesystem, diff against schema, append missing.\n */\nexport function runSchemaSync(projectRoot: string): SchemaSyncResult {\n const appDir = resolveAppDir(projectRoot);\n\n const filesystemSegments = collectDynamicSegments(appDir);\n\n const schemaPath = findSchemaFile(appDir);\n\n if (filesystemSegments.length === 0 && !schemaPath) {\n return {\n filesystemSegments: [],\n existingSegments: [],\n addedSegments: [],\n removedSegments: [],\n created: false,\n };\n }\n\n if (!schemaPath) {\n // Create new schema file\n const newPath = join(appDir, 'schema.ts');\n writeFileSync(newPath, generateNewSchema(filesystemSegments), 'utf-8');\n return {\n filesystemSegments,\n existingSegments: [],\n addedSegments: filesystemSegments,\n removedSegments: [],\n created: true,\n };\n }\n\n // Read existing schema and diff\n const content = readFileSync(schemaPath, 'utf-8');\n const existingSegments = parseExistingSchemaKeys(content);\n const missing = filesystemSegments.filter((seg) => !existingSegments.includes(seg));\n const stale = existingSegments.filter((seg) => !filesystemSegments.includes(seg));\n\n if (missing.length === 0 && stale.length === 0) {\n return {\n filesystemSegments,\n existingSegments,\n addedSegments: [],\n removedSegments: [],\n created: false,\n };\n }\n\n let updated = content;\n if (stale.length > 0) {\n updated = removeFromSchema(updated, stale);\n }\n if (missing.length > 0) {\n updated = appendToSchema(updated, missing);\n }\n writeFileSync(schemaPath, updated, 'utf-8');\n\n return {\n filesystemSegments,\n existingSegments,\n addedSegments: missing,\n removedSegments: stale,\n created: false,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,aAAa,MAA2B;CAC/C,IAAI,KAAK,eAAe,KAAK,aAAa,OAAO,IAAI,KAAK,UAAU;CACpE,QAAQ,KAAK,aAAb;EACE,KAAK,aACH,OAAO,OAAO,KAAK,UAAU;EAC/B,KAAK,sBACH,OAAO,QAAQ,KAAK,UAAU;EAChC,SACE,OAAO,IAAI,KAAK,UAAU;CAC9B;AACF;;;;;AAMA,SAAgB,uBAAuB,QAA0B;CAC/D,MAAM,OAAO,WAAW,MAAM;CAC9B,MAAM,2BAAW,IAAI,IAAY;CACjC,aAAa,KAAK,MAAM,QAAQ;CAChC,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC,KAAK;AAC5B;AAEA,SAAS,aAAa,MAAmB,UAA6B;CACpE,IAAI,KAAK,WAGP,SAAS,IAAI,aAAa,IAAI,CAAC;C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,MAAM,MAAM,UAAU;AAC1F;;;;AAkBA,SAAgB,cAAc,aAAuC;CACnE,MAAM,SAAS,cAAc,WAAW;CAExC,MAAM,qBAAqB,uBAAuB,MAAM;CAExD,MAAM,aAAa,eAAe,MAAM;CAExC,IAAI,mBAAmB,WAAW,KAAK,CAAC,YACtC,OAAO;EACL,oBAAoB,CAAC;EACrB,kBAAkB,CAAC;EACnB,eAAe,CAAC;EAChB,iBAAiB,CAAC;EAClB,SAAS;CACX;CAGF,IAAI,CAAC,YAAY;EAEf,MAAM,UAAU,KAAK,QAAQ,WAAW;EACxC,cAAc,SAAS,kBAAkB,kBAAkB,GAAG,OAAO;EACrE,OAAO;GACL;GACA,kBAAkB,CAAC;GACnB,eAAe;GACf,iBAAiB,CAAC;GAClB,SAAS;EACX;CACF;CAGA,MAAM,UAAU,aAAa,YAAY,OAAO;CAChD,MAAM,mBAAmB,wBAAwB,OAAO;CACxD,MAAM,UAAU,mBAAmB,QAAQ,QAAQ,CAAC,iBAAiB,SAAS,GAAG,CAAC;CAClF,MAAM,QAAQ,iBAAiB,QAAQ,QAAQ,CAAC,mBAAmB,SAAS,GAAG,CAAC;CAEhF,IAAI,QAAQ,WAAW,KAAK,MAAM,WAAW,GAC3C,OAAO;EACL;EACA;EACA,eAAe,CAAC;EAChB,iBAAiB,CAAC;EAClB,SAAS;CACX;CAGF,IAAI,UAAU;CACd,IAAI,MAAM,SAAS,GACjB,UAAU,iBAAiB,SAAS,KAAK;CAE3C,IAAI,QAAQ,SAAS,GACnB,UAAU,eAAe,SAAS,OAAO;CAE3C,cAAc,YAAY,SAAS,OAAO;CAE1C,OAAO;EACL;EACA;EACA,eAAe;EACf,iBAAiB;EACjB,SAAS;CACX;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as classifyUrlSegment, r as effectiveUrlSegment } from "./segment-classify-C539Pa2O.js";
|
|
2
2
|
import { join, relative } from "node:path";
|
|
3
|
-
import { existsSync
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
4
|
//#region src/routing/codegen-shared.ts
|
|
5
5
|
/**
|
|
6
6
|
* Build a TypeScript type expression for a single param using the global
|
|
@@ -427,32 +427,6 @@ function formatParamsType(params, hasSchema) {
|
|
|
427
427
|
}).join("; ")} }`;
|
|
428
428
|
}
|
|
429
429
|
//#endregion
|
|
430
|
-
|
|
431
|
-
var cache = /* @__PURE__ */ new Map();
|
|
432
|
-
/**
|
|
433
|
-
* Read a file's text content, returning a cached copy when the file
|
|
434
|
-
* hasn't been modified since the last read (checked via mtime + size).
|
|
435
|
-
*
|
|
436
|
-
* Falls back to a fresh read on any stat/read error.
|
|
437
|
-
*/
|
|
438
|
-
function readFileCached(filePath) {
|
|
439
|
-
try {
|
|
440
|
-
const stat = statSync(filePath);
|
|
441
|
-
const entry = cache.get(filePath);
|
|
442
|
-
if (entry && entry.mtimeMs === stat.mtimeMs && entry.size === stat.size) return entry.content;
|
|
443
|
-
const content = readFileSync(filePath, "utf-8");
|
|
444
|
-
cache.set(filePath, {
|
|
445
|
-
mtimeMs: stat.mtimeMs,
|
|
446
|
-
size: stat.size,
|
|
447
|
-
content
|
|
448
|
-
});
|
|
449
|
-
return content;
|
|
450
|
-
} catch {
|
|
451
|
-
cache.delete(filePath);
|
|
452
|
-
return readFileSync(filePath, "utf-8");
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
//#endregion
|
|
456
|
-
export { generateRouteMap as n, readFileCached as t };
|
|
430
|
+
export { generateRouteMap as t };
|
|
457
431
|
|
|
458
|
-
//# sourceMappingURL=
|
|
432
|
+
//# sourceMappingURL=codegen-Bps1sLKJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codegen-Bps1sLKJ.js","names":[],"sources":["../../src/routing/codegen-shared.ts","../../src/routing/link-codegen.ts","../../src/routing/codegen.ts"],"sourcesContent":["/**\n * Shared codegen helpers — import-path computation and codec chain type\n * builders.\n *\n * Extracted from `codegen.ts` so `link-codegen.ts` can use the same\n * helpers without a cyclic import.\n */\n\nimport { relative, posix } from 'node:path';\nimport type { ParamEntry } from './codegen-types.ts';\n\n/**\n * Compute a relative import specifier for a codec/page file, stripping\n * the .ts/.tsx extension and resolving against the codegen output dir.\n */\nexport function codecImportPath(codecFilePath: string, importBase: string | undefined): string {\n const absPath = codecFilePath.replace(/\\.(ts|tsx)$/, '');\n if (importBase) {\n return './' + relative(importBase, absPath).replace(/\\\\/g, '/');\n }\n return './' + posix.basename(absPath);\n}\n\n/**\n * Build a TypeScript type expression for a single param using the global\n * schema's InferCodecType. Falls back to the param's base type when\n * schema doesn't declare this param (schemas are opt-in per key).\n *\n * Uses `infer` to extract the codec value rather than direct indexing\n * because TypeScript doesn't narrow index validity inside a conditional\n * type's true branch — `typeof schema.segmentParams[K]` produces TS2538\n * even when the condition proves K is a valid key. In .d.ts files that\n * error is suppressed and the type silently becomes `any`.\n */\nexport function buildSchemaParamType(p: ParamEntry, fallback?: string): string {\n const key = JSON.stringify(p.bracketName);\n const fb = fallback ?? p.type;\n return `typeof schema['segmentParams'] extends Record<${key}, infer V> ? InferCodecType<V> : ${fb}`;\n}\n","/**\n * Typed `<Link>` codegen — interface augmentation generation.\n *\n * Extracted from `codegen.ts` to keep that file under the project's\n * 500-line cap. This module owns everything that emits the\n * `interface LinkFunction { ... }` augmentation blocks in the generated\n * `.timber/timber-routes.d.ts`.\n *\n * Two augmentation blocks are emitted:\n *\n * 1. **Per-route discriminated union** (`formatTypedLinkOverloads`) —\n * one call signature whose props is a union keyed on `href`. TS\n * narrows by literal href and reports prop errors against the\n * matched variant. See TIM-835 and `design/09-typescript.md`.\n *\n * 2. **Catch-all overloads** (`formatLinkCatchAllOverloads`) — external\n * href literals (`http://`, `mailto:`, etc.) and a computed-string\n * `<H extends string>` signature for runtime-computed paths.\n *\n * Block ordering is critical for error UX: per-route is emitted FIRST\n * so that, after TS's \"later overload set ordered first\" merge rule,\n * the discriminated union ends up LAST in resolution order — the\n * overload TS reports against on failure.\n */\n\nimport type { ParamEntry, RouteEntry } from './codegen-types.ts';\nimport { buildSchemaParamType } from './codegen-shared.ts';\nimport { classifyUrlSegment } from './segment-classify.ts';\n\n/**\n * The `searchParams` prop type, emitted identically on every Link variant\n * — per-route pattern, resolved template, and catch-all.\n *\n * TIM-1343: there is no per-route narrowing any more. `params.ts` is gone,\n * so codegen has no definition to read a `SearchParamsDefinition<T>` from.\n * Type safety moved to the value's construction site instead: callers write\n * `definition.buildSearchParams({ ... })`, which checks `Partial<T>` there\n * and returns a query STRING — the only shape that survives the RSC Flight\n * boundary. A plain record is the uncodec'd escape hatch. See `client/link.tsx` §\"searchParams prop shapes\".\n *\n * Declared once so the three emission sites cannot drift apart.\n */\nexport const SEARCH_PARAMS_PROP_TYPE = 'string | Record<string, unknown>';\n\n/** Shared Link base-props type literal used in every emitted call signature. */\nexport const LINK_BASE_PROPS_TYPE =\n \"Omit<import('react').AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> & { prefetch?: boolean; scroll?: boolean; preserveSearchParams?: true | string[]; onNavigate?: import('./client/link.js').OnNavigateHandler; children?: import('react').ReactNode }\";\n\n/**\n * Build a TypeScript template literal pattern for a dynamic route.\n * e.g. '/products/[id]' → '/products/${string}'\n * '/blog/[...slug]' → '/blog/${string}'\n * '/docs/[[...path]]' → '/docs/${string}' (also matches /docs)\n * '/[org]/[repo]' → '/${string}/${string}'\n */\nexport function buildResolvedPattern(route: RouteEntry): string | null {\n const parts = route.urlPath.split('/');\n const templateParts = parts.map((part) => {\n const seg = classifyUrlSegment(part);\n switch (seg.kind) {\n case 'catch-all':\n case 'optional-catch-all':\n // eslint-disable-next-line no-template-curly-in-string -- codegen output\n return '${string}';\n case 'dynamic': {\n const prefix = seg.prefix ?? '';\n const suffix = seg.suffix ?? '';\n // eslint-disable-next-line no-template-curly-in-string -- codegen output\n return `${prefix}\\${string}${suffix}`;\n }\n default:\n return part;\n }\n });\n return templateParts.join('/');\n}\n\n/**\n * Format the segmentParams type for Link overloads.\n *\n * Link params accept `string | number` for single dynamic segments\n * (convenience — values are stringified at runtime). Catch-all and\n * optional catch-all remain `string[]` / `string[] | undefined`.\n *\n * With a global schema, the schema codec's inferred type wins. Without\n * one, a URL segment is a raw string (widened to string | number for\n * Link convenience) — per-segment codec chains were deleted in TIM-1342.\n */\nexport function formatLinkParamsType(params: ParamEntry[], hasSchema?: boolean): string {\n if (params.length === 0) {\n return '{}';\n }\n\n const fields = params.map((p) => {\n const fallback = p.type === 'string' ? 'string | number' : p.type;\n const codecType = hasSchema ? buildSchemaParamType(p, fallback) : fallback;\n return `${p.name}: ${codecType}`;\n });\n return `{ ${fields.join('; ')} }`;\n}\n\n/**\n * Catch-all call signatures for `<Link>` — external hrefs and computed\n * `string` variables. Emitted from codegen in a SEPARATE\n * `declare module` block (declared AFTER the per-route block) so the TS\n * \"later overload set ordered first\" rule places these catch-all\n * signatures ahead of per-route in resolution order, leaving per-route\n * as the final overload whose error message is reported on failure.\n *\n * The conditional `string extends H ? ... : never` protection preserves\n * TIM-624's guarantee that unknown internal path literals don't match\n * the catch-all — typos like `<Link href=\"/typo\" />` still error.\n */\nexport function formatLinkCatchAllOverloads(): string[] {\n const lines: string[] = [];\n const baseProps = LINK_BASE_PROPS_TYPE;\n\n const catchAllSearchParams = SEARCH_PARAMS_PROP_TYPE;\n\n // ExternalHref inlined here rather than referenced as an exported\n // alias so the generated .d.ts stands alone without source imports.\n /* eslint-disable no-template-curly-in-string -- codegen output */\n const externalHref =\n '`http://${string}` | `https://${string}` | `mailto:${string}` | `tel:${string}` | `ftp://${string}` | `//${string}` | `#${string}` | `?${string}`';\n /* eslint-enable no-template-curly-in-string */\n\n lines.push(' // Typed Link overloads — catch-all (block 2 / emitted second)');\n lines.push(' interface LinkFunction {');\n\n // (1) External/literal-protocol hrefs.\n //\n // TIM-833: `segmentParams` is permissively typed as\n // `Record<string, unknown>` (not `never`) so generic wrappers that\n // forward a `LinkProps`-shaped object can compile when the wrapper\n // happens to bottom out at an external href. There are no dynamic\n // segments to interpolate for an external href, so this prop is\n // ignored at runtime — accepting an open-shape object instead of\n // forbidding it removes a footgun without changing behavior.\n lines.push(` (props: ${baseProps} & {`);\n lines.push(` href: ${externalHref}`);\n lines.push(` segmentParams?: Record<string, unknown>`);\n lines.push(` searchParams?: ${catchAllSearchParams}`);\n lines.push(` }): import('react').JSX.Element`);\n\n // (2) Computed/variable href — non-literal `string` only.\n //\n // `string extends H` is true only when H is the wide `string` type,\n // not a specific literal. For literal hrefs, this overload must NOT\n // be selectable so the per-route discriminated union (block 1) is\n // the resolution target.\n //\n // TIM-833 follow-up: the previous shape used `string extends H ? {...} : never`\n // on the WHOLE props type. For literal H, that collapsed `props` to\n // `never`, and JSX type inference then read `(never).children` as\n // `never` — producing the misleading\n // `'children' prop expects type 'never' which requires multiple\n // children, but only a single child was provided` (TS2745) error,\n // which buried the actual prop-mismatch message under a noise diagnostic.\n //\n // Fix: move the `: never` from the whole props onto just the `href`\n // field. The overload remains uncallable for literal H (since `\"/x\"`\n // is not assignable to `never`), but `children` retains its real\n // `ReactNode` type so JSX inference no longer collapses to never.\n // The diagnostic surface becomes: TS reports the per-route block's\n // error chain (the helpful \"Type 'number' is not assignable to type\n // 'string'\" message) WITHOUT a leading TS2745 noise line.\n lines.push(` <H extends string>(`);\n lines.push(` props: ${baseProps} & {`);\n lines.push(` href: string extends H ? H : never`);\n lines.push(` segmentParams?: Record<string, string | number | string[]>`);\n lines.push(` searchParams?: ${catchAllSearchParams}`);\n lines.push(` }`);\n lines.push(` ): import('react').JSX.Element`);\n\n lines.push(' }');\n return lines;\n}\n\n/**\n * Generate typed per-route Link call signatures via LinkFunction\n * interface merging.\n *\n * TIM-835: This emits a SINGLE call signature whose props is a\n * discriminated union keyed on `href`. TypeScript narrows the union by\n * the literal `href` at the call site, then checks the rest of the\n * props against the matched variant. When `segmentParams` or\n * `searchParams` is wrong, TS reports the error against the matched\n * variant — naming the user's actual `href` and the offending field.\n *\n * Before TIM-835, this function emitted N separate per-route overloads\n * (one per route, sometimes two for dynamic routes). When ALL overloads\n * failed, TS would pick an arbitrary failed overload (heuristically the\n * \"last tried\") to render the diagnostic, often pointing at a route\n * completely unrelated to the one the user wrote. The discriminated\n * union sidesteps overload-resolution heuristics entirely.\n *\n * Open property shapes (`Record<string, unknown>` instead of `never`)\n * for `segmentParams` on routes that don't declare them keep generic\n * `LinkProps`-spreading wrappers compiling. (Aligned with TIM-833.)\n *\n * TIM-832: this function still emits the per-route block FIRST and the\n * catch-all block follows, so per-route remains the LAST overload set in\n * resolution order — the one TS reports against on failure. With a\n * discriminated union there is only one call signature in this block,\n * so the resolved-template-vs-pattern ordering reduces to placing the\n * pattern variant before the resolved-template variant inside the union.\n */\nexport function formatTypedLinkOverloads(routes: RouteEntry[], hasSchema?: boolean): string[] {\n const lines: string[] = [];\n const baseProps = LINK_BASE_PROPS_TYPE;\n\n // Build the union variants. Each route contributes one variant for the\n // pattern href (e.g. '/products/[id]') and, for dynamic routes, an\n // additional variant for the resolved-template href (e.g.\n // `/products/${string}`).\n //\n // The PATTERN variant must be listed BEFORE the resolved-template\n // variant for the same route so that when the user writes the literal\n // pattern href (`<Link href=\"/products/[id]\" />`), TS narrows to the\n // pattern variant (which carries the typed `segmentParams` shape)\n // rather than the looser resolved-template variant. Without this\n // ordering, TS would silently match the resolved-template variant\n // first — swallowing typed-segmentParams type errors.\n const variants: string[] = [];\n for (const route of routes) {\n const hasDynamicParams = route.params.length > 0;\n // For routes with no dynamic params, accept an absent OR open-shape\n // segmentParams. `Record<string, unknown>` keeps generic spreads\n // compiling and gives a readable error if a non-object is passed.\n const paramsProp = hasDynamicParams\n ? `segmentParams: ${formatLinkParamsType(route.params, hasSchema)}`\n : 'segmentParams?: Record<string, unknown>';\n\n // TIM-1343: searchParams is no longer typed per-route. There is no\n // convention file to read a definition from, so codegen has nothing to\n // narrow with — the value is either a URLSearchParams built by\n // `definition.buildSearchParams()` (which type-checks its own\n // `Partial<T>` at that call) or a plain String()-coerced record.\n const searchParamsProp = `searchParams?: ${SEARCH_PARAMS_PROP_TYPE}`;\n\n // Pattern variant FIRST (more specific).\n variants.push(\n `${baseProps} & { href: '${route.urlPath}'; ${paramsProp}; ${searchParamsProp} }`\n );\n\n // Resolved-template variant SECOND (looser, matches interpolated hrefs).\n if (hasDynamicParams) {\n const templatePattern = buildResolvedPattern(route);\n if (templatePattern) {\n // TIM-835: `Record<string, never>` for segmentParams forbids ANY\n // provided keys on the resolved-template variant. Without this,\n // the resolved-template would shadow the pattern variant for\n // literal pattern hrefs (`<Link href=\"/products/[id]\" segmentParams={...} />`)\n // because both variants accept the literal `'/products/[id]'`\n // and the looser variant would silently swallow segmentParams\n // type errors.\n variants.push(\n `${baseProps} & { href: \\`${templatePattern}\\`; segmentParams?: Record<string, never>; ${searchParamsProp} }`\n );\n }\n }\n }\n\n lines.push(' interface LinkFunction {');\n if (variants.length === 0) {\n // No page routes — emit nothing. The catch-all block in the second\n // augmentation still provides external/computed-string signatures.\n lines.push(' }');\n return lines;\n }\n lines.push(' (');\n lines.push(' props:');\n for (const variant of variants) {\n lines.push(` | (${variant})`);\n }\n lines.push(` ): import('react').JSX.Element`);\n lines.push(' }');\n\n return lines;\n}\n","/**\n * Route map codegen.\n *\n * Walks the scanned RouteTree and generates a TypeScript declaration file\n * mapping every route to its params and searchParams shapes.\n *\n * This runs at build time and in dev (regenerated on file changes).\n * No runtime overhead — purely static type generation.\n */\n\nimport { existsSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { RouteTree, SegmentNode } from './types.ts';\nimport type { ParamEntry, RouteEntry } from './codegen-types.ts';\nimport { buildSchemaParamType } from './codegen-shared.ts';\nimport { effectiveUrlSegment, type UrlSegmentIdentity } from './segment-classify.ts';\nimport { formatLinkCatchAllOverloads, formatTypedLinkOverloads } from './link-codegen.ts';\n\n/** Options for route map generation. */\nexport interface CodegenOptions {\n /** Absolute path to the app/ directory. Required for page searchParams detection. */\n appDir?: string;\n /**\n * Absolute path to the directory where the .d.ts file will be written.\n * Used to compute correct relative import paths for page files.\n * Defaults to appDir when not provided (preserves backward compat for tests).\n */\n outputDir?: string;\n /**\n * Whether a global schema (app/schema.ts) exists.\n * Auto-detected from appDir when not explicitly set.\n */\n hasSchema?: boolean;\n}\n\n/**\n * Generate a TypeScript declaration file string from a scanned route tree.\n *\n * The output is a `declare module '@timber-js/app'` block containing the Routes\n * interface that maps every route path to its params and searchParams shape.\n */\nexport function generateRouteMap(tree: RouteTree, options: CodegenOptions = {}): string {\n // Auto-detect schema from appDir when not explicitly set\n const hasSchema = options.hasSchema ?? detectSchema(options.appDir);\n\n const routes: RouteEntry[] = [];\n collectRoutes(tree.root, [], '', routes, hasSchema, false);\n\n // Sort routes alphabetically for deterministic output\n routes.sort((a, b) => a.urlPath.localeCompare(b.urlPath));\n\n // When outputDir differs from appDir, import paths must be relative to outputDir\n const importBase = options.outputDir ?? options.appDir;\n\n return formatDeclarationFile(routes, importBase, hasSchema, options.appDir);\n}\n\n/** Schema file extensions to check, in priority order. */\nconst SCHEMA_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\n\n/**\n * Detect whether app/schema.{ts,tsx,js,jsx} exists.\n */\nfunction detectSchema(appDir: string | undefined): boolean {\n if (!appDir) return false;\n return SCHEMA_EXTENSIONS.some((ext) => existsSync(join(appDir, `schema${ext}`)));\n}\n\n/**\n * Recursively walk the segment tree and collect route entries.\n *\n * A route entry is created for any segment that has a `page` or `route` file.\n * Params accumulate from ancestor dynamic segments.\n */\nfunction collectRoutes(\n node: SegmentNode,\n ancestorParams: ParamEntry[],\n parentTreePath: string,\n routes: RouteEntry[],\n hasSchema: boolean,\n insideSlot: boolean,\n insideIntercepting = false\n): void {\n // Build the tree path (includes groups, slots — uniquely identifies this segment).\n // Root node has empty segmentName, producing treePath = ''.\n const treePath = node.segmentName ? `${parentTreePath}/${node.segmentName}` : parentTreePath;\n // Accumulate params from this segment.\n //\n // The segment is read through `effectiveUrlSegment` for the same reason the\n // runtime coercer is: an intercepting node's own `segmentType` is\n // 'intercepting' and its `paramName` is unset — the param it binds lives in\n // the intercepted name (`(.)[albumSlug]` → `[albumSlug]`). Reading the node\n // directly emitted `{}` for a segment the router does bind and coerce, so\n // the types disagreed with the values for every intercepting page with a\n // dynamic intercepted segment, and for its descendants, which lost the\n // ancestor param too.\n const urlSegment = effectiveUrlSegment(node);\n const params = [...ancestorParams];\n if (urlSegment.paramName) {\n params.push({\n name: urlSegment.paramName,\n bracketName: bracketNameForSegment(urlSegment),\n type: paramTypeForSegment(urlSegment.segmentType),\n });\n }\n\n // Check if this segment is a leaf route (has page or route file)\n const isPage = !!node.page;\n const isApiRoute = !!node.route;\n\n // A segment that hosts code but is not itself addressable — a layout,\n // middleware, or access check above the leaf — still gets a `$segment`\n // module, so `getSegmentParams(SEGMENT_PATH)` is callable from it and needs\n // a matching typed overload. Emitting only leaves left those call sites on\n // the broad `Record<string, string | string[]>` signature, which since\n // TIM-1342 (which deleted `defineSegmentParams`) is their ONLY typed path.\n // design/41-global-params.md's Type Summary promises layouts and middleware\n // exact accumulated params.\n //\n // `isRoutable: false` keeps them out of the urlPath-keyed emissions — the\n // `Routes` interface and `<Link>` variants — where they would publish a URL\n // that no request can reach. They belong only to the segmentPath-keyed\n // APIs: `getSegmentParams`, `useSegmentParams`, `TimberSegmentParams`.\n const hostsCode = !!node.layout || !!node.middleware || !!node.access;\n\n if (isPage || isApiRoute || hostsCode) {\n const entry: RouteEntry = {\n urlPath: node.urlPath,\n segmentPath: treePath || '/',\n params,\n isApiRoute,\n isRoutable: isPage || isApiRoute,\n isSlotRoute: insideSlot,\n isInterceptingRoute: insideIntercepting,\n hasSchema,\n };\n\n routes.push(entry);\n }\n\n // Recurse into children. An intercepting subtree is flagged, and the flag is\n // sticky — the descendants are where the false URLs are. See\n // `RouteEntry.isInterceptingRoute` for what the flag drops and why dedupe\n // alone was not enough.\n for (const child of node.children) {\n const childIntercepting = insideIntercepting || child.segmentType === 'intercepting';\n collectRoutes(child, params, treePath, routes, hasSchema, insideSlot, childIntercepting);\n }\n\n // Recurse into slots (they share the parent's URL path, but may have their own pages)\n for (const slot of Object.values(node.slots)) {\n collectRoutes(slot, params, treePath, routes, hasSchema, true, insideIntercepting);\n }\n}\n\n/**\n * Dedupe route entries by urlPath for urlPath-keyed emissions (the Routes\n * interface and typed Link variants).\n *\n * Parallel-slot pages share their parent's urlPath; emitting one entry per\n * slot page produced duplicate interface keys (TS2300/TS2717 under\n * skipLibCheck:false) and duplicate overloads. The non-slot entry is the\n * canonical one; when only slot entries exist (parent has no page), the\n * lexicographically smallest segmentPath wins so output is independent of\n * slot scan order.\n *\n * The loser is discarded outright. It used to donate its `searchParams`\n * definition to the winner, because a slot could carry one the parent page\n * lacked; since TIM-1343 no route entry carries a searchParams definition at\n * all, there is nothing left to merge.\n *\n * segmentPath-keyed emissions (getSegmentParams, useSegmentParams,\n * TimberSegmentParams) must NOT use this — segmentPaths are already unique\n * and slot entries feed those APIs directly.\n */\nfunction dedupeRoutesByUrlPath(routes: RouteEntry[]): RouteEntry[] {\n const byPath = new Map<string, RouteEntry>();\n for (const route of routes) {\n const existing = byPath.get(route.urlPath);\n if (!existing) {\n byPath.set(route.urlPath, route);\n continue;\n }\n\n const routeWins =\n (existing.isSlotRoute && !route.isSlotRoute) ||\n (!!existing.isSlotRoute === !!route.isSlotRoute &&\n route.segmentPath.localeCompare(existing.segmentPath) < 0);\n byPath.set(route.urlPath, routeWins ? route : existing);\n }\n return [...byPath.values()];\n}\n\n/**\n * Determine the TypeScript type for a segment's param.\n */\n/**\n * Derive the bracket key for schema/codegen lookup.\n * For bare segments like `[id]` this is the segmentName itself.\n * For affixed segments like `img-[id].png` this is `[id]` — the bare bracket form.\n */\nfunction bracketNameForSegment(node: UrlSegmentIdentity): string {\n if (node.paramPrefix || node.paramSuffix) {\n return `[${node.paramName}]`;\n }\n return node.segmentName;\n}\n\nfunction paramTypeForSegment(segmentType: string): ParamEntry['type'] {\n switch (segmentType) {\n case 'catch-all':\n return 'string[]';\n case 'optional-catch-all':\n return 'string[] | undefined';\n default:\n return 'string';\n }\n}\n\n/**\n * Emit the schema-based type exports: TimberSegmentParams, TimberRoute,\n * AllSegmentParams, RoutesWithParams.\n *\n * These types use InferCodecType references so they stay in sync with\n * the schema without hardcoding resolved types.\n *\n * Design doc: design/41-global-params.md §Codegen Output\n */\nfunction formatSchemaTypes(routes: RouteEntry[]): string[] {\n const lines: string[] = [];\n\n lines.push('/** Union of all valid route patterns. */');\n lines.push('export type TimberRoute = keyof TimberSegmentParams;');\n lines.push('');\n lines.push('/** Maps each segment path to its accumulated segment params. */');\n lines.push('export interface TimberSegmentParams {');\n\n for (const route of routes) {\n if (route.params.length === 0) {\n lines.push(` '${route.segmentPath}': {};`);\n } else {\n lines.push(` '${route.segmentPath}': {`);\n for (const p of route.params) {\n lines.push(` ${p.name}: ${buildSchemaParamType(p)};`);\n }\n lines.push(' };');\n }\n }\n\n lines.push('}');\n lines.push('');\n\n // AllSegmentParams — flat union of all param types across all routes\n lines.push('/** All segment params (union of all route params). */');\n lines.push('export type AllSegmentParams = {');\n lines.push(\n ' [K in keyof TimberSegmentParams as TimberSegmentParams[K] extends Record<string, never>'\n );\n lines.push(' ? never');\n lines.push(' : K]: TimberSegmentParams[K];');\n lines.push('} extends infer U');\n lines.push(' ? { [K in keyof U[keyof U]]: U[keyof U][K] }');\n lines.push(' : never;');\n lines.push('');\n\n // RoutesWithParams — filter routes by required param keys\n lines.push(\n '/** Filters TimberRoute to routes whose accumulated params include all listed keys. */'\n );\n lines.push('export type RoutesWithParams<K extends keyof AllSegmentParams> = {');\n lines.push(' [R in TimberRoute]: K extends keyof TimberSegmentParams[R] ? R : never;');\n lines.push('}[TimberRoute];');\n\n return lines;\n}\n\n/**\n * Format the collected routes into a TypeScript declaration file.\n */\nfunction formatDeclarationFile(\n routes: RouteEntry[],\n importBase?: string,\n hasSchema?: boolean,\n appDir?: string\n): string {\n const lines: string[] = [];\n\n lines.push('// This file is auto-generated by timber.js route map codegen.');\n lines.push('// Do not edit manually. Regenerated on build and in dev mode.');\n lines.push('');\n // export {} makes this file a module, so all declare module blocks are\n // augmentations rather than ambient replacements. Without this, the\n // declare module blocks would replace the original module types entirely\n // (removing exports like bindUseQueryStates that aren't listed here).\n lines.push('export {};');\n lines.push('');\n\n if (hasSchema) {\n // Schema-based codegen: import schema and InferCodecType\n // Compute the schema import path relative to the output directory\n const schemaImport =\n appDir && importBase\n ? './' + relative(importBase, join(appDir, 'schema')).replace(/\\\\/g, '/')\n : '../app/schema';\n lines.push(`import type schema from '${schemaImport}';`);\n lines.push(\"import type { InferCodecType, SegmentParamCodec } from '@timber-js/app/params';\");\n lines.push('');\n // Collect all unique bracket keys from routes for key validation\n const allBracketKeys = new Set<string>();\n for (const route of routes) {\n for (const p of route.params) {\n allBracketKeys.add(p.bracketName);\n }\n }\n\n // Augment the ValidDynamicSegmentKeysRegistry so defineSchema constrains keys\n // to known filesystem segments. Unknown keys produce inline TS errors.\n if (allBracketKeys.size > 0) {\n lines.push(\"declare module '@timber-js/app/params' {\");\n lines.push(' interface ValidDynamicSegmentKeysRegistry {');\n for (const key of [...allBracketKeys].sort()) {\n lines.push(` ${JSON.stringify(key)}: true;`);\n }\n lines.push(' }');\n lines.push('}');\n lines.push('');\n }\n // Guard: detect when the schema or params imports silently degraded to\n // `any` because TypeScript could not resolve the import specifier.\n // In a .d.ts an unresolved import does NOT error — every downstream\n // type silently becomes `any`, which satisfies every assertion. Only\n // an explicit IsAny check catches it.\n lines.push('type _IsAny<T> = 0 extends 1 & T ? true : false;');\n lines.push('type _AssertSchemaNotAny<_T extends false = _IsAny<typeof schema>> = true;');\n lines.push('type _AssertCodecTypeNotAny<_T extends false = _IsAny<SegmentParamCodec>> = true;');\n lines.push('');\n // Type-level validation: each schema value must be a Codec or Standard Schema.\n // Running `pnpm run typecheck` will surface errors for invalid values.\n lines.push('type _AssertSchemaValues = {');\n lines.push(\n \" [K in keyof typeof schema['segmentParams']]: typeof schema['segmentParams'][K] extends SegmentParamCodec ? true : ['Error: value for', K, 'is not a valid Codec or Standard Schema'];\"\n );\n lines.push('};');\n // Generic constraint enforces that all values are `true` — if any value is\n // an error tuple, TS reports a real diagnostic instead of silently computing it.\n lines.push(\n 'type _EnforceSchemaValues<_T extends Record<string, true> = _AssertSchemaValues> = true;'\n );\n lines.push('');\n }\n\n // urlPath-keyed emissions use the deduped list (slot pages share their\n // parent's urlPath); segmentPath-keyed emissions below keep all entries.\n //\n // Intercepting subtrees are dropped outright rather than deduped: their\n // computed urlPath is not a route any request can reach, so a path that\n // happens NOT to collide with a real one would otherwise be published as a\n // real route. See `RouteEntry.isInterceptingRoute`.\n const uniqueByUrlPath = dedupeRoutesByUrlPath(\n routes.filter((r) => r.isRoutable && !r.isInterceptingRoute)\n );\n\n lines.push(\"declare module '@timber-js/app' {\");\n lines.push(' interface Routes {');\n\n // TIM-1343: no `searchParams` member. With `params.ts` gone there is no\n // convention file to read a definition from, so the framework has nothing\n // to type it with — and an always-`{}` member is a claim that every route\n // has no search params, which is false. Search-param types now come from\n // the definition object itself, wherever the app chooses to keep it.\n for (const route of uniqueByUrlPath) {\n const paramsType = formatParamsType(route.params, hasSchema);\n\n lines.push(` '${route.urlPath}': {`);\n lines.push(` segmentParams: ${paramsType}`);\n lines.push(` }`);\n }\n\n lines.push(' }');\n\n // When a global schema exists, emit segment param types inside the\n // @timber-js/app module augmentation so that declare module blocks\n // for @timber-js/app/server and @timber-js/app/client can reference\n // AllSegmentParams via `import type { AllSegmentParams } from '@timber-js/app'`.\n if (hasSchema) {\n lines.push('');\n lines.push(...formatSchemaTypes(routes).map((l) => ` ${l}`));\n }\n\n lines.push('}');\n lines.push('');\n\n // useQueryStates + typed Link are urlPath-keyed → deduped list.\n const pageRoutes = uniqueByUrlPath.filter((r) => !r.isApiRoute);\n // getSegmentParams / useSegmentParams are segmentPath-keyed → full list,\n // so slot segments keep their own typed overloads.\n const dynamicRoutes = routes.filter((r) => r.params.length > 0);\n\n // Generate @timber-js/app/server augmentation — typed getSegmentParams\n if (dynamicRoutes.length > 0) {\n lines.push(\"declare module '@timber-js/app/server' {\");\n if (hasSchema) {\n lines.push(\" import type { AllSegmentParams } from '@timber-js/app'\");\n }\n for (const route of dynamicRoutes) {\n const paramsType = formatParamsType(route.params, hasSchema);\n lines.push(\n ` export function getSegmentParams(segmentPath: '${route.segmentPath}'): ${paramsType}`\n );\n }\n lines.push(\n hasSchema\n ? ' export function getSegmentParams(): Partial<AllSegmentParams>'\n : ' export function getSegmentParams(): Record<string, string | string[]>'\n );\n lines.push('}');\n lines.push('');\n }\n\n // Generate overloads for @timber-js/app/client\n\n if (dynamicRoutes.length > 0 || pageRoutes.length > 0) {\n lines.push(\"declare module '@timber-js/app/client' {\");\n lines.push(\" import type { SearchParamsDefinition } from '@timber-js/app/search-params'\");\n if (hasSchema) {\n lines.push(\" import type { AllSegmentParams } from '@timber-js/app'\");\n }\n lines.push('');\n\n // useSegmentParams overloads\n if (dynamicRoutes.length > 0) {\n for (const route of dynamicRoutes) {\n const paramsType = formatParamsType(route.params, hasSchema);\n lines.push(\n ` export function useSegmentParams(segmentPath: '${route.segmentPath}'): ${paramsType}`\n );\n }\n lines.push(\n hasSchema\n ? ' export function useSegmentParams(): Partial<AllSegmentParams>'\n : ' export function useSegmentParams(): Record<string, string | string[]>'\n );\n lines.push('');\n }\n\n // Typed Link overloads — per-route with DIRECT types (no conditionals).\n // Direct types preserve TypeScript's excess property checking.\n //\n // TIM-832: per-route and catch-all are emitted as TWO separate\n // augmentation blocks. Per TS's merging rule \"later overload sets\n // ordered first\", the catch-all block (declared SECOND in this file)\n // ends up FIRST in the merged call-signature list at resolution time,\n // which puts the per-route block LAST — so its error message is the\n // one TypeScript reports when no overload matches. This gives users a\n // clear prop-mismatch error (e.g. \"'string | undefined' is not\n // assignable to 'string | number' on id\") instead of the old\n // confusing \"Type 'string' is not assignable to type 'never'\" cascade.\n if (pageRoutes.length > 0) {\n lines.push(' // Typed Link overloads — per-route (block 1 / emitted first)');\n lines.push(...formatTypedLinkOverloads(pageRoutes, hasSchema));\n lines.push('');\n }\n\n lines.push('}');\n lines.push('');\n }\n\n // TIM-832: catch-all block — emitted as a SEPARATE `declare module`\n // augmentation so TS's \"later overload set first\" rule orders it ahead\n // of the per-route block above at resolution time, leaving per-route as\n // the \"last overload\" whose error TypeScript reports.\n lines.push(\"declare module '@timber-js/app/client' {\");\n lines.push(\" import type { SearchParamsDefinition } from '@timber-js/app/search-params'\");\n lines.push('');\n lines.push(...formatLinkCatchAllOverloads());\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Format the params type for a route entry.\n */\nfunction formatParamsType(params: ParamEntry[], hasSchema?: boolean): string {\n if (params.length === 0) {\n return '{}';\n }\n\n // Without a schema a URL segment is an uninterpreted string — that IS\n // its type. Per-segment codec chains used to narrow it here; TIM-1342\n // deleted them along with params.ts.\n const fields = params.map((p) => {\n const codecType = hasSchema ? buildSchemaParamType(p) : p.type;\n return `${p.name}: ${codecType}`;\n });\n return `{ ${fields.join('; ')} }`;\n}\n\n// TIM-1341: `useQueryStates` no longer has a route-string form, so the\n// generated `.d.ts` emits no overloads for it. Its source signature —\n// `useQueryStates(codecs, options?)` — is fully generic over the codec map\n// and needs no per-route augmentation. Reaching another route's codecs is\n// done by importing that route's `searchParams` definition from its\n// `params.ts` and calling `definition.useQueryStates()`, which is typed by\n// inference and cannot fail at runtime on an unpopulated registry.\n// See design/23-search-params.md §\"Client Access\".\n\n// Link overload formatters and helpers (`formatTypedLinkOverloads`,\n// `formatLinkCatchAllOverloads`, `formatLinkParamsType`,\n// `buildResolvedPattern`, `LINK_BASE_PROPS_TYPE`) were extracted to\n// `./link-codegen.ts` (TIM-835) to keep this file under the 500-line\n// cap. They are imported at the top of this file.\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,SAAgB,qBAAqB,GAAe,UAA2B;CAG7E,OAAO,iDAFK,KAAK,UAAU,EAAE,WAE2B,EAAI,mCADjD,YAAY,EAAE;AAE3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