feat(renderer): let a renderer map route files and set hydration

Merged
KI
11d ago
+1757-31

Problem

A custom renderer could only use Farm's folder routes (page.leaf, layout.leaf) and the literal export const hydrate reading. A library with its own file convention (flat files, index, _layout, a .client suffix) or its own syntax for hydration had no way to tell Farm.

Change

Two build-time hooks on the renderer descriptor, next to its module ids:

defineRenderer({
  name: "leaf",
  // ...vite, server, client, componentExtensions
  routes({ root, defaults }) {
    return {
      dir: "src/app", // optional
      resolve(file) {
        // file: { path, segments, name, extension }
        return defaults.resolve(file) ?? { kind: "page", pattern: "/guides/harvest", hydrate: true };
      },
    };
  },
  hydration: {
    pages: false,
    layouts: false,
    strategy: "visible",
    resolve(source, file) {
      return /\/\/ @hydrate/.test(source) ? { hydrate: true } : undefined;
    },
  },
});
  • routes() maps each file's { kind, pattern } to the name Farm's folders would give it (blog/[slug]/page.leaf). Route matching, layouts, the not-found page, the production route table, and generated route types all reuse the existing parser, while the module path stays the real file. defaults is Farm's folder resolver, so a renderer can keep folders and add its own convention.
  • hydration: for each page and layout, the file's own setting ("use client", hydrate/island exports, or hydration.resolve()) wins, then its route rule, then the renderer's defaults.
  • Fails closed. A bad pattern, a non-root not-found, two files for one kind and pattern, a throwing resolve(), a dir outside the project, or a file whose export and renderer syntax disagree fails the scan. The error names the file and the fix. Descriptor validation reports every bad field at once.
  • Stays in src/app. Route handlers, middleware, metadata files, and @slot folders stay in src/app and are never passed to resolve().
  • Dev. Adding or removing a file under the rules' directory refreshes routes and types. Editing a mapped route file reloads the page. Other files there (stylesheets, components) keep their hot updates.

Safety and compatibility

  • Apps without routes() or hydration keep the existing code paths. resolveFarmRendererRoutes returns null, no hydration scope is registered, and the not-found lookup is unchanged.
  • Additive public API: new optional descriptor fields and new exported types (FarmRendererRoutes, FarmRendererRoute, FarmRendererRouteFile, FarmRendererRoutesContext, FarmRendererRouteKind, FarmRendererHydration, FarmRendererHydrationOptions).
  • Route strategy. A route's page and the hydrating layouts above it share one root. When their strategies disagree, the route hydrates on "load", which is Farm's existing rule. In the example, the root layout.tsx hydrates and declares nothing, so harvest.leaf's // @hydrate interaction hydrates the page but the route loads on "load". The page's own plan still records interaction. This is documented.
  • Overlap with #3147. #3147 changes the example's .leaf markup to {{ }}. Whichever PR merges second must convert the six new src/app/guides/*.leaf files.

Verification

  • pnpm --filter @farm.js/core exec vitest run src/__tests__/renderer-routes.test.ts: 32 passed.
    • It covers mapping, Farm-owned files and slots, defaults, bad rules, duplicates, the route table, rediscovery, route types, every hydration level, conflicts, descriptor errors, and route-file vs. route-module detection.
    • The "use client" default-strategy test fails without its fix and passes with it.
  • pnpm --filter @farm.js/core test: 713 files passed on the first run. The other 54 files failed only because sibling packages weren't built in this worktree (Failed to resolve entry for package "@farm.js/vue", jobs, mcp, otel, and so on), with 2 exceptions in server-renderer-route-states.
    • Those 2 were real failures: partial RouteManager mocks lacked the new method. The not-found lookup now consults the renderer only when it has routes().
    • After building those siblings and making that fix, all 54 files passed (363 tests).
  • pnpm --filter @farm.js/core type-check and pnpm --filter @farm.js/cli type-check: pass.
  • pnpm --filter @farm.js/cli test: 351 passed.
  • pnpm test:renderers: all 7 suites pass.
  • pnpm --filter farm-leaf test: 27 passed. farm-leaf type-check: pass.
  • tests/e2e-custom-renderer with Chrome: 16 passed against farm dev and 16 passed against the node-server production build, including 4 new /guides tests:
    • flat pages inside _layout.leaf
    • generateMetadata on [crop].leaf
    • 404s for _tip, _layout, watering.client, and unknown crops
    • data-farm-client from the .client rule and the pragma, working counters, and client navigation through the guides layout
  • Dev hot updates, checked with a temporary Playwright probe that was not committed:
    • Editing a stylesheet under the rules' directory hot-updates without a reload.
    • Editing a mapped flat page reloads and shows the change.
  • farm generate --check in the example: up to date (/guides, /guides/[crop], /guides/harvest, /guides/watering).
  • oxfmt --check and oxlint on changed files: clean. pnpm docs:check-navigation: pass.
  • CI fix after the first run. scripts/renderer-capability-matrix.test.js loads renderer.ts alone as a data: URL, so the new runtime import from ./island failed on all three Test jobs. renderer.ts now checks strategies against a local Record<FarmIslandStrategy, true>, so a new strategy fails the type-check until it's listed. That test fails at 07fc1d5b3 and passes at e4dbf754c; the root node --test suite: 80 of 81, the other needs a full workspace build.
  • After merging main (#3144 touched 4 of these files): core type-check passes, 95 related core test files pass (922 tests), and tests/e2e-custom-renderer passes 16/16 in dev and in production.
  • The standalone leaf repo: farming-labs/leaf#3 uses both hooks; 32 unit and 17/17 e2e (dev and production) against core and CLI packed from this branch.

Not verified

  • pnpm docs:build.
  • Windows. Path handling uses /-normalized absolute paths, but I didn't run it.
  • Deploy targets other than node-server.
  • A layered app whose layer has its own routes() directory. Unit-level only, via per-source-root scans.

Found, not fixed here (pre-existing on main's descriptor): in farm dev, a custom-renderer app hits a 500 after this sequence: edit a stylesheet that a .tsx layout imports, then edit a page. The error is leaf: useState() can only be called while a component renders. It reproduces without routes().

Documentation and release

  • docs/renderers/custom: new "Route files" and "Hydration" sections, descriptor bullets, and a limit. docs/renderers: cross-link.
  • Example: src/app/guides, the descriptor's routes() and hydration, README, and regenerated src/farm.d.ts.
  • No release-flow changes.

Summary by cubic

Custom renderers can now define their own route file conventions and hydration syntax. Previously a custom renderer could only use Farm's folder routes (page.leaf, layout.leaf) and the literal export const hydrate; now the descriptor accepts two build-time hooks that map files to routes and set hydration defaults.

  • routes(context) returns { dir?, resolve(file) }, mapping each file's { kind, pattern } to the route Farm's folders would name. Route matching, layouts, not-found handling, route tables, and generated route types all reuse the existing parser, while defaults exposes Farm's folder rules so both conventions can coexist.
  • hydration sets page and layout defaults, a default strategy, and resolve(source, file) for a renderer's own syntax. A file's own setting wins over its route rule, which wins over the renderer's defaults; a file whose export and renderer syntax disagree fails the scan.
  • Route rules fail closed: invalid patterns, duplicate routes, throwing resolvers, and directories outside the project produce errors naming the file and the fix.
  • Farm-owned files (route.ts, middleware, metadata files, and @slot folders) stay in src/app and are never passed to resolve(). Adding or removing files in the rules' directory refreshes routes in dev; editing a mapped route file reloads its page.
  • Apps without routes() or hydration keep the existing code paths. The new descriptor fields and exported types are additive. The strategy check lives in renderer.ts without runtime imports, so it keeps working when the file is loaded standalone by the capability matrix test.